簡體   English   中英

向結構數組添加元素

[英]Adding elements to Struct Array

struct GENERATIONS
{
char generation[MAX_ROWS][MAX_COLS];
int hasCycle;
};

typedef struct GENERATIONS Generation;

我有一個struct類型的數組:

Generation generations[MAX_GENERATIONS];

我這樣聲明一個Generation變量:

Generation *currentGeneration = NULL;
currentGeneration = (Generation *) malloc(sizeof(Generation));

並嘗試將世代添加到世代數組中:numGenerations設置為0,然后通過循環遞增。

copyGeneration(currentGeneration);
generations[numGenerations] = currentGeneration;

但是每次從類型'struct Generation *'分配給'Generation'類型時,都會得到錯誤的不兼容類型。 我了解這與我不了解但需要的指針有關。

為什么當我將數組聲明為:

Generation *generations[MAX_GENERATIONS];

一切突然正常嗎?

每個currentGeneration都是一個Generation的指針。 但是,當您聲明數組Generation generations[MAX_GENERATIONS]它希望每個索引都是 Generation ,而不是指向一個的指針。 但是,當您將數組聲明為Generation *generations[MAX_GENERATIONS]它希望每個索引都是一個指向Generation的指針,這就是您要分配給每個索引的內容。

該錯誤告訴您確切的問題所在。 您的變量currentGeneration類型為“指向世代的指針”,而變量generations的類型為“世代數組”。 您不能將指向Generation的指針分配給Generation數組的索引-您只能分配Generation。

當您將數組聲明為Generation *generations[MAX_GENERATIONS] ,一切都會正常,因為您正在將指向Generation的指針分配給Generation指針數組的索引。

要解決此問題,可以采用其他方式進行。 你能做的就是這個

#define MAX_GENERATIONS 1024 // you can take some other value too
#include <stdio.h>
#include <stdlib.h>
static int count = 0

Generation** push(Generation** generations, Generation obj){
 count++;
 if (count == MAX_GENERATIONS){
   printf("Maximum limit reached\n");
   return generations;

 if ( count == 1 )
   generations = (Generation**)malloc(sizeof(Generation*) * count);
 else
   generations = (Generation**)realloc(generations, sizeof(Generation*) * count);

 generations[count - 1] = (Generation*)malloc(sizeof(Generation));
 generations[count - 1] = obj;

 return generations;
}

int main(){
  Generation** generations = NULL;
  Generation currentGeneration;
  // Scan the the elements into currentGeneration
  generations = push(generations, currentGeneration); // You can use it in a loop
}

currentGenerationGeneration * ,不是Generation

您需要一個Generation *數組來保存它,而不是Generation數組。

暫無
暫無

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

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