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

标签 c char

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

#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/

相关文章:

c - 从产生奇怪输出的字符串中删除字符

c - 堆栈粉碎检测到 C

c++ - 将 C uint8_t 指针 + 大小组合转换为 C++ 迭代器

c - 在循环中填充数组

c - 使用 scanf() 提取存储在字符串中的 URL 的域名扩展

c# - 如何将字符串 "brakemeup"转换为 char[stringlength] 数组?

c - 读取结构内部的字符时有什么问题吗?

c - 如何获取 *chars 并返回非整数?

JAVA - 从文本文件中读取,识别新行

c - 在 while 循环中与乘法一起使用的后递增