简体   繁体   中英

Variable-size arrays/similar in C with pointers?

I think my wording may not be entirely accurate but please bear with me.

What I'm trying to do is write code that allows a user to input any amount of numbers and store them in an array for use at another piece of the code. However I think I'm struggling with how to use pointers correctly in order to achieve that. Here's the code I have at the moment:

int n = 0, marks[] = {0};
while (EOF != scanf("%d", marks+n))
{
    n++;
    int marks[n]=marks;
}

int *i_p=marks;

Unfortunately I can't initialise the variable size array with my version of C ("error: variable-sized object may not be initialised") and I don't know how else to do it. What should I change and how to make this program work correctly?

Note: this question was an exercise for school and while I read some answers to other questions using calloc/malloc, we are not expected to know or use this, so I would prefer a different solution if possible.

What you want is not available out of the box. You need to implement a dynamic array.

size_t marks_size = 8;
int n = 0, *marks = malloc(marks_size * sizeof(*marks)), mark;
if (!marks) abort();

while (EOF != scanf("%d", &mark))
{
    n++;
    if (n > marks_size)
    {
        marks_size *= 2;
        marks = realloc(marks, marks_size * sizeof(*marks));
        if (!marks) abort();
    }
    marks[n]=mark;
}
int *i_p=marks;

free(marks); // when you're done with the array, free the memory

Of course you can make this code better, but this is the idea.

C does not have arrays whose sizes vary dynamically. Even dynamically- allocated arrays have fixed size for their lifetime. C does have arrays whose (fixed) size is not known until run time. It also has arrays whose (fixed) size is determined from an associated initializer -- that's what you have in the code you present. The array you declare has length 1 because the initializer provides exactly one element.

If you cannot use dynamic allocation ( malloc or calloc ), and you cannot determine how long your array needs to be without reading all the elements, then there is no general solution. You need more constraints on the problem.

The best you can do in that case is declare an array that you hope will be long enough for every case the program needs to handle in practice, and to catch and reject attempts to provide more values than that. (An upper bound on the size of the problem you must handle is just the sort of added constraint that would be helpful.) Of course, in that case you must track how many elements of your array have actually been used.

By the way, the error you report arises from this line:

    int marks[n]=marks;

That's wrong at least four different ways. I'm not even positive what it's supposed to do, but maybe you mean to re-declare array marks with a larger dimension. As I already said, C does not provide for that except via dynamic allocation.

After looking at your last line - not using calloc or malloc - there are a few alternatives.

The first, and easiest alternative is to use a very big array, and stop the user from inputting more values when it is full. Odds are, if you ask your teacher "what is the maximum amount of values the user is allowed to input", they will give you a number. Use this as the size of your array.

If your teacher doesn't say, then you can ask the user at runtime. C99 introduces a thing called a Variable Length Array . This is not an array that grows when you put things in it - you specify the length, and it will stay that length for the rest of its life. But you can specify the length at runtime. So just ask the user how many entries they are going to make, and create the array to match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM