How to declare an array with an arbitrary size

2019-02-18 15:21发布

问题:

Ok, this is a C programming homework question. But I'm truly stuck.

I ask the user to input words, and then I insert the input into an array, but I can't have any control over the number of words the user types.

I guess what I'm asking is how do you declare a an array in C without declaring its length and without asking the user what the length should be.

I know this has something to do with malloc, but if you could give me some examples of how to do this, I would really appreciate it.

回答1:

You can realloc it every time like:

int size = 0;
char **array = malloc(0);
while(/* something */)
{
    char *string = // get input
    size++;
    array = realloc(array, size * sizeof(char*));
    array[size - 1] = string;
}

Or in chunks if you care about speed.



回答2:

You can malloc a block of memory large enough to hold a certain number of array items.

Then, before you exceed that number, you can use realloc to make the memory block bigger.

Here's a bit of C code that shows this in action, reallocating an integer array whenever it's too small to hold the next integer.

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

int main (void) {
    int *xyzzy = NULL;   // Initially NULL so first realloc is a malloc.
    int currsz = 0;      // Current capacity.
    int i;

    // Add ten integers.

    for (i = 0; i < 10; i++) {
        // If this one will exceed capacity.

        if (i >= currsz) {
            // Increase capacity by four and re-allocate.

            currsz += 4;
            xyzzy = realloc (xyzzy, sizeof(int) * currsz);
                // Should really check for failure here.
        }

        // Store number.

        xyzzy[i] = 100 + i;
    }

    // Output capacity and values.

    printf ("CurrSz = %d, values =", currsz);
    for (i = 0; i < 10; i++) {
        printf (" %d", xyzzy[i]);
    }
    printf ("\n");

    return 0;
}


回答3:

Yes, you want malloc. Checkout this tut.

http://www.cprogramming.com/tutorial/dynamic_memory_allocation.html

This site is good in general for learning.

Here is an example of using realloc, it is basically exactly what you are asking to do.

http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/



回答4:

0) obviously you will need multiple buffers, so you will need a list like structure: perhaps a record with char array 100 chars and a pointer to next structure 1) You need to capture the words char by char and store them in your buffer 2) once the buffer is full you allocate another record, chain it with the previous one and keep going until you are out of mem or the process is over.

That should be better performance than realloc function. I believe malloc is trying to give contious block of memory. Therefore the list like structure will be faster and work better.