0

I want to first user to tell me how many elements they want in the array. Then I create an array of char (char a[n]) where n is the number of elements I got from the user. I want to for loop to scan the input of character. But the for loop jumps two times and scan the input.

#include <stdio.h>

int main(void)
{
    int n, i;
    printf("How many elements you want in the array?  ");
    scanf("%d",&n);
    char a[n];
    for(i = 0; i < n; i++)
    {
         printf("Enter a character:  ");
         scanf("%c", &a[i]);
    }
    for(i = 0; i < n; i++)
    {
         printf("%c", a[i]);  
    }

    return 0;
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • After the declaration of char a[n], it goes to the for loop and there I have problems. It jumps two time. – alxprogrmz Jul 28 '18 at 20:05
  • in C and C++, you cannot simply define and array using `a[n]`, first you have to allocate a size to it say `a[MAX_LENGTH]` where `MAX_LENGTH` can be defined as `1000`or `2000` depending on your requirement. Then only you can use it like `a[n]`. Otherwise there is a logical error, because arrays cannot be defined during runtime. – Code_Ninja Jul 28 '18 at 20:11
  • @Code_Ninja: which millennium are you living in? In C++ (which this question is not tagged with), you are correct. However, variable length arrays (VLA) have been a part of standard C since the C99 standard. Your comment is mostly inaccurate for this question, therefore. The code is perfectly acceptable to C99 compilers, and to C11 or C17 compilers that do not define `__STDC_NO_VLA__`. – Jonathan Leffler Jul 28 '18 at 20:13
  • @JonathanLeffler I coded in C/C++ last time in 2013, am I late to say this? – Code_Ninja Jul 28 '18 at 20:15
  • @Code_Ninja: The only major modern platform where you might be using a compiler without support for VLA is on Microsoft Windows with MS Visual Studio as the compiler. I'm not sure what their current stance is on them. Essentially all other platforms support them, if only because both GCC and Clang support them. So, yes, you're probably a bit late to the party to be saying that the `char a[n];` notation is not valid C. There are some compilers on some platforms that do not support them, but three versions of the standard _do_ support them. (Some embedded platforms have compilers without VLAs.) – Jonathan Leffler Jul 28 '18 at 20:19
  • okay thanks for the update @JonathanLeffler, I moved to Java soon after.. and now I am in demandware.. need to keep myself a bit more updated. :) – Code_Ninja Jul 28 '18 at 20:21

0 Answers0