0

Below is the code that works properly fine and shows the correct output.

But it highlights an error in the line char name[n], But why?

  1. I have already declared n and taken its input.

Then, I declare the array name[n] which is highlighting n under the char name[n].

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

    int main()
    {
    int n;
    printf("\n Enter the value of n - ");
    scanf("%d",&n);
    
    char name[n];   // <--------
    for(int i=0 ; i<n ; i++)
    {
        name[i] = getch();
        printf("*");
    }

    printf("\n");
    for(int i=0 ; i<n ; i++)
    {
        printf("%c",name[i]);
    }

    getch();
   }
greybeard
  • 2,249
  • 8
  • 30
  • 66
  • 1
    Read about VLA in C: https://stackoverflow.com/questions/14075194/variable-length-arrays-vla-in-c-and-c – RedYoel Dec 12 '21 at 08:33
  • `*char name[n];*` Is the two `*` part of your code ?? – Support Ukraine Dec 12 '21 at 08:58
  • 2
    "But it highlights an error..." Is that your editor that highlights something? – Support Ukraine Dec 12 '21 at 08:59
  • Your editor probably highlights which line because in previous versions of C it was not possible to declare a variable after using a statement/function nor does it initialize array sizes with non-constant values. Maybe in the ide configuration you can change the version of C you are using. –  Dec 12 '21 at 11:56
  • Most likely you are using a Microsoft C++ compiler that does not support variable length arrays or another compiler in strict C++ mode. What compiler are you using? – Eric Postpischil Dec 12 '21 at 11:58
  • @Eric Postpischil: certainly but probably the ide does not know and highlights (.. and then you stop making me feel old :^D) –  Dec 12 '21 at 12:02
  • @dmaxime: We get people using some old software on Stack Overflow, but it is not **probable** that OP is using an IDE so old that it complains about declarations after statements, which has been allowed in C since the 1999 standard (and before that in compilers). [My prior comment was wrong about ANSI C, from 1990.] – Eric Postpischil Dec 12 '21 at 12:37
  • 1
    ANSI C does not support dynamic length arrays. – Florin C. Dec 12 '21 at 13:01
  • @4386427 yes my editor highlights the error. I am using visual studio code. – Free_loader Dec 14 '21 at 14:59
  • @4386427 the "*" is not the part of the code, that I made to highlight the particular line in the source code. – Free_loader Dec 14 '21 at 15:00

0 Answers0