It is my code for working with two dimensional arrays.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
void print_array(double ** m, int n)
{
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("%.2f ", m[i][j]);
printf("\n");
}
return;
}
double ** allocate_array(int n)
{
double ** m = (double **)calloc(sizeof(double *), n);
int i;
for (i = 0; i < n; i++)
m[i] = (double *)calloc(sizeof(double), n);
return m;
}
void free_array(double ** m, int n)
{
int i;
for (i = 0; i < n; i++)
free(m[i]);
free(m);
return;
}
// array_sum(result, sum1, sum2, dimensions)
void array_sum(double ** sum, double ** x1, double ** x2, int n)
{
double **s;
s = allocate_array(n);
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
s[i][j] = x1[i][j] + x2[i][j];
memcpy(sum, s, sizeof(**s)*n);
free_array(s, n);
printf("hhh\n");
print_array(sum, n);
return;
}
int main()
{
int n;
FILE* f;
f = fopen("array.txt", "r");
fscanf(f, "%d", &n);
double **m;
m = allocate_array(n);
int i; int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
fscanf(f, "%lf", &m[i][j]);
//print_array(m, n);
double **k;
k = allocate_array(n);
array_sum(k, m, m, n);
//print_array(k, n);
free_array(m, n);
return 0;
}
Why freeing of s results that sum also freed and as result function doesn't return correct result? What I am should use for modifying objects like arrays os structs in function through pointer?
答案 0 :(得分:2)
对于初学者这个陈述
memcpy(sum, s, sizeof(**s)*n);
^^^^^^^^^^^
无效。
应该看起来像
memcpy(sum, s, sizeof( *s ) * n);
^^^^^^^^^^^^
此语句将指向s的数组中的指针复制到sum指向的数组。
然而在此声明之后
free_array(s, n);
这些指针变得无效,因为这些指针所指向的内存已被释放。
考虑到您分配了占用不同内存范围的n + 1个数组,并且无法使用memcpy
复制所有这些数组。
只需写下
void array_sum(double ** sum, double ** x1, double ** x2, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
sum[i][j] = x1[i][j] + x2[i][j];
printf("hhh\n");
print_array(sum, n);
}
另外你应该添加声明
free_array(k, n);
主要是由k ..指向的空闲分配数组。