Answer the question
In order to leave comments, you need to log in
C: passing predefined strings to a function
I always thought that when predefining a string variable *s = "habr"
, and s[] = "habr"
are almost complete synonyms.
Then why in the code below (compiled in GCC, various versions, on Linux) only option I works, while options II and III fail with Segmentation Fault?
// Вариант I
#include <stdio.h>
void test(char *s) {
s[2] = 'X';
puts(s);
}
int main() {
char x[] = "123456";
test(x);
return 0;
}
// Вариант II
#include <stdio.h>
void test(char *s) {
s[2] = 'X';
puts(s);
}
int main() {
char *x = "123456";
test(x);
return 0;
}
// Вариант III
#include <stdio.h>
void test(char *s) {
s[2] = 'X';
puts(s);
}
int main() {
test("123456");
return 0;
}
Answer the question
In order to leave comments, you need to log in
It's the difference between arrays and pointers. Generally speaking, she is.
On initialization
char array[] = "abc" allocates memory for a new string array and sets its elements to "a", "b", "c" and "\0"
char *pointer = "abc" sets the pointer to the string "abc ”, which, generally speaking, can reside (as a string literal) in a protected area of memory (ie read-only).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question