Assigning strings to arrays of characters

后端 未结 9 1376
小鲜肉
小鲜肉 2020-11-22 15:03

I am a little surprised by the following.

Example 1:

char s[100] = \"abcd\"; // declare and initialize - WORKS

Example 2:



        
相关标签:
9条回答
  • 2020-11-22 15:40
    1    char s[100];
    2    s = "hello";
    

    In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.

    0 讨论(0)
  • 2020-11-22 15:41

    To expand on Sparr's answer

    Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.

    Think of it like this:

    Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.

    Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.

    PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++

    0 讨论(0)
  • 2020-11-22 15:41

    What I would use is

    char *s = "abcd";
    
    0 讨论(0)
  • 2020-11-22 15:44

    There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character \0. Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x[] = {'h','e','l','l','o','\0'};

    The correct way would be:

    char s[100];
    strncpy(s, "hello", 100);
    

    or better yet:

    #define STRMAX 100
    char    s[STRMAX];
    size_t  len;
    len = strncpy(s, "hello", STRMAX);
    
    0 讨论(0)
  • 2020-11-22 15:49

    Note that you can still do:

    s[0] = 'h';
    s[1] = 'e';
    s[2] = 'l';
    s[3] = 'l';
    s[4] = 'o';
    s[5] = '\0';
    
    0 讨论(0)
  • 2020-11-22 15:51

    You can use this:

    yylval.sval=strdup("VHDL + Volcal trance...");
    

    Where yylval is char*. strdup from does the job.

    0 讨论(0)
提交回复
热议问题