A
A
Alexander Borzunov2011-08-29 19:50:44
C++ / C#
Alexander Borzunov, 2011-08-29 19:50:44

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;
}


Perhaps this is something elementary for the language, but I myself did not figure it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Livid, 2011-08-29
@hx0

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 question

Ask a Question

731 491 924 answers to any question