2

I am trying to understand how pointer incrementing and dereferencing go together, and I did this to try it out:

#include <stdio.h>
int main(int argc, char *argv[])
{
    char *words[] = {"word1","word2"};
    printf("%p\n",words);
    printf("%s\n",*words++);
    printf("%p\n",words);
    return 0;
}

I expected this code to do one of these:

  1. First dereference then increase the pointer (printing word1)
  2. First dereference then increase the value (printing ord1)
  3. Dereference pointer + 1 (printing word2)

But compiler won't even compile this, and gives this error: lvalue required as increment operand am I doing something wrong here?

yasar
  • 13,158
  • 28
  • 95
  • 160

4 Answers4

2

You need to put braces around the pointer dereference in the second printf, e.g.:printf("%s\n",(*words)++); Also, if you're attempting to get number 2 in your list there, you need to use the prefix increment rather than postfix.

thelazydeveloper
  • 3,598
  • 2
  • 19
  • 12
  • I gave you +1, but it might be helpful to explain the precedence issue, or at least point to a source that illustrates it. – jpm Apr 14 '12 at 02:17
2

You cannot increment an array, but you can increment a pointer. If you convert the array you declare to a pointer, you will get it to work:

#include <stdio.h>
int main(int argc, char *argv[])
{
    const char *ww[] = {"word1","word2"};
    const char **words = ww;
    printf("%p\n",words);
    printf("%s\n",*words++);
    printf("%p\n",words);
    return 0;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

words is the name of the array, so ++ makes no sense on it. You can take a pointer to the array elements, though:

for (char ** p = words; p != words + 2; ++p)
{
    printf("Address: %p, value: '%s'\n", (void*)(p), *p);
}

Instead of 2 you can of course use the more generic sizeof(words)/sizeof(*words).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

The problem is with this line:

printf("%s\n",*words++);

It is read as *(words++), i.e. increment a block of memory. That doesn't make sense, it is a bit like trying to do:

int a = 1;
(&a)++; // move a so that it points to the next address

which is illegal in C.

The problem is caused by the distinction between arrays and pointers in C: (basically) an array is a block of memory (allocated at compile time), while a pointer is a pointer to a block of memory (not necessarily allocated at compile time). It is a common trip-up when using C, and there are other question on SO about it (e.g. C: differences between char pointer and array).

(The fix is described in other answers, but basically you want to use a pointer to strings rather than an array of strings.)

Community
  • 1
  • 1
huon
  • 94,605
  • 21
  • 231
  • 225