Reputation: 19
I'm beginner in the studies of C language (not C++) and I'm trying to define a dynamic array of strings, but I'm experiencing difficulties for appending an element.
I have tried to define the array as:
char **e = malloc(3 * sizeof(char *));
e[0] = "abc";
e[1] = "def";
e[2] = "ghi";
It ran successfully, but trying to resize it, using:
**e = realloc(e, 4 * sizeof(char *));
Returned the error: "assignment makes integer from pointer without a cast". What am I doing wrong?
Thanks, Fábio
Upvotes: 0
Views: 239
Reputation: 16117
This is the refined code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char **e = malloc(3 * sizeof(char *));
e[0] = malloc(4 * sizeof(char));
e[1] = malloc(4 * sizeof(char));
e[2] = malloc(4 * sizeof(char));
strcpy(e[0], "abc");
strcpy(e[1], "def");
strcpy(e[2], "ghi");
puts(e[0]);
puts(e[1]);
puts(e[2]);
}
Some problems found in your code:
To allocate memory to a pointer, write ptr = malloc(1)
, not malloc(ptr, 1)
.
e
is a "pointer to pointer to char", while e[0]
to e[2]
are "pointers to char". So when mallocing e, use sizeof (char *)
, and when mallocing e[x]', use
sizeof (char)` instead.
*e = "abc";
only copy the address of the string literal, not the value it contains. To copy the whole char array, you have to write strcpy(e[0], "abc");
.Upvotes: 0
Reputation: 2594
Short answer:
e = realloc(e, 4 * sizeof(char *));
Long answer:
Let's split your original declaration char **e = malloc(3 * sizeof(char *));
into declaration and assignment.
char **e;
e = malloc(3 * sizeof(char *));
The first line introduces the variable e
and specifies its type char **
. The second line assigns the expression that you put on the right side of the =
sign to the newly declared variable.
To assign a new value to e
, you modify the second line to read:
e = realloc(e, 4 * sizeof(char *));
Upvotes: 2