0

The program I am working on requires the user to enter an integer value and then based on that value print an array of zero's. I have been able to do this when the size of the array is preset however when attempting to do it on a user input I get compiler errors. I have tried researching on a fix however I have come upon nothing since most of the fixes use dynamic memory allocation which we have not yet taught how to use. This is the code I have come up with so far.

In my attempts at finding out why I get errors is that I found if I don't initialise the array with 0 the array is printed to the size the user inputs however of course the array output numbers are completely random.

When I have the size of the array initialised I get the error variable-sized object may not be initialized with a small arrow pointing to the j within the square brackets in int j, ar[j]={20};.

Is there any other way that doesn't use dynamic memory allocation?

#include <stdio.h>

int main(void){

    int i;
    int j, ar[j]={0};

    printf("Please enter the value:");
    scanf("%d",&j);

    for(i=0; i<j;i++){
        printf("%i\n",ar[j]);
    }
Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
sandalwood
  • 41
  • 1
  • 7

2 Answers2

0
 int j, ar[j]={0};   // you should not do this 

This not correct as j is uninitalized .

But this will be supported in C99-

 int j;
 printf("Please enter the value:");
 scanf("%d",&j);         // take input in j 
 int  ar[j];             // this statement int ar[j]={0} will give compilation error

 for(i=0;i<j;i++){
   ar[i]=0;        
   printf("%d",ar[i]);
 }
ameyCU
  • 16,489
  • 2
  • 26
  • 41
-1

I don't think there are any ways that don't use dynamic memory allocation.

I suggest that you should use malloc or calloc for C. calloc clears the memory after allocating.

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

int main(void){

    int i;
    int j, *ar;

    printf("Please enter the value:");
    scanf("%d",&j);
    ar = calloc(j, sizeof(int));
    if (ar == NULL) return 1;

    for(i=0; i<j;i++){
        printf("%i\n",ar[j]);
    }

    free(ar);
    return 0;
}

Using new[] is good for C++.

#include <stdio.h>

int main(void){

    int i;
    int j, *ar;

    printf("Please enter the value:");
    scanf("%d",&j);
    ar = new int[j];

    for(i=0; i<j;i++){
        printf("%i\n",ar[j]);
    }
    delete[] ar;
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Thank you for your answer if you don't mind can you please explain or link me to something that goes over what is happening here: `ar = calloc(j, sizeof(int)); if (ar == NULL) return 1;` and also what the `free(ar)` does. – sandalwood Sep 22 '15 at 08:58
  • `calloc(j, sizeof(int))` allocates `j` blocks of `sizeof(int)` and clear them to zero. `if (ar == NULL)` checks if the allocation succeeded. – MikeCAT Sep 22 '15 at 09:03
  • Oh okay I see, thank you for your help. It seems the learning for C coding never ends :P. – sandalwood Sep 22 '15 at 09:06