I wanted to understand the exit of this code

Asked

Viewed 41 times

0

I’m trying to make a simple code that takes more than one sentence and puts it in an array of size (number of sentences) N. I was able to make a code but with the size of the array already defined:

#include <stdio.h>

int main(){

    int n = 2;
    char lista[n][100]; 

    for (int x = 0; x < n; x++){
        scanf("%[^\n]%*c", lista[x]);
    }

    for (int x = 0; x < n; x++){
        printf("%s\n", lista[x]);
    }

    return 0;
}

It works perfectly, I spin, write two sentences and then it returns me the two sentences I wrote.

I tried later to use scanf to define n, which would be how many sentences there are in this array, so:

#include <stdio.h>

int main(){

    int n;
    scanf("%i", &n);
    char lista[n][100]; 

    for (int x = 0; x < n; x++){
        scanf("%[^\n]%*c", lista[x]);
    }

    for (int x = 0; x < n; x++)
    {
        printf("%s\n", lista[x]);
    }

    return 0;
}

But when I run the code and put the number 2 in the terminal, for example, before I can write the sentences it simply returns to me " " right away. I’m so lost, I have no idea what this "".

1 answer

3


The size of the array needs to be set at compile time (when compiling), cannot be done in Runtime (i.e., when running), so it works in the first example, where it is already previously set to 2.

It is possible to use the malloc to change the size of the array in Runtime. See more here: C Dynamic memory allocation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.