difference fixed width strings and zero-terminated strings

后端 未结 3 1750
轮回少年
轮回少年 2020-12-10 21:16

gcc 4.4.4 c89

I got into a recent discussion about \"fixed width strings\" and \"zero terminated strings\".

When I think about this. They seem to be the same

3条回答
  •  轮回少年
    2020-12-10 21:44

    First of all, I think you mean fixed length string, not fixed with string.

    Second, the above is a null terminated string. It shouldn't be changed because of its definition as a literal constant.

    AFAIK C doesn't have any real "fixed length strings". At best, you could define a buffer of size N and place no more than N-1 characters in it, where placing more would be an error and forgetting the null terminator can be an error.

    As for strncpy, what it does is that it copies the specified number of characters, and zero pads the rest. This means that if the destination is not long enough, you would either be writing past the available space, or would not have a null terminator to your string, leading to errors when you attempt to use the string.

提交回复
热议问题