0

I couldn't find answer of the exact question, since the condition is a bit more specific: How can i allocate array of struct pointers.

typedef struct COORDS
{
  int xp;
  int yp;
} coord;

coord** xy;

i want to allocate it like: xy[500][460] But it returns invalid memory error when accessing them.

6
  • 1
    For starters, new is a reserved word. Are you trying to allocate in heap or declare it in stack? Commented May 13, 2014 at 12:44
  • 1
    The compiller is old and its really old C. new is not a reserved word in my case, but i will edit the example. Commented May 13, 2014 at 12:47
  • 1
    new is only a reserved word in C++ Commented May 13, 2014 at 12:47
  • @Amarghosh new is reserved in c++ but not in c (which this question is tagged). That being said, it's still a very good idea to avoid use of c++ keywords in c. Commented May 13, 2014 at 12:48
  • 1
    @mah I think it's a good idea to use c++ keywords in C; it will alert someone who accidentally uses a C++ compiler on your code Commented May 13, 2014 at 12:51

2 Answers 2

2
coord** new = malloc (500 * sizeof (coord*));
int idx = 0;

for(; idx < 500; ++idx)
    new [idx] = malloc (460 * sizeof (coord));
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry to say. But it again gives the same error, using this code. The access is: xy[1][2].xp = 20;
@Lively: Does your code compile without warnings?
It is pretty ancient built-in compiler from a game engine. The coded posted by @barak manos ..work'd however.
0

Static allocation:

coord xy[500][460];

Dynamic allocation:

coord** xy = (coord**)malloc(sizeof(coord*)*500);
for (int i=0; i<500; i++)
    xy[i] = (coord*)malloc(sizeof(coord)*460);

// and at a later point in the execution of your program
for (int i=0; i<500; i++)
    free(xy[i]);
free(xy);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.