Hunter McMillen
Hunter McMillen

Reputation: 61515

C: issue with printing an array of char *

I have an array of char * initialized like this:

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:

  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 ?

Upvotes: 0

Views: 183

Answers (4)

cnicutar
cnicutar

Reputation: 182609

It seems most likely that keyi isn't NUL-terminated.

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]);

Upvotes: 4

jpalecek
jpalecek

Reputation: 47762

Your char*s do not point to NUL-terminated strings. You need to make keyi 49 bytes long, and put a 0 at keyi[48].

Upvotes: 1

James M
James M

Reputation: 16718

You should write a 0 byte onto the end of the 48 character string, or it won't know when to stop printing. Just be sure to allocate 49 bytes to allow for this.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206508

%s prints the contents untill it encounters a \0, Your elements are not \0 terminated.
So it prints out the contents until it randomly encounters a \0.

You should explicitly \0 terminate your contents.

Upvotes: 2

Related Questions