How to declare an array with an arbitrary size

情到浓时终转凉″ 提交于 2019-12-01 08:42:33
Dani

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.

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;
}

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/

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!