so i've seen few questions relating none descriptive or explains me i'm trying change how many strings in array of strings eg array[3][155] realloc() array[4][155] create 4 strings hold 155 chars each can modified doing fgets(array[4], 155, stdin); , print out 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 3 can change size strcpy(array[0], "hello spot 0\n"); strcpy(array[1], "sup spot 1\b"); strcpy(array[2], "sup spot 2"); while(pnm != arrays) { printf("word %d: %s", pnm, array[pnm]); pnm++; } realloc(array, 4); strcpy(array[3], "sup spot 3!"); printf("the array now.\n"); pnm = 0; while(pnm != 4) { printf("%s", array[pnm]); pnm++; } }
which in console outputs
bash-3.2$ ./flash word 0: hello spot 0 flash(1968,0x7fff70639000) malloc: *** error object 0x7fff5828f780: pointer being realloc'd not allocated *** set breakpoint in malloc_error_break debug word 1: sup spot word 2: sup spot 2abort trap: 6 bash-3.2$
the error message you're getting pretty nice:
pointer being realloc'd not allocated
if going use realloc
, need pass either null pointer or pointer dynamically allocated using function malloc
or realloc
. pointer passed array stored on stack, different heap , not have reallocation feature.
i see calling realloc
argument of 4. realloc
function has no way know structure of array or how big elements are, need pass number of bytes want instead.
also, need store pointer returned realloc
somewhere, preferably after check not null. if realloc returns non-null pointer, should forget original pointer passed it.
Comments
Post a Comment