MeHow
MeHow

Reputation: 133

user input in struct in C?

int a;
scanf("%d",a);

typedef struct mylist {
    int info[a];
    struct mylist *link;

} Node;

this is my very simple struct and variable 'a' that don't work.

The thing which I want my program to do is to read input from the user and insert the digit into the struct (the user can determine the size of the array), however, I don't know how to do it since I get an error:

"variably modified ‘info’ at file scope".

I want to know whether it is possible to do this in a simple way.

Upvotes: 2

Views: 20238

Answers (3)

4pie0
4pie0

Reputation: 29724

You must have pointer to array of correct size or use flexible array. Here is how to use a pointer initializing it to point to storage of proper size.

struct mylist {
    int *info;    // or int info[] at the end of struct def if C99 is used
    int info_size;
    struct mylist *link;
};

int main(void)
{
    int *array;
    struct mylist m;
    if (scanf("%d", &m.info_size) != 1)
    {
        perror("scanf failed");
        exit(EXIT_FAILURE);
    }
    // ok
    array = malloc(sizeof(int) * m.info_size);
    if (array == NULL)
    {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }
    // ok, commit changes
    m.info = array;

Upvotes: 1

David Ranieri
David Ranieri

Reputation: 41017

As pointed out by @David Hoelzer

scanf("%d",a);

should be

scanf("%d",&a);

If you are under C99 you can use flexible array members:

typedef struct mylist {
    struct mylist *link;
    int info[]; /* should be the last member */
} Node;

and then

Node *node = malloc(sizeof *node + (a * sizeof(int)));

Upvotes: 2

David Hoelzer
David Hoelzer

Reputation: 16331

When you use scanf into an integer you must pass a pointer. You may want to check the documentation.

 scanf("%d", &a);

As far as using a variable to allocate data, you can do it, but you will want to use malloc most likely after defining your structure as a type.

Upvotes: 3

Related Questions