c - C 中的二维数组指针

标签 c arrays pointers multidimensional-array

我有功能和主要

#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/

相关文章:

c - 什么用于引导 C 编译器

c++ - 为什么这运行良好? (访问范围外变量的地址)

c - int *(*papi[10]) 是什么意思

c - 在递归函数中操作全局数组

c++ - 如何在我的网站上编译 C 代码

c - 在 C 中的数组末尾附加一个 float

java 2d数组将每行的最高值更改为零

Javascript:如何找到元素在多维数组中的位置

python - python中矩阵的逻辑乘法

2D 矩阵上的移位、旋转和翻转操作可以组合成一个操作吗?