簡體   English   中英

C中的2D數組指針

[英]2D array pointer in C

我有功能和主要

#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);
}

C99支持VLA,C11支持VLA。 如果您的編譯器不支持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);
}

嘗試這個:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>

void 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(){
    int i;
    double **myarray = (double**) malloc(2 * sizeof(double*));
    for(i = 0; i < 2; ++i)
        myarray[i] = (double*) malloc(2 * sizeof(double));
    setArray(myarray);
}

首先,您的setarray應該接受2D數組,而不是Poniter。 如果知道數組的寬度,則可以這樣定義它:

void setArray(double (*thearray)[2]) //2D array decays into a pointer to an array

然后只需致電:

setArray(myarray)

數組僅衰減一次指針,因此2D數組不會衰減到指針指針。 如果寬度不固定,請使用指針的指針代替:

void setArray(double **thearray)
{
    ...
}

setArray((double **)myarray) //explicitly convert.

2D數組具有雙指針( ** )。 在將數組作為參數發送時,不需要添加與號,因為不帶方括號的數組是地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM