[英]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
}
currentGeneration
是Generation *
,不是Generation
。
您需要一个Generation *
数组来保存它,而不是Generation
数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.