1

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.

1
  • sizeof (string_arr[0]); doesnt give the right space. other elements are 3 seen chars but zeroth element is 2 seen chars Commented Jul 18, 2012 at 17:43

5 Answers 5

4

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 (...);
...
Sign up to request clarification or add additional context in comments.

2 Comments

...or previously returned by a calloc() or realloc().
Hummm... the last line of the code sample above, what happens if realloc fails, you've got a memory leak there on string_array...
3

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.

Comments

3

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

Comments

2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.