2010-02-12 93 views
0

在另一篇文章中link text分配空间的指针结构

我试图做同样的事情用一个结构,但我有我的sizeof操作符的问题,所以在整数的情况下,我这样做:

size_t totalMem = rows * sizeof(int *) + rows * cols * sizeof(int)); 

而在我这样做的结构情况:

size_t totalMem = (rows * sizeof(struct TEST *)) + (rows * cols * sizeof(struct TEST)); 

但我得到的错误:的sizeof无效的应用程序不完全类型结构的测试。

有什么想法?谢谢。

回答

3

因为你定义结构作为

typedef struct { ... } TEST; 

你应该总是指结构作为TEST,不struct TEST,即使用

size_t totalMem = (rows * sizeof(TEST*)) + (rows * cols * sizeof(TEST)); 

要使用struct TEST实际上你需要命名结构,即

struct TEST { ... }; 

您可以

typedef struct TEST { ... } TEST; 
+0

+1:打我 – tur1ng 2010-02-12 22:01:45

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

#include "C2_Assignment_5_Exercise_2_Driver.h" 

作为我的size_t语句的一部分。然后在.h文件中的定义是:

#ifndef C2_ASSIGNMENT_5_EXERCISE_2_DRIVER_H 
#define C2_ASSIGNMENT_5_EXERCISE_2_DRIVER_H 

typedef struct 
{ 
    char charObj; 
    short shortObj; 
    long longObj; 
    double doubleObj; 
} TEST; 

#endif 
+0

编辑您的疑问句而不是添加答案,谢谢。 – kennytm 2010-02-12 21:57:08

0

变化让双方:

typedef struct MYTEST 
{ 
    char charObj; 
    short shortObj; 
    long longObj; 
    double doubleObj; 
} TEST; 

size_t totalMem = (rows * sizeof(struct TEST *)) + (rows * cols * sizeof(struct TEST)); 

size_t totalMem = (rows * sizeof(struct MYTEST *)) + (rows * cols * sizeof(struct MYTEST));