Assigning a string of characters to a char array

前端 未结 6 882
半阙折子戏
半阙折子戏 2020-12-03 03:14

I Want to know why the first statements works and why not second one in c++

char a[10]=\"iqbal\";  // it works

a=\"iqbal\"; // does not work 
6条回答
  •  独厮守ぢ
    2020-12-03 03:45

    The char array a will be static and can not be changed if you initialize it like this. Anyway you can never assign a character string a="iqbal" in c. You have to use strncpy or memcpy for that. Otherwise you will try to overwrite the pointer to the string, and that is not what you want.

    So the correct code would do something like:

    char a[10];
    strncpy(a, "iqbal", sizeof(a) - 1);
    a[sizeof(a) - 1] = 0;
    

    The -1 is to reserve a byte for the terminating zero. Note, you will have to check for yourself if the string is null terminated or not. Bad api. There is a strlcpy() call that does this for you but it is not included in glibc.

提交回复
热议问题