Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I recently came across the below code where macro is defined as below

unsigned char cbuf[10];
#define pbuf() (&cbuf[0])

Can anyone please explain what is being done in the #define(macro definition) line?

share|improve this question
 
well, pbuf() is being defined to (&cbuf[0])... –  H2CO3 Nov 2 '12 at 7:41
3  
This macro has no purpose but to obfuscate the code, don't use it. –  Lundin Nov 2 '12 at 7:45

2 Answers

When ever code contains pbuf(), preprocessor (which is run before actually compiling) replaces that with (&cbuf[0]), basically changing the source code fed to the actual compiler.

So, the intention of the macro is to give address of first element of cbuf variable (what ever that variable is in current scope, since preprocessor really just does "string replace" without no idea of context). It is a bit redundant, since name of the array is also address of it's first element...

In other words, where ever you would use pbuf(), just write cbuf directly.

share|improve this answer
 
somewhere else in the code pbuf()[2], pbuf()[3] are also accessed. If the address of the first element is given to pbuf(), then how come the above two are possible. –  user1611753 Nov 2 '12 at 7:47
 
@user1611753 In C, pointer can be used as an array. That is, int *foo; foo[index]=value; is valid. Also works the other way, int a[5]; int *ip = a; is valid, array variable name works much like a pointer. Pointer to an array is exactly same as pointer to first element of the array, and can be used interchangeably. –  hyde Nov 2 '12 at 7:50
 
...this is why it is said, that C does not have real arrays. C arrays are basically just syntactic sugar around pointers. If you are passing arrays of variable length around, you have to tell the length separately (either other parameter, or some array end marker, like 0 byte with C strings, and often a NULL pointer at last element in case of pointer arrays which do not otherwise contain NULLs. –  hyde Nov 2 '12 at 7:56

Rewind pointer

#include <stdio.h>

unsigned char cbuf[10];
#define pbuf (&cbuf[0]) /* Note that () is not necesary */

int main(int argc, char *argv[])
{
   unsigned char *p = pbuf; /* p points to &cbuf[0] */
   int i;

   for (i = 0; i < 3; i++) {
      *p++ = 'a' + i; /* p points to &cbuf[i] */
   }
   p = pbuf; /* p points to &cbuf[0] again */
   printf("%c\n", *p);
   return 0;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.