我有功能和主要
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>
setArray(double *thearray){
*thearray[0][0] = 2.0;
*thearray[0][1] = 2.0;
*thearray[1][0] = 2.0;
*thearray[1][1] = 2.0;
}
void main(){
double myarray[2][2];
setArray(&myarray);
}
我无法在 setArray
函数上指定数组的大小,因为我不知道它会是什么。我需要填充这个特定函数中的数组,但我不能。得到错误:
test.c: In function ‘setArray’:
test.c:8:13: error: subscripted value is neither array nor pointer nor vector
test.c:9:13: error: subscripted value is neither array nor pointer nor vector
test.c:10:13: error: subscripted value is neither array nor pointer nor vector
test.c:11:13: error: subscripted value is neither array nor pointer nor vector
test.c: In function ‘main’:
test.c:16:1: warning: passing argument 1 of ‘setArray’ from incompatible pointer type [enabled by default]
test.c:7:1: note: expected ‘double *’ but argument is of type ‘double (*)[2][2]’
最佳答案
您可以使用 VLA:
void setArray(int m, int n, double arr[m][n])
{
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
arr[r][c] = 2.0;
}
int main()
{
double myarray[2][2];
setArray(2, 2, myarray);
}
VLA 在 C99 中受支持,在 C11 中可选。如果您的编译器不支持 VLA,则您无法满足您的要求。但是,您可以将数组作为一维数组传递,并使用算术查找正确的元素:
void setArray(int num_rows, int num_cols, double *arr)
{
#define ARR_ACCESS(arr, x, y) ((arr)[(x) * num_cols + (y)])
for (int r = 0; r < num_rows; ++r)
for (int c = 0; c < num_cols; ++c)
ARR_ACCESS(arr, r, c) = 2.0;
#undef ARR_ACCESS
}
int main()
{
double myarray[2][2];
setArray(2, 2, (double *)&myarray);
}
关于c - C 中的二维数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23037951/