Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pointer and array [duplicate]

Tags:

c++

c

Possible Duplicates:
Difference between char *str=“STRING” and char str[] = “STRING” ?
C: differences between pointer and array

Hi,

Can anybody tell me the difference between the statements below?

char *p = "This is a test";

char a[] = "This is a test";
like image 883
Umesha MS Avatar asked Feb 22 '11 13:02

Umesha MS


3 Answers

When you declare char p[] you are declaring an array of chars (which is accessible to be both read and written), and this array is initialized to some sequence of characters i.e. "This is test" is copied to the elements in this array.

When you declare char* p, you are declaring a pointer that points directly to some constant literal - not a copy. These can only be read.

like image 61
DanS Avatar answered Nov 14 '22 06:11

DanS


a is an array which means that you can use the sizeof() operator on a and sizeof(a)/sizeof(a[0]) is equal to the array length.

p is a pointer to a constant memory zone.

like image 21
Benoit Avatar answered Nov 14 '22 06:11

Benoit


1 - pointer which points to the read only section of the program containing "This is test\0" string.

2 - memory (13 bytes) which is initialized with contents mentioned above.

like image 3
XAder Avatar answered Nov 14 '22 06:11

XAder