My string in c looks like this, it contains 9 numbers each separated by a comma like
91,86,94,12,54,88,79,58,66
and a two dimension array with three ROWS and three COLS, I wish to assign these numbers to the array up to the last index of the two dimension array, I have tried the code below but when i print the elements of the matrix afterwards, I see crazy numbers;
CODE
char* replaced="91,86,94,12,54,88,79,58,66";
//Define the two dimension array
int ROWS=3;
int COLS=3;
//assign memory to the array
int (*matrix_array)[ROWS] = malloc(sizeof(int[ROWS][COLS]));
//initialize all members to zero
memset(matrix_array,0,sizeof (matrix_array));
//split the string into tokens
char delim[2]=",";
//ge the first token
char* token= strtok(replaced,delim);
//get the remaining tokens
for(int i=0;i<ROWS;i ){
for(int j =0;j<COLS;j ){
while(token!=NULL){
//parse an integer out of the token
int sub=atoi(token);
//assign the number to the array
matrix_array[i][j]=sub;
//update the token for the while loop
token=strtok(NULL,delim);
}
}
}
However when I use the code below on the matrix_array to check the assignment, I see big numbers , please help
for(int row=0;row<ROWS;row ){
for(int col=0;col<COLS;col ){
printf("%d\n",matrix_array[row][col]);
}
}
CodePudding user response:
You're consuming all your tokens on the first-row/first-column cell. From there on out, there are no more token. the biggest hint of this is that the last value in the input is the only value that appears to have actually been parsed, and its in [0][0].
Fixing that, and a plethora of other issues:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char replaced[] = "91,86,94,12,54,88,79,58,66";
// Define the two dimension array
int ROWS = 3;
int COLS = 3;
// initialize all members to zero
int(*matrix_array)[COLS] = calloc(ROWS, sizeof *matrix_array);
// split the string into tokens
char delim[] = ",";
// ge the first token
char *token = strtok(replaced, delim);
// get the remaining tokens
for (int i = 0; token && i < ROWS; i )
{
for (int j = 0; token && j < COLS; j )
{
matrix_array[i][j] = atoi(token);;
token = strtok(NULL, delim);
}
}
for (int row = 0; row < ROWS; row )
{
for (int col = 0; col < COLS; col )
{
printf("%d ", matrix_array[row][col]);
}
fputc('\n', stdout);
}
free(matrix_array);
return EXIT_SUCCESS;
}
Output
91 86 94
12 54 88
79 58 66
Frankly, I'd also use strtol to convert your values, but I leave that as an exercise to you.
