So I have created a struct, in which one of the variable is a pointer to a dynamic array of chars. So I implemented it as a pointer to pointer. Then I used a separate function to initialize the struct:
#include<stdio.h>
#include<stdlib.h>
//create a struct
typedef struct{
//use a double pointer
char **dynamicArray;
int size;
int topValue;
}Stack;
/*
Inintializes the stack
Dyanmic Array will have a size of 2
*/
void intializeStack(Stack *stack){
stack->size = 2;
stack->topValue = 0;
//create a dyanmic array of char and set the value in the struct to the address for the newly created array
char *dyanmic;
dyanmic = malloc(2 * sizeof(char));
stack->dynamicArray = &dyanmic;
}
int main(){
Stack stack;
intializeStack(&stack);
printf("stack.size: %d\n", stack.size);
printf("stack.topValue: %d\n", stack.topValue);
int i;
for (i = 0; i < stack.size; i++){
*(stack.dynamicArray)[i] = 'r';
printf("%d value of the dynamic array: %c\n", i, *(stack.dynamicArray)[i]);
}
printf("Check if the stack is empty: %s\n",isEmpty(&stack)?"true":"false");
return 0;
}
The array is initially set to a size of 0. The problem is when I try to access the second element in the array, i get a segmentation fault error.
Segmentation fault (core dumped)
Am I doing something wrong in the implementation?