Allocating space for pointers to struct
In another post link text
I am trying to do the same thing with a struct, but I have a problem with my sizeof operator, so in the integer case, I did this:
size_t totalMem = rows * sizeof(int *) + rows * cols * sizeof(int));
And in the struct case I did this:
size_t totalMem = (rows * sizeof(struct TEST *)) + 开发者_如何学运维(rows * cols * sizeof(struct TEST));
But I get the error: Invalid application of sizeof to incomplete type of struct TEST.
Any thoughts? Thanks.
Because you're defining the struct as
typedef struct { ... } TEST;
you should always refer to the struct as TEST
, not struct TEST
, i.e. use
size_t totalMem = (rows * sizeof(TEST*)) + (rows * cols * sizeof(TEST));
To use struct TEST
you need to actually name the struct, i.e.
struct TEST { ... };
You can allow both with
typedef struct TEST { ... } TEST;
#include <stdio.h>
#include <stdlib.h>
#include "C2_Assignment_5_Exercise_2_Driver.h"
as part of my size_t statement. And then the definition in the .h file is:
#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
Change:
typedef struct MYTEST
{
char charObj;
short shortObj;
long longObj;
double doubleObj;
} TEST;
and
size_t totalMem = (rows * sizeof(struct TEST *)) + (rows * cols * sizeof(struct TEST));
to
size_t totalMem = (rows * sizeof(struct MYTEST *)) + (rows * cols * sizeof(struct MYTEST));
精彩评论