我需要制作一个可以接受一维数组和二维数组的函数。我还需要使用单个指针作为此函数的参数来做到这一点。
如果有人要问,我用双指针作为函数matrix
的参数解决了我的问题,但是现在我不得不以其他方式做到这一点。
我在考虑传递指针数组,并在我的函数中将(行的)每个指针分配给临时的一维数组。我不熟悉C语言,所以也许我犯了一些愚蠢的错误,但是我相信tmpTab = &tab[i];
这行代码应该可以工作,但是不能,因为我在输出时会遇到垃圾。
void matrix(double* tab, int n, int l) {
int count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
int i, j, isCol = 1, isRow = 1;
double *tmpTab;
if (l >= n || l < 0) { isRow = 0; }
if (l >= n || l < 0) { isCol = 0; }
for (i = 0; i < n; i++) {
tmpTab = &tab[i];
for (j = 0; j < n; j++) {
printf("\n%i: %lf", j, tab[j]);
if (tab[j] < S || tab[j] > E) count1++;
if (isRow && i == l && tab[j] >= S && tab[j] <= E) count2++;
if (isCol && j == l && tab[j] >= S && tab[j] <= E) count3++;
if (i == j && tab[j] >= S && tab[j] <= E) count4++;
if (i > j && tab[j] >= S && tab[j] <= E) count5++;
if (i + j == n - 1 && tab[j] >= S && tab[j] <= E) count6++;
}
}
}
分配我的数组的函数:
double **allocate_array(int n) {
double **tab;
tab = (double **)malloc(sizeof(double) * n);
for (int i = 0; i < n; i++) {
tab[i] = (double *)malloc(sizeof(double) * n);
}
return tab;
}
主要:
int main()
{
double **tab;
tab = read_array("dane.txt", &N);
print_array(tab, N);
matrix((double *)tab, N, 2);
}
从文件读取正常,print_array也正常。 这是我的研究计划的输出。
3.30 2.30 2.10 3.30 3.40 3.30 2.30 2.10 3.30 3.40 3.30 2.30 2.10 3.30 3.40 3.30 2.30 2.10 3.30 3.40 3.60 2.60 2.60 3.60 3.50 0: 0.000000 1: 0.000000 2: -6277435991103237715486889255272272650483169294881725067238215516160.000000 3: -6277438562204192487878988888393020692503707483087375482269988814848.000000 4: -6277438562204192487878988888393020692503707483087375482269988814848.000000 0: 0.000000 1: 0.000000 2: -6277435991103237715486889255272272650483169294881725067238215516160.000000 3: -6277438562204192487878988888393020692503707483087375482269988814848.000000 4: -6277438562204192487878988888393020692503707483087375482269988814848.000000 0: 0.000000 1: 0.000000 2: -6277435991103237715486889255272272650483169294881725067238215516160.000000 3: -6277438562204192487878988888393020692503707483087375482269988814848.000000 4: -6277438562204192487878988888393020692503707483087375482269988814848.000000 0: 0.000000 1: 0.000000 2: -6277435991103237715486889255272272650483169294881725067238215516160.000000 3: -6277438562204192487878988888393020692503707483087375482269988814848.000000 4: -6277438562204192487878988888393020692503707483087375482269988814848.000000 0: 0.000000 1: 0.000000 2: -6277435991103237715486889255272272650483169294881725067238215516160.000000 3: -6277438562204192487878988888393020692503707483087375482269988814848.000000 4: -6277438562204192487878988888393020692503707483087375482269988814848.000000