Simple C array declaration / assignment question

后端 未结 9 1940
醉话见心
醉话见心 2021-01-05 06:13

In higher level languages I would be able something similar to this example in C and it would be fine. However, when I compile this C example it complains bitterly. How can

9条回答
  •  感情败类
    2021-01-05 06:51

    There is also this... :)

    char S[16]="";
    strncpy(S,"Zoodlewurdle...",sizeof(S)-1);
    

    Test what happens if you declare S[8] or S[32], to see why this is so effective.

    I wrote my own string functions based on the logic of OpenBSD's strlcpy, aimed at ensuring a terminator byte MUST exist in the event of overflow, and standard strncpy won't do this so you have to watch carefully how you use it.

    The method above is effective because the ="" at declaration ensures 0 bytes throughout, and sizeof(S)-1 ensures that if you overdo the quoted string passed to strncpy, you get truncation and no violation of the last 0 byte, so this is safe against overflow now, AND on accessing the string later. I aimed this at ANSI C so it ought to be safe anywhere.

提交回复
热议问题