L
LaBird
Dear all,
I'd like to ask for the following C code segment:
#include <stdio.h>
int main()
{
char *a = "abc"; /* Line 1 */
printf("%s", a); /* Line 2 */
a[0] = '1'; /* Line 3 */
return 0;
}
The code compiles without warnings and errors,
runs ok until line 3 with "segmentation fault".
However, if Line 1 is changed to:
char a[] = "abc";
The program runs successfully. My question is:
Why char *a = "abc" is allowed, but then a[0] = '1'
will cause a segmentation fault?
Also, if Line 1 is changed to:
char *a = {'a', 'b', 'c', '\0'};
The program has compilation warnings, and the
execution will give segmentation fault on Line 2.
Why this form of initialization is not allowed?
Thanks!
Best Regards,
Benny (LaBird),
email: Remove all numerals to get the valid address.
I'd like to ask for the following C code segment:
#include <stdio.h>
int main()
{
char *a = "abc"; /* Line 1 */
printf("%s", a); /* Line 2 */
a[0] = '1'; /* Line 3 */
return 0;
}
The code compiles without warnings and errors,
runs ok until line 3 with "segmentation fault".
However, if Line 1 is changed to:
char a[] = "abc";
The program runs successfully. My question is:
Why char *a = "abc" is allowed, but then a[0] = '1'
will cause a segmentation fault?
Also, if Line 1 is changed to:
char *a = {'a', 'b', 'c', '\0'};
The program has compilation warnings, and the
execution will give segmentation fault on Line 2.
Why this form of initialization is not allowed?
Thanks!
Best Regards,
Benny (LaBird),
email: Remove all numerals to get the valid address.