+ 2

I have a few doubts related to strings in c. Can any one please help?

1) char a[3] = "ab"; printf("%s",a); Here, array a contains the base address of the first character and point to it. Then why is it possible to print the entire string using array name(here, a)? 2)char a[3] = "abc"; printf("%s",a); Is array a storing a string or is it just an array of characters? How is charater name printing abc as output? 3) char a[ ] = "abc"; Here string gets stored in stack and can be modified. char *p = (char *)malloc(4 * sizeof(char)); String is stored in heap and can be modified. char *x = "abc"; Where is this string getting stored? In stack or heap? And why can't this be modified?

28th Apr 2020, 8:23 PM
Shreyoshi Raychaudhary
1 ответ
+ 3
I'd say the main difference between a character array and a string is that a string is null-terminated. When you pass arrays as arguments to functions, they decay into pointers to the first element. So when passing 'a' to printf() or strlen() they have the start offset and can iterate over the string until they find a null-terminator. If your string is invalid and doesn't have a null-terminator those functions will continue indefinitely or more likely until they find a 0 somewhere in memory. (Buffer overrun). char a[3] = "abc" is a modifiable char array, but would be an invalid string as it doesn't store the null-terminating character at the end due to the size limitation. C is smart enough to append a null-terminator when you assign to character arrays using double quoted "string literals". If you do a[] = { 'a', 'b' }; you'd have to insert a null-terminator yourself to make it a valid string as shown here: a[] = { 'a', 'b', '\0' }; For a fixed size array, you need to the number of characters + an additional char for the null-terminator. a[4] = { 'a', 'b', 'c', '\0' } or a[4] = "abc"; char *x = "abc"; should really be const char *x = "abc" for the reasons you mentioned, it's not modifiable and points to a constant literal in read only memory. Because it has a static storage duration it's stored in memory until the program ends (unlike the stack or heap which can shrink and grow).
28th Apr 2020, 9:19 PM
Damyian G
Damyian G - avatar