Mohammad
Mohammad

Reputation: 3

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

Upvotes: 0

Views: 86

Answers (2)

Lundin
Lundin

Reputation: 214770

  • 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.

Upvotes: 1

dbush
dbush

Reputation: 224852

When you do this:

printf("%d\n",array);

Since array has type int *, you're attempting to print the value of of the pointer, not what it points to. Also, the %d format specifier is for printing an int value, not a int * value. You should instead use %p to print the pointer.

Upvotes: 0

Related Questions