简体   繁体   中英

char arrays in c end char

I'm reading from a socket into a char array and I want to know when to stop reading. The terminating char sequence is '\\r\\n\\r\\n'. If what I read in is smaller than the array size I don't want to loop around anymore. My question is really if I load into the array say 10 characters and it has length 20, what is the array[20] index set to?

Thanks

edit:

Sorry I did mean array[19], setting the last index to NULL as suggested? seems like an appropriate solution. To give some more detail, I need to know when all the data has been read from the socket. I don't know the size of the data to be sent only that it terminates with '\\r\\n\\r\\n'

If it has length 20, then array[20] is outside your array and shouldn't be accessed like that (unless you want to do some sort of wizardy and hacking beyond your explanation).

EDIT: If you meant array[19], then no. You need to set the NUL character at array index = size of string received. ASCII NUL character '\\0' is not C NULL constant, which for 32-bits machines would be 4-byte long, and that would potentially overwrite data.

My question is really if I load into the array say 10 characters and it has length 20, what is the array[20] index set to?

It's not set to anything. Feel free to set it to something yourself (for instance, a null terminator).

Generally in the name of efficiency C does not initialize an array to any known value, so you'll get whatever was leftover in memory.

You can explicitly initialize the array to fix this. A common initialization for a sequence of bytes is zero, which won't match your search string and will act as and end-of-string if you try to process the array as a string.

char array[20] = {0}; /* the extra elements are always initialized to 0 as well */
char array2[20];
memset(array2, 0, sizeof(array2));

I'll presume you had a typo and meant array[19] instead of array[20] .

In C, when the array is malloced, the array has whatever is leftover in the malloced chunk of memory. If you copy several chars into the array and want the chars to be read as a string, you have to set the next char after the last char to be '\\0'.

由于您知道何时停止读取,因此可以将数组中的下一个字符设置为'\\0'以标记字符串的结尾。

To the best of my knowledge, the ANSI C standard does not describe what value should be allocated to uninitialized arrays. Consider it to be garbage and assume that nothing can be said about it. Although, I have mostly observed them to be 0 (using gcc). This implementation may vary across compilers.

Also, this value could depend on the previous steps which have modified array[19] (as mOskitO pointed out, array[20] is out of bounds).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM