簡體   English   中英

指向結構體中char的指針,分段錯誤

[英]Pointer to pointer to char in struct, segmentation fault

因此,我創建了一個結構,其中一個變量是指向chars動態數組的指針。 因此,我將其實現為指向指針的指針。 然后,我使用了一個單獨的函數來初始化結構:

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

從這個意義上抽象f :)

char **dyanmic; 
dyanmic = malloc(sizeof(char *));
*dyanmic = malloc(2 * sizeof(char)); 
stack->dynamicArray = dyanmic; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM