I need to create a string of arrays from a string input in different iterations. This string of arrays will be passed to a separate function in each iteration. The string input will be of the form 'A a,b,c,d,e,f,g,h' , basically 'A' followed by 8 comma separated string values. The code I wrote for this is -
#include <stdio.h>
#include <string.h>
int main() {
while (1) {
char x[100];
fgets(x, sizeof(x), stdin); // read string
if (x[0] == 'A') {
int k = 2; // index of 1st required value
char temp[8][25];
for (int i = 0; i < 8; i = i + 1) {
int temp2 = k;
while ((x[k] != ',') && (x[k] != '\n')) {
k = k + 1; // find no. of characters in one particular value
}
strncpy(temp[i], &x[temp2], k - temp2); // copy required characters into temp
k = k + 1;
}
printf("%s",temp[0]);
}
else break;
}
return 0;
}
Problems-
1 - If I input 'A a,a,a,a,a,a,a,a' then temp[0] stores 'a~j' or some other random characters after the a. These random characters pop up in other temps too for different input strings (in Codeblocks)
2 - If in one iteration input is 'A abc,a,a,a,a,a,a,a' and in second it is 'A fg,a,a,a,a,a,a,a' then temp[0] goes from 'abc' to 'fgc' instead of 'fg' (Codeblocks)
Codeblocks and Visual Studio printed quite different strings in the print statement. Is it possible to deal with these problems so that I have a string of arrays in each iteration depending on the string input? Does the problem lie with strncpy? Is malloc a better way? Any help is appreciated.