How to declare an array with an arbitrary size

后端 未结 4 1622
失恋的感觉
失恋的感觉 2021-01-14 10:32

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

4条回答
  •  一向
    一向 (楼主)
    2021-01-14 10:43

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

提交回复
热议问题