2013-03-06 93 views
-2

我想创建一个表,并且表的条目是结构类型。 从“TableRow”类型分配类型'SortTableRows'时,出现“不兼容的类型”错误。当分配类型时不兼容的类型

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct TableRow 
{ 
    int startingValue; 
    int entries[100]; 
}TableRow; 

typedef TableRow SortTableRows[20]; //Table Containing entries of type TableRow 

SortTableRows* SortTableRowsPtr; 

int main() 
{ 

    TableRow *tableRow; 
    tableRow = malloc(sizeof(TableRow)); 
    tableRow = NULL; 
    SortTableRowsPtr[2]=*tableRow; //Error 
    return 0; 
} 
+3

'tableRow = malloc(sizeof(TableRow)); tableRow = NULL;'你只是在尽可能少的行中泄漏了内存(只有一个未分配的'malloc()'可以更快地执行)。 – WhozCraig 2013-03-06 18:15:40

+1

删除typedef TableRow SortTableRows [20];''这里你不需要typedef来声明struct的数组。只是做'TableRow SortTableRows [20];' – 2013-03-06 18:24:19

+0

@GrijeshChauhan更不用说那个typedef是错的 – 2013-03-06 19:22:57

回答

3

我想你的意思是使用(*SortTableRowsPtr)[2],即分配给SortTableRows数组中TableRow型的第三阵列条目。

还是应该SortTableRowsPtr是一个数组20指针TableRow

typedef TableRow (*SortTableRows)[20]; 
0

以下情况如何?你在哪里将tableRow分配给SortTableRows数组中的第3行。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

typedef struct TableRow 
{ 
    int startingValue; 
    int entries[100]; 
}TableRow_t; 

int main() 
{ 

    TableRow_t SortTableRows[20]; 
    TableRow_t *tableRow = NULL; 

    /* Put some data into the 3rd row */ 
    SortTableRows[2].startingValue = 2; 
    for (i = 0; i < 100; ++i) { 
      SortTableRows[2].entries[i] = i; 
    } 

    tableRow = &(SortTableRows[2]); 

    printf("%d: %d, %d, %d\n", 
        tableRow->startingValue, 
        tableRow->entries[0], 
        tableRow->entries[1], 
        tableRow->entries[2]); 

    return 0; 
}