简体   繁体   English

C:打印字符数组时出现问题*

[英]C: issue with printing an array of char *

I have an array of char * initialized like this: 我有一个char *数组初始化如下:

char *keys[16]; //16 elements, each of which is a char *

Then I am assigning to this array like this: 然后我将这样分配给该数组:

  for(i = 0; i < NUM_ROUNDS; i++)
  {
     //do some operations that generate a char* holding 48 characters named keyi
     keys[i] = keyi;
  } 

But then when I printout all of the elements of the char * array I am getting junk at the end of the print statement: 但是,当我打印出char *数组的所有元素时,我在print语句的末尾发现垃圾:

  int k;
  for(k = 0; k < 16; k++)
  {
     printf("keys[%d] = %s\n", k,keys[k]);
  }

Output looks like this: 输出看起来像这样:

keys[0] = 000110110000001011101111111111000111000001110010çVTz¸ä
keys[1] = 011110011010111011011001110110111100100111100101çVTz¸ä
keys[2] = 010101011111110010001010010000101100111110011001çVTz¸ä
keys[3] = 011100101010110111010110110110110011010100011101çVTz¸ä
keys[4] = 011111001110110000000111111010110101001110101000çVTz¸ä
keys[5] = 011000111010010100111110010100000111101100101111çVTz¸ä

Any idea what I am doing wrong here? 知道我在这里做错了吗? Should I be allocating memory before assigning to the array ? 我应该在分配给数组之前分配内存吗?

It seems most likely that keyi isn't NUL-terminated. 似乎keyi没有被NUL终止。

Maybe you want this ? 也许你想要这个?

keyi[48] = 0;   /* Caveat, keyi must be at least 49 chars wide. */
keys[i] = keyi;

Or maybe: 或者可能:

printf("keys[%d] = %.48s\n", k,keys[k]);

%s prints the contents untill it encounters a \\0 , Your elements are not \\0 terminated. %s打印内容,直到遇到\\0为止,您的元素不会被\\0终止。
So it prints out the contents until it randomly encounters a \\0 . 因此,它将打印出内容,直到它随机遇到\\0为止。

You should explicitly \\0 terminate your contents. 您应该\\0明确终止您的内容。

You should write a 0 byte onto the end of the 48 character string, or it won't know when to stop printing. 您应该在48个字符串的末尾写一个0字节,否则它将不知道何时停止打印。 Just be sure to allocate 49 bytes to allow for this. 只需确保分配49个字节即可。

Your char* s do not point to NUL-terminated strings. 您的char*不指向NUL终止的字符串。 You need to make keyi 49 bytes long, and put a 0 at keyi[48] . 您需要将keyi 49个字节长,并在keyi[48]放置一个0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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