简体   繁体   中英

C - Why is this string not being assigned to the variable?

I've been trying to understand why my string/char array loses the value assigned to it in the for loop as soon as the loop ends. The value for token2 is a user input that gets shunted into the "token2" variable earlier on in the code. I have several checks prior to this portion and token2 is populated as expected.

int dayInt2;
char dayToken2[3];

//For loop to parse out the month portion of second token.
for (int i = 3; i < 5; i++)
{
  dayToken2[i] = token2[i];
  printf("For loop parse: %c\n", token2[i]);
}
dayToken2[3] = '\0'; //Add null pointer to the last character space of the string array.

printf("dayToken2 value: %s\n", dayToken2); //Debugging to check the value in dayToken2.

dayInt2 = atoi(dayToken2); //converts day

printf("dayInt2 value: %s\n", dayInt2); //Debugging to check if the string conversion to int worked.
  1. dayToken2[3] is outside the array. The indexes are from zero. So the maximum index is 2 .

  2. printf("dayInt2 value: %s\n", dayInt2); is wrong. You try to print the integer but you say the printf that it should expect the string. It has to be printf("dayInt2 value: %d\n", dayInt2);

  3. dayToken2[i] = token2[i]; is also wrong as i changes from 3 to 4 . It has to be dayToken2[i - 3] = token2[i]; . You can use memcpy for that memcpy(dayToken2, token2 + 3, 2);

When defining your char array, you set the max indices as 3, so there is only dayToken[0], dayToken[1], dayToken[2]. In your for loop you set i from 3-5, try doing from 0-2.

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