Character arrays and pointers
What’s the difference between char s[] and char* s?
‣
As a declaration, none:
int f(char* s)
int f(char s[])
‣
As a definition:
char s[] = “hello”
- Allocates the string in modifiable memory, and defines s to be a pointer to the head of the string.!
- Can change the contents, but s will always point to the same place!
- Can’t write: s = p; an array name is not a variable (i.e., can’t be used as an l-value)!
char* s = “hello”
- Allocates a pointer (freely modifiable)!
- Allocates a string (not modifiable) - typically allocated in the text segment of memory!
- s points to the beginning of the string, but modifications to the string (e.g., *s = ‘x’) is undefined!
- s can be reassigned to point to other strings
7