I would like to create a dynamic two-dimensional array of pointers to strings, like in the diagram below:
The program below is an extracted part of a program, and allocating dynamically stack A seems to work fine, but I'm having trouble creating a dynamic two-dimensional array of pointers to the cells of A.
// Global
char **stack_A; // dynamic array of strings
char ***stack_B; // dynamic array of pointers to strings
int main(){
stack_A = malloc(sizeof(char *));
stack_B = malloc(sizeof(char **));
function();
return 0;
}
void function(){
// example for first entry
char *text = "some text";
stack_A = realloc(stack_A, sizeof(char *)*strlen(text));
stack_A[0] = strdup(text);
stack_B[0] = realloc(stack_B[0], sizeof(char **));
stack_B[0][0] = *stack_A[0];
printf("%s", **stack_B[0][0]); // I want to output "some text"
}
Update: both the comment and answer was helpful in resolving the issue.
1 Answer 1
The problem is that you are not copying the pointer to the string, but the first charachter of the string:
stack_B[0][0] = *stack_A[0]; -> *stack_A means the first array in the group of arrays.
it means the same as stack_A[0].
*stack_A[0] means the first char in stack_A[0]: 's'
You need to copy the pointer, not the first letter:
stack_B[0][0] = *stack_A[0] becomes stack_B[0][0] = stack_A[0].
stack_A = realloc(A, sizeof(char *)*strlen(text));--> Here you increase the size of stack_A to the length of the text_string... why is that?stack_B[0][0] = *stack_A[0];The lvalue is of typechar*while the rvalue is of typechar...A? Andstack_B[0] = realloc(stack_B[0], sizeof(char **));will invoke undefine d behavior by using value of buffer allocated viamalloc()and not initialized, which is indeterminate.char ***stack_Bis not a 2D array of strings, it is a pointer to a pointer to a string.