0

I would like to create a dynamic two-dimensional array of pointers to strings, like in the diagram below:

enter image description here

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.

asked Aug 5, 2020 at 15:26
7
  • 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? Commented Aug 5, 2020 at 15:33
  • I might have gotten it wrong, but I just need to increase a cell of stack_A to make some space for "text". Commented Aug 5, 2020 at 15:34
  • 1
    stack_B[0][0] = *stack_A[0]; The lvalue is of type char* while the rvalue is of type char... Commented Aug 5, 2020 at 15:38
  • 3
    What is A? And stack_B[0] = realloc(stack_B[0], sizeof(char **)); will invoke undefine d behavior by using value of buffer allocated via malloc() and not initialized, which is indeterminate. Commented Aug 5, 2020 at 15:39
  • 1
    char ***stack_B is not a 2D array of strings, it is a pointer to a pointer to a string. Commented Aug 5, 2020 at 16:54

1 Answer 1

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].

MikeCAT
75.1k11 gold badges50 silver badges71 bronze badges
answered Aug 5, 2020 at 15:39
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.