I'm new at C. Here is a function, one of its' proposes is to fill the sizes, and I have problems with it. I fill it correctly, but then, in perform(), where I call marray_read() from, sizes is filled with zeros.
int64_t** marray_read( size_t* rows, size_t* sizes[] ) {
size_t n = read_size();
*rows = n;
sizes = malloc(n * sizeof(size_t));
int64_t **array = (int64_t **)malloc(n*sizeof(int64_t*));
size_t m = 0;
for (size_t i = 0; i < n; i++) {
m = read_size();
sizes[i] = m;
array[i] = (int64_t *)malloc(m*sizeof(int64_t));
for (size_t j = 0; j < m; j++) {
array[i][j] = read_int64();
}
}
for (size_t i = 0; i < n; i++) {
printf("%zu ", sizes[i]);
}
printf("\n");
return array;
}
void perform() {
size_t rows;
size_t* sizes;
int64_t** marray = marray_read(&rows, &sizes);
for (size_t i = 0; i < rows; i++) {
printf("%zu ", sizes[i]);
}
// Output for rows=3 is: 0 0 0
}
I have already read this, but when I use memcpy(), everything is still ok in marray_read(), but I get Segmentation fault in perform():
int64_t** marray_read( size_t* rows, size_t* sizes[] ) {
size_t n = read_size();
*rows = n;
memcpy(sizes, malloc(n * sizeof(size_t)), (n * sizeof(size_t)));
int64_t **array = (int64_t **)malloc(n*sizeof(int64_t*));
size_t m = 0;
for (size_t i = 0; i < n; i++) {
m = read_size();
sizes[i] = m;
array[i] = (int64_t *)malloc(m*sizeof(int64_t));
for (size_t j = 0; j < m; j++) {
array[i][j] = read_int64();
}
}
for (size_t i = 0; i < n; i++) {
printf("%zu ", sizes[i]);
}
printf("\n");
return array;
}
void perform() {
size_t rows;
size_t* sizes;
int64_t** marray = marray_read(&rows, &sizes);
for (size_t i = 0; i < rows; i++) {
printf("%zu ", sizes[i]);
}
// Output: Segmentation fault
}
I need to realise this function without memcpy(), but I'm interested in any way to do it.