1

can someone help with this piece of code? I leaved out check of allocations to keep it brief.

typedef struct {
  int x;
  int y;
} MYSTRUCT;

void init(MYSTRUCT **p_point);
void plusOne(MYSTRUCT **p_point, int *p_size);

int main()
{
  MYSTRUCT *point;
  int size = 1;

  init(&point);

  plusOne(&point, &size);
  plusOne(&point, &size);

  point[1]->x = 47;  //  this was the problem
  point[1].x = 47;   //  this is solution    

  return 0;
}

void init(MYSTRUCT **p_point)
{
  *p_point = (MYSTRUCT *) malloc( sizeof(MYSTRUCT) );
}

void plusOne(MYSTRUCT **p_point, int *p_size) 
{
  (*p_size)++;

  *p_point = realloc(*p_point, *p_size * sizeof(MYSTRUCT) ); // also calling to the function is fixed
}

I don't understand why index notation doesn't work after calling to functions.

2 Answers 2

2

This is because you are not multiplying the p_size by sizeof(MYSTRUCT) in the call of realloc, and not assigning the results back to p_point:

*p_point = realloc(*p_point, *p_size * sizeof(MYSTRUCT));

Notes:

  • You do not need to cast the result of malloc or realloc in C.
  • For consistency, consider passing &size to init, and set it to 1 there.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for incredibly fast answer. I've fixed the realloc() as you said but still can't use the index notation. I need it because in next step I want to make function which fills x and y of the array.
@the_Imp You need to use ., not -> there, because point[1] is MYSTRUCT itself, not a pointer to MYSTRUCT.
Thank you. It works. I try to make other functions and hope it'll works.
0

You have some type confusion going on... Here:

MYSTRUCT *point;

you declare point to be a pointer to a MYSTRUCT structure (or an array of them).

The syntax point[i] is equivalent to *(point + i) - in other words, it already dereferences the pointer after the addition of the appropriate offset, yielding a MYSTRUCT object, not a pointer to one.

The syntax p->x is equivalent to (*p).x. In other words, it also expects p to be a pointer, which it dereferences, and then yields the requested field from the structure.

However, since point[i] is no longer a pointer to a MYSTRUCT, using -> on it is wrong. What you are looking for is point[i].x. You could alternatively use (point + i) -> x, but that's considerably less readable...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.