gpt4 book ai didi

c - 指向结构体中 char 的指针,段错误

转载 作者:行者123 更新时间:2023-11-30 14:55:01 25 4
gpt4 key购买 nike

所以我创建了一个结构体,其中变量之一是指向动态字符数组的指针。所以我把它实现为一个指向指针的指针。然后我使用一个单独的函数来初始化结构:

#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;
}

数组的大小最初设置为 0。问题是当我尝试访问数组中的第二个元素时,出现段错误错误。

Segmentation fault (core dumped)

我在实现过程中做错了什么吗?

最佳答案

以下构造令人困惑并且最终是错误的:

for (i = 0; i < stack.size; i++){
*(stack.dynamicArray)[i] = 'r';
printf("%d value of the dynamic array: %c\n", i, *(stack.dynamicArray)[i]);
}

您实际上通过这种结构引用了**的第一级。试试这个:

for (i = 0; i < stack.size; i++){
stack.dynamicArray[0][i] = 'r';
printf("%d value of the dynamic array: %c\n", i, stack.dynamicArray[0][i]);
}

关于c - 指向结构体中 char 的指针,段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com