Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C strings pointer vs. arrays [duplicate]

Tags:

c

Possible Duplicate:
What is the difference between char s[] and char *s in C?

Why is:

char *ptr = "Hello!"

different than:

char ptr[] = "Hello!"

Specifically, I don't see why you can use (*ptr)++ to change the value of 'H' in the array, but not the pointer.

Thanks!

like image 232
John McGee Avatar asked Jul 08 '10 19:07

John McGee


2 Answers

You can (in general) use the expression (*ptr)++ to change the value that ptr points to when ptr is a pointer and not an array (ie., if ptr is declared as char* ptr).

However, in your first example:

char *ptr = "Hello!"

ptr is pointing to a literal string, and literal strings are not permitted to be modified (they may actually be stored in memory area which are not writable, such as ROM or memory pages marked as read-only).

In your second example,

char ptr[] = "Hello!";

The array is declared and the initialization actually copies the data in the string literal into the allocated array memory. That array memory is modifiable, so (*ptr)++ works.

Note: for your second declaration, the ptr identifier itself is an array identifier, not a pointer and is not an 'lvalue' so it can't be modified (even though it converts readily to a pointer in most situations). For example, the expression ++ptr would be invalid. I think this is the point that some other answers are trying to make.

like image 85
Michael Burr Avatar answered Sep 28 '22 08:09

Michael Burr


When pointing to a string literal, you should not declare the chars to be modifiable, and some compilers will warn you for this:

char *ptr = "Hello!"    /* WRONG, missing const! */

The reason is as noted by others that string literals may be stored in an immutable part of the program's memory.

The correct "annotation" for you is to make sure you have a pointer to constant char:

const char *ptr = "Hello!"

And now you see directly that you can't modify the text stored at the pointer.

like image 22
u0b34a0f6ae Avatar answered Sep 28 '22 09:09

u0b34a0f6ae