How can I read triples of numbers from the program arguments into an array of integers and then display them? That is I enter ./read 1,2,3 4,5,6 7,8,9 and the ouptput should be
1 2 3
4 5 6
7 8 9
My code works well only for strings, but not integers
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
int d[argc][3];
int x[3];
for(i = 1; i < argc; i ++){
char *a[3];
int j = 0;
a[j] = strtok(argv[i], ",");
while(a[j] != NULL){
a[++j] = strtok(NULL, ",");
x[j] = atoi(&(a[j]));
}
printf("%s %s %s \n", a[0], a[1], a[2]);
printf("%d %d %d \n", x[0], x[1], x[2]);
}
return 0;
}
It displays 1 0 0 on each line.
,between3,4, but not6 7.int d[argc][3];?x[j] = atoi(a[j]);thena[++j] = strtok(NULL, ",");a[3]is out of bounds.strtok()fails, then this line:x[j] = atoi(&(a[j]));(which is written incorrectly, it should be;x[j] = atoi(a[j]);will be accessing memory at address 0. This is almost certain to result in aaccess violationseg fault event. I.E. always check (!=NULL) the returned value fromstrtok()before de-referencing that value