I have been working on some code that tokenizes a string from a line and then creates a temp array to copy the string into it (called copy[]) and it is filled with 0's initially (The end game is to split this copy array into temp arrays of length 4 and store them in a struct with a field char* Value). For some reason my temp arrays of size 4 end up having a size of 6.
char* string = strtok(NULL, "\"");
printf("%s", string);
int len = (int)strlen(string);
while(len%4 != 0) {
len++;
}
char copy[len];
for(int i = 0; i < len; i++){
copy[i] = '0';
}
printf("%s\n", copy);
int copyCount = 0;
int tmpCount = 0;
char temp[4];
while (copyCount < len) {
if(tmpCount == 4) {
tmpCount = 0;
}
while(tmpCount < 4) {
temp[tmpCount] = copy[copyCount];
tmpCount++;
copyCount++;
}
printf("%s %d\n", temp, (int)strlen(temp));
}
This yields:
This is the end
0000000000000000
This is the end0
This� 6
is � 6
the � 6
end0� 6
And should yield:
This is the end
0000000000000000
This is the end0
This 4
is 4
the 4
end0 4
I've been messing around with this for awhile and can't seem to figure out why its making temp have a length of 6 when I set it to 4. Also I'm not sure where the random values are coming from. Thanks!
char copy[len];is valid C code nowadays, even in the middle of a function like this.