Tuesday, 15 September 2015

In C, char array and string array in c shows different size, but when compared they are same -


In the attempt of four arrays in C, I came up with this problem.

  void main () {four buffers [5] = {'s', 'd', 'f', 'd', 'f'}; Four [5] = "SDFDF"; Printf ("% d \ n", * A == * buffer); Printf ("% s \ n", buffer); Printf ("% d \ n", (int) string (buffer)); Printf ("% d \ n", (int) string (a)); }  

is output

  1 sdfdf sdfdf 5 6  

The main problem is that '\ 0' , correctly defines 5 character string and To get started with the initial list, it should be

  four buffer [6] = {'s', 'd', 'f', such as  char  From an array, 'D', 'F', '\ 0'};   

The second version in your code is incorrect because the array can only store 5 characters, again

  char a [6] = "SDFDF"; Instead of 5 * /  

/ * ^ 6 you can not expect any work after that part of the code to work, when you have lost '\ 0 '.

printf () with "% s" spcifier and strlen () expect previous special value '\ 0' or 0 if you want, to stay there, when it is not, then these functions apply undefined behavior because they go beyond the end of the array There are '\ 0' . Searching for


No comments:

Post a Comment