Article 4XKN6 A question about C character arrays

A question about C character arrays

by
jsbjsb001
from LinuxQuestions.org on (#4XKN6)
I've been doing some practice with character arrays, and using them the copy some strings. While I've found a way to fix the issue I've been coming across; I've been getting garbage printed at the end of the string when I print it out with printf.

While I've done some searches to try and find out more; I'm still not quite sure what the actual problem is. I'm thinking my for loop to count the number of array elements is causing undefined behaviour, and that's the reason for the garbage being printed out. I looked at this link, and this link, and that's what it seems to suggest as far as I can tell. But again, I'm still not quite sure I'm thinking right about the issue.

When I use the commented out sizeof line below instead of the for loop (or hardcoding the number "5" in the last for loop's condition), that does seem to fix the problem. But I would like to be clear on what the problem actually is to begin with.

Basically, using a for loop to count the number of array elements or hardcoding the number "5" into the last for loop's condition (but doesn't seem to do it for less than 4 or whatever else), and using the string "Hello" to copy into another array, printf prints "Hello@" instead of just "Hello". But it only seems to do it if I only copy from the first array (the string1 array) though.

Here's my code;

Code:#include <stdio.h>

int main(void) {

const char string1[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
const char string2[] = { ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0' };
char constrings[15];
int i, j, c, row = 0;
char letter[10];

for ( int k = 0; string1[k] != '\0'; ++k ) {
row = string1[k];
row = k + 1;
}

// row = sizeof(string1)/sizeof(char);
// row -= 1;

printf("Number of elements for string1 array: %i\n", row);

for ( i = 0; i < row; ++i ) {
constrings[i] = string1[i];
}

for ( j = 0; j < 7; ++j ) {
constrings[row + j] = string2[j];
}
printf("\n%s\n", string1);

for ( c = 0; c < 5; ++c ) {
letter[c] = string1[c];
printf("c = %i letter[%c] ? %s\n", c, letter[c], c < 5 ? "True" : "False");
}
printf("\nletter[] = %s\n", letter);
printf("letter[5] = %c\n", letter[5]);

printf("\n%s\n", constrings);

return 0;
}And here's the output:

Code:james@jamespc: practice> ./constring
Number of elements for string1 array: 5

Hello
c = 0 letter[H] ? True
c = 1 letter[e] ? True
c = 2 letter[l] ? True
c = 3 letter[l] ? True
c = 4 letter[o] ? True

letter[] = Hello@
letter[5] = @

Hello World!latest?d=yIl2AUoC8zA latest?i=oOa2n30DDt0:CP8xI22PMKY:F7zBnMy latest?i=oOa2n30DDt0:CP8xI22PMKY:V_sGLiP latest?d=qj6IDK7rITs latest?i=oOa2n30DDt0:CP8xI22PMKY:gIN9vFwoOa2n30DDt0
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments