Frank
Frank

Reputation: 2173

How to realloc() memory to string array

I have a string array of,

char *string_arr[] = {     "Hi",  "Hi2", "Hi3", "Hi4"    };

Now I need to realloc memory to the array, because I have to insert another element into the array like "Hi5". How can I do that?

I tried:

string_arr = realloc (.....); 

but it doesn't work, it gives: "incompatible types in assignment" error.

Upvotes: 1

Views: 1502

Answers (5)

Jeyaram
Jeyaram

Reputation: 9504

Memory for the string array will be allocated in read-only section.

      .section        .rodata
    .LC0:
            .string "Hi"
    .LC1:
            .string "Hi2"
    .LC2:
            .string "Hi3"
    .LC3:
            .string "Hi4"
            .text
    .globl main
            .type   main, @function
    main:
            pushl   %ebp
            movl    %esp, %ebp
            subl    $16, %esp
            movl    $.LC0, -16(%ebp)
            movl    $.LC1, -12(%ebp)
.....
.....


Not in the heap. so you can't use realloc() to extend the memory.

Upvotes: 2

chmeee
chmeee

Reputation: 3638

There are two problems with your code:

1) You are attempting to realloc() a fixed-size array. realloc() can only be used on memory allocated using malloc().

2) string_arr is an array, not a pointer. Arrays do degenerate into pointers when used as rvalues in expressions, but are still distinct data types as lvalues.

Upvotes: 3

Francis P
Francis P

Reputation: 13665

Create a new array of size +1, transfer the elements from the initial array to the new array.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272822

You cannot realloc an array that has not been malloc-ed.

Upvotes: 3

paulsm4
paulsm4

Reputation: 121881

You can only "realloc()" a pointer to memory you got from "malloc ()".

char **string_arr;

int nelms = 10;
string_array = (char **)malloc (sizeof (char *) * nelms);
if (!string_array) {
  perror ("malloc failed");
  return;
}

string_array[0] = strdup ("Hi");
string_array[1] = strdup ("Hi2");
string_array[2] = strdup ("Hi3");
string_array[3] = strdup ( "Hi4");
...
string_array = realloc (...);
...

Upvotes: 4

Related Questions