I have this function that has to read from a csv. It does but when i try to print the value in the main after read_csv
without returning a void**
, throw segv. Instead, if i return the array and print the value as it is now the main, it works correctly. So, Why aren't changes made inside functions persisted in main?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NITEMS 7
#define SIZE sizeof(Data)
#define K 5
typedef struct _data
{
int id;
char field1[50];
int field2;
float field3;
}Data;
void ** read_csv(void **array, const char *filename){
int capacity = 1, size = 0;
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("errore");
return NULL;
}
Data *row;
while (!feof(file)){
row = malloc(sizeof(Data));
if (row == NULL) {
printf("Unable to allocate new row!");
exit(EXIT_FAILURE);
}
fscanf(file,"%d,%49[^,],%d,%f\n",&row->id,&row->field1,&row->field2,&row->field3);
if (size >= capacity) {
capacity = 2 * capacity;
array = (void **)realloc(array, capacity * sizeof(void**));
}
array[size] = row;
size++;
printf("\n\n%d", ((Data*)array[0])->id);
}
fclose(file);
return array;
}
int main(int argc, char const *argv[])
{
if(argc < 3){
printf("\n Please make sure that each file is inserted in correct way: \n ./main first(csv) second (ordered csv) third(k) fourth(field)\n\n");
exit(EXIT_FAILURE);
}
void ** array = malloc(sizeof(void **));
if(array == NULL)
exit(EXIT_FAILURE);
// read_csv(array,argv[1]) --> this don't mantain the changes
array = read_csv(array, argv[1]); // this yes
return 0;
}