0

I have a for loop that resizes and appends a number to an dynamically sized array. However the array only repeats a couple times then the program ends.

#include<stdio.h>
#include<stdlib.h>
int main() {
int *primes = (int*)malloc(sizeof(int));
for (int i = 0; i < 15000; i++) {
    primes[i] = i;
    primes = (int*)realloc(primes, (i+2)*sizeof(int));
}

for (int i = 0; i < sizeof(primes)/sizeof(int); i++) {
    printf("%i, ", primes[i]);
}

free(primes);
return 0;
}

This prints 0, 1, then exits Why does it not continue to 15000?

1 Answers1

1

primes is a pointer, which has a size of 8 bytes on a 64-bit computer. An int has 4 bytes. 8/4=2, so it runs twice.

Lionel Foxcroft
  • 1,584
  • 3
  • 9
  • 23
  • Maybe you should precise that the problem come from the size evaluation of prime, an int pointer, in line : `for (int i = 0; i < sizeof(primes)/sizeof(int); i++) {` – Zilog80 Mar 24 '21 at 03:07