-6

I need to translate my C++ code into C99:

struct TransferData  {
    int data[256];
} *readData;    

readData = (TransferData  *) malloc(sizeof(struct TransferData));       

I nearly tried everything but get compiler errors each time. Can anyone help?

halfelf
  • 9,737
  • 13
  • 54
  • 63
user3619609
  • 29
  • 1
  • 3
  • 2
    You should post some of the compiler errors also. – kusma May 09 '14 at 08:37
  • 2
    [Note that casting the result of `malloc` is considered bad style in `C`](http://stackoverflow.com/a/605858/1171191) (while it is necessary in `C++`, although you probably shouldn't be using `malloc` in the first place). – BoBTFish May 09 '14 at 08:39

3 Answers3

4

For C you need to cast to struct TransferData *, not to TransferData *. You don't have a type named TransferData * (or drop the cast altogether, but it's another holy war, pointless IMHO).

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
2

You can either do as @icepack said, or change your struct definition like so:

typedef struct  {
    int data[256];
} TransferData;

TransferData *readData;
readData = malloc(sizeof(TransferData));

Edit: Note that it's preferable to use sizeof with variables instead of types to avoid repetition:

readData = malloc(sizeof(*readData));

But be careful not to accidentally pass the size of a pointer when using this style.

Without the typedef, you need to write struct StructType in C, which you don't need in C++. As said in the comments, casting the result of malloc is unnecessary in C, and just clutters your code. It is necessary in C++, but you shouldn't be using malloc there.

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40
1

If you are using C, you should not cast the result of malloc. It's a bad style to repeat type information. Also, the type of the structure is struct TransferData and not TransferData as in C++. I suggest

readData = malloc(sizeof(*readData));    
ajay
  • 9,402
  • 8
  • 44
  • 71