Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I increment an array?

Tags:

arrays

c

pointers

char a[] = "hello";

My understanding is that a acts like a constant pointer to a string. I know writing a++ won't work, but why?

like image 838
Piyush Bhuwalka Avatar asked Dec 14 '22 00:12

Piyush Bhuwalka


1 Answers

No, it's not OK to increment an array. Although arrays are freely convertible to pointers, they are not pointers. Therefore, writing a++ will trigger an error.

However, writing

char *p = a;
p++;

is fine, becuase p is a pointer, with value equal to the location of a's initial element.

like image 101
Sergey Kalinichenko Avatar answered Jan 02 '23 03:01

Sergey Kalinichenko