-1

I want to initialize an array of variable length with random zeros and ones. My problem is that the array I created seems to only have a length of 4 elements. Why is that?

int main()
{
    int i, j;
    int length = 20;
    int *array = (int *) calloc(length, sizeof(int));
    for (i = 1; i < length; i++) {
        array[i] = 1;
        printf("%d", array[i]);
    }
    printf("\n");
    for (j = 0; j < sizeof(array); j++) {
        printf("%d", array[j]);
    }
    getchar();
}
MrCGenius
  • 21
  • 4
  • 1
    Possible duplicate of [Why does a C-Array have a wrong sizeof() value when it's passed to a function?](https://stackoverflow.com/questions/2950332/why-does-a-c-array-have-a-wrong-sizeof-value-when-its-passed-to-a-function) – Andrew Henle Jun 06 '17 at 14:09
  • Thanks, that turned out to be an answer to my question. – MrCGenius Jun 12 '17 at 19:34

3 Answers3

3

The type of array is int *, so the size of array in the sense of sizeof(array) is the size of a pointer value (i.e. 4 on 32 bit systems and 8 on 64 bit systems).

You should simply write for (j = 0; j < length; j++) instead of for (j = 0; j < sizeof(array); j++).

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
3

You issue is that sizeof(array) returns you the size of int *, which on your systems evaluates to 4. Simply use j < length as stop criterion in the second iteration.

harfel
  • 302
  • 3
  • 14
0

Solution is, instead of the the sizeof operator in for (j = 0; j < sizeof(array); j++), use for (j = 0; j < length; j++).

Also, i presume you want 20 elements of 0s and 1s in the array. So you might want to change

in the line for (i = 1; i < length; i++)

use for (i = 0; i < length; i++) instead.

Now for the explanation, the primary bug in the code is in the line

for (j = 0; j < sizeof(array); j++)

The sizeof operator returns size in bytes of the object representation of type. In your case the type is int, hence for a 32 bit machine, the sizeof operator will return 4 and for a 64 bit machine it will return 8. So in the second loop, runtime length is returned as 4(your machine is 32bit).

To explore all the elements you have input in the first loop, just use the same length variable to point to each index of the array instead of the sizeof operator.

  • Thanks! So how exactly do I know whether the name of my array represents the array itself or just a pointer to its first element? – MrCGenius Jun 07 '17 at 14:52
  • you are allocating memory for an array and assigning a pointer to it. The pointer would always point to the address of the first index and then increment as you iterate over it. And this is generic for arrays declared with definite size as well. – Sheikh Faisal Miskhat Jun 09 '17 at 09:49