I'm trying to put the elements from a .csv file to a 2 dimensional array. Here is the code I've wrote so far.
#include <string.h>
#include <stdio.h>
#define MAX_SIZE 200
char* data[33][13]={0};
int i = 0;
int j = 0;
void passDataToArray()
{
const char* fileName = "input.csv";
char wordsArray[MAX_SIZE];
char* wordToken;
FILE* inputFile = fopen(fileName, "r");
if (!inputFile)
{
printf("error: could not parse file %s\n", fileName);
}
while (fgets(wordsArray, sizeof(wordsArray), inputFile))
{
char* duplicatedArray = strdup(wordsArray);
while(wordToken = strsep(&duplicatedArray, ",")) {
//printf("%s ", wordToken);
j++;
if(j==13){
//printf("\n%d ", i);
i++;
j=0;
}
data[i][j]=wordToken;
}
}
fclose(inputFile);
}
void printData(){
for(i = 0; i < 33; i++) {
for(j = 0; j < 13; j++) {
printf("%s ", data[i][j]);
}
printf("\n");
}
}
int main()
{
passDataToArray();
printData();
}
How I can print the data without any problem but can't store them in array?
Btw I'm getting segfault for the code above. I assume that it's probably because of this line
data[i][j]=wordToken;
1) Am I doing sth wrong with the definitions of the variables?
2) What is the point of storing the pointers in an array? Obviously I'm doing that wrong as well but how that helps me to save the strings in the data?
3) Is it possible just passing the words as String to a 2 dimensional array?
I would appreciate some help. Thanks.