簡體   English   中英

訪問typedef'ed指針數組的元素

[英]Accessing elements of typedef'ed array of pointers

我在訪問傳遞給函數的數組元素時遇到了一些問題。

#define N (128)
#define ELEMENTS(10)
typedef int (*arrayOfNPointers)[N];

因此,如果這是正確的,它是描述的陣列的數據類型N指針int

我稍后單獨初始化我的數組,如下所示:

arrayOfNPointers myPtrs = { 0 };
int i;
for (i=0; i<N; i++) {
  myPtrs[i] = (int*)malloc(ELEMENTS);
}

但是,這失敗並出現以下錯誤:

error: incompatible types when assigning to type 'int[128]' from type 'int *'

所以,我的語法似乎有些不對勁。 但是在另一塊代碼中,我正在修改一些這樣的結構的內容,我沒有問題。

void doWork(void* input, void* output) {
   int i,m,n;
   arrayOfNPointers* inputData = (arrayOfNPointers*)input;
   int* outputData = (int*)output;

   for (m=0, n=0; n<nSamples; n++) {
      for (i=0; i<nGroups; i++) {
         outputData[m++] = (*inputData)[i][n];
      }
   }
}

這個陣列邏輯是否嚴重破壞?

typedef int (*arrayOfNPointers)[N];

所以,如果這是正確的,它是一個描述N指針數組的數據類型。

我認為這是一個指向N個整數數組的指針,而不是指向整數的N個指針的數組....

這意味着以下行的行為不符合您的預期... myPtrs [i] =(int *)malloc(ELEMENTS); 因為myPtrs是指向N維數組的指針(在這種情況下是128個int的數組),myPtrs [i]是第i個n維數組。 所以你試圖指定一個指向數組的指針,這就是你得到msg的原因......

錯誤:從類型'int *'分配類型'int [128]'時出現不兼容的類型

我相信你正在尋找的是以下......

#define N 128
#define ELEMENTS 10
typedef int* arrayOfNPointers[N];

arrayOfNPointers myPtrs = { 0 };
int i;
for (i=0; i<N; i++) {
  myPtrs[i] = malloc(sizeof( int ) * ELEMENTS);
}

您希望arrayOfPointer是一個N指向ELEMENTS整數的數組。 另外,當malloc()為整數空間時,需要將ELEMENTS的數量乘以整數的大小。 實際上,您分配的空間太小,無法容納您嘗試存儲在其中的數據。

您的typedef將arrayOfPointer聲明為指向N個整數數組的指針。 請記住使用左右閱讀規則來了解您聲明變量/類型的內容。 因為你在parens中有(*arrayOfPointer) ,右邊沒有任何東西,左邊有一個指針,所以arrayOfPointer是一個指針TO [N] (右)int(左)。 不是你想要的。

另外...... 不要在C中強制使用malloc()

基於malloc()的使用,它似乎是一個int*數組:

int* myPtrs[N];   /* Array of 'int*'. */

而不是指向int[128]數組的指針:

int (*myPtrs)[N]; /* Pointer to array of int[N]. */

是必須的。 使用malloc()是不正確的,因為它為10個字節而不是 10個int分配內存。 改成:

/* Casting result of malloc() is not required. */
myPtrs[i] = malloc(sizeof(int) * ELEMENTS);

暫無
暫無

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

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