0
#include <stdio.h>
#include <stdlib.h>    

int main()
{
  long k;
  scanf("%ld", &k);
  long *number = calloc(k,sizeof(long));
  for (int i = 0; i < k ; i++)    
  {
    scanf("%ld", number+i);
  }
  for (int i = 0; i < k; i++)
  {
    printf("%ld", *(number+i));
  }
  free (number);
}

Hi i am trying to create an array of variable length and i believe c99 is unable to do so so i have to use calloc.
Q1) Is my code correct? i ran valgrind and it returns me few million errors from 2 context at the end.
Q2) Is there a better way to do this?
Q3) Is there a need to check for NULL? (99% i believe so :D)

1
  1. Looks about right. You don't check whether scanf was successful, and might end up with garbage in the rest of your array.
  2. You could long number[k]; (as long as k is known at the time of declaration) to allocate on stack instead of heap (saves you the free). Always keep in mind the lifetime of your variables (on stack until ending the block they were declared in) when passing pointers.
  3. Yes. calloc just like malloc might fail and return NULL, in which case a later line will likely cause a segmentation fault. If that happens in your example of allocating space for just a few numbers, you probably have worse problems. But add checks anyway.
3
  • Yes looks like c99 actually supports variable length array. I did not know what i did to have encountered an error of "Variable sized object may not be initialized"... Thanks – Yan Bo Pei Sep 29 '18 at 16:28
  • Ah i believe the error came when i do long arr[k] = {0}. apparent c99 do not allow this. Dannggg confuse rayyyy – Yan Bo Pei Sep 29 '18 at 16:31
  • Didn't know that last part, as I've never tried, so thanks for that. But matches the observation that after placing int arr[1000] = {0}; into my code, the compiler put 4000 zero bytes in the executable, a memset might have been the better choice. Not sure all compilers work that way, though, haven't repeated the experiment in a while.. – Blauelf Sep 30 '18 at 21:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .