-1

Could help about making that code pure C.

struct edge
{
    char key;
    char values[5];
};

edge* a = new edge[9];
Rckt
  • 185
  • 1
  • 3
  • 11
  • 1
    This code won't even compile as C++. You have to provide a minimal working code example and ask your question. –  Mar 06 '12 at 21:23
  • 1
    just change the last line to `struct edge *a = malloc(sizeof(*a) * 9)`. – Niklas B. Mar 06 '12 at 21:23
  • It's not clear what you want to achieve. Do you want to create nine instances of `struct edge`? Also, CPP means C PreProcessor, but you mean C++ which is an entirely different thing. – DarkDust Mar 06 '12 at 21:24
  • http://stackoverflow.com/a/612350/1214731 is a good resource for this kind of question. – tmpearce Mar 07 '12 at 01:47

2 Answers2

6
typedef struct
{  
    char key;
    char values[5];
} edge ;

edge *a = malloc(9 * sizeof(edge)) ;

This should do it

rrr105
  • 182
  • 7
  • 1
    @Rckt: You're declaring `edge* a` in global scope (which has static storage duration) and can only be initialized with constants, i.e. `1` or `"hello"`, etc. (This is another C quirk). – Jesse Good Mar 06 '12 at 21:33
  • which compiler are you using? – rrr105 Mar 06 '12 at 21:35
  • There shouldn't be any problem with this code. What exactly is the structure of the rest of your program? – rrr105 Mar 06 '12 at 21:39
  • I've fixed it. But I need to create nine instances of struct edge. Is it possible? – Rckt Mar 06 '12 at 21:40
  • The above code does exactly that. It assigns enough space for 9 elements of edge. If you want to access the nth element, just use *(edge + n - 1) ; – rrr105 Mar 06 '12 at 21:43
0

I'm going to take a shot in the dark, and assume that you actually don't need dynamic memory allocation at all. In that case, the C version is:

struct edge
{
    char key;
    char values[5];
};

struct edge a[9];

Remember, in C++ you don't need new to create objects, you only need new if you want to dynamically create objects.

If my guess is correct, the above will work perfectly for you. If my guess is incorrect, then you'll get an error in your program on a line like:

a = foo;
Robᵩ
  • 163,533
  • 20
  • 239
  • 308