Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why I get strange value after using calloc function in c when i print each element and print the whole value?

I’m new to see and just experimenting some function of it. I came across calloc() function.
I wonder why the whole variable printed, is not same as each of the indexes . shouldn’t the variable value be 0?

#include "stdio.h"
#include "stdlib.h"

int main()
{
    int *array;
    array = calloc(100,sizeof(int));
    printf("%d\n",array);
    for(int i  = 0 ; i<sizeof(array);i++)
    {
        printf("%d\n", array[i]);
    } 
    free(array);
}

and the output is

-1300734400
0
0
0
0
0
0
0
0

I expected that the value printed in the printf("%d\n",array); would be zero

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • printf("%d\n",array); This is wrong, you are printing the address of the array, not the contents. In case you mean to actually print the address, you should use %p and also cast the pointer to (void*).

  • i<sizeof(array) This is wrong.

    • For a normal array, sizeof gives the size in bytes but array[i] assumes int item number i, not a byte. To get the number of items of an array, you must do sizeof(array)/sizeof(*array).

    • However you don’t actually have an array here but a pointer to the first element. So you can’t use sizeof at all or you will get the size of the pointer! Typically 2 to 8 bytes depending on system.

  • #include "stdio.h" When including standard library headers, you should use <stdio.h>. The " " syntax is for user-defined headers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading