Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment Char Array Pointer

Tags:

arrays

c

pointers

Is it possible to increment/advance a char array like I can a char pointer?

For example I can do this for a char pointer:

while (*cPtr) 
   printf("c=%c\n", *(cPtr++));

But I am not able to do this:

// char cArray[] = "abcde";
while (*cArray)
   printf("c=%c\n", *(cArray++));  // Compile error: 19 26  [Error] lvalue required as increment operand

The purpose is to be able to iterate over a char array when I dont know the length of the array. My thinking is that I just want to advance till I find a null character I guess unless theres an easier way?

char a[] = "abcde";
int index = -1;

while (a[++index]) 
   printf("c=%c\n", a[index]);
like image 724
sazr Avatar asked May 02 '15 02:05

sazr


1 Answers

Is it possible to increment/advance a char array like I can a char pointer?

Unlike pointers, arrays are not lvalues and you can't modify it. That's a major difference between arrays and pointers.

like image 122
haccks Avatar answered Oct 01 '22 00:10

haccks