简体   繁体   中英

Reallocating a two-dimensional array in C

So i've seen a few questions relating to this but none really too descriptive or that explains it to me So i'm trying to change how many strings are in an array of strings eg array[3][155] realloc() into array[4][155] to create 4 strings that hold 155 chars each which can then be modified by doing fgets(array[4], 155, stdin); and then print out the new array

My attempt here

 #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main () {
    int arrays = 3;
    int pnm = 0;
    char array[arrays][155]; //Default size is 3 you can change the size
    strcpy(array[0], "Hello from spot 0\n");
    strcpy(array[1], "Sup from spot 1\b");
    strcpy(array[2], "Sup from spot 2");
    while(pnm != arrays) {
        printf("Word %d: %s", pnm, array[pnm]);
        pnm++;
    }
    realloc(array, 4);
    strcpy(array[3], "Sup from spot 3!");
    printf("The array is now.\n");
    pnm = 0;
    while(pnm != 4) {
        printf("%s", array[pnm]);
        pnm++;
    }

}

which in console outputs

bash-3.2$ ./flash
Word 0: Hello from spot 0
flash(1968,0x7fff70639000) malloc: *** error for object 0x7fff5828f780: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug
Word 1: Sup from spot Word 2: Sup from spot 2Abort trap: 6
bash-3.2$

The error message you're getting is pretty nice:

pointer being realloc'd was not allocated

If you are going to use realloc , you need to pass it either a NULL pointer or a pointer that was dynamically allocated using a function like malloc or realloc . The pointer you passed is to an array that is stored on the stack, which is a different from the heap and does not have a reallocation feature.

I also see you are calling realloc with an argument of 4. The realloc function has no way to know about the structure of your array or how big its elements are, so you need to pass the number of bytes you want instead.

Also, you need to store the pointer returned by realloc somewhere, preferably after you check that it is not NULL. If realloc returns a non-NULL pointer, you should forget about the original pointer you passed to it.

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