1

I am having problem while creating dynamic array using both malloc and calloc.

    int main() {
      float *xd_real_send;
      int Nooflines_Real;
      int *X;
      float test[500];

      Nooflines_Real = count_lines(infile);
      printf("Nooflines_Real: %d\n", Nooflines_Real);

      X = (int *) malloc(Nooflines_Real*sizeof(int));
      xd_real_send = (float *) calloc (Nooflines_Real,sizeof(float));

      printf("size of X %d, test %d and size of xd_real_send %d\n",
      sizeof(X)/sizeof(int),sizeof(test)/sizeof(float),
      sizeof(xd_real_send)/sizeof(float));fflush(stdout);

    }

And the output is

    Nooflines_Real: 40
    size of X 2, test 500 and size of xd_real_send 2

Could you please tell what Am I doing wrong.

3
  • 1
    Don't cast the result of malloc or calloc. Commented Nov 15, 2012 at 16:47
  • sizeof(X) is the sizeof(int*). Commented Nov 15, 2012 at 16:48
  • Answers: stackoverflow.com/a/605858/694576 @dreamcrash Commented Nov 15, 2012 at 16:53

1 Answer 1

1

X and xd_real_send are defined as pointers.

The sizeof operator applied returns the amount of memory use by the pointer, not the size of what the pointer refers to.

It not possible (in any portable way) to request the size of a memory block once allocated dynamically and refered by some pointer.

For dynamically allocated memory the application needs to take care of keeping track of how large those memory blocks are.


test is defined expliciltly as an array, so sizeof is able to determine the array's size.

Sign up to request clarification or add additional context in comments.

3 Comments

Could you please tell how can i check if array of size 40 is created for xd_real_send.
Test ((Nooflines_Real == 40) && (NULL != (xd_real_send = calloc(Nooflines_Real, sizeof(float)))) @user1733911
if((Nooflines_Real == 40) && (NULL != (xd_real_send = calloc(Nooflines_Real, sizeof(float))))){ printf("ok"); } else { printf("not ok"); } output was "not ok"

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.