指向结构中char的指针,分段错误

时间:2017-09-19 19:44:10

标签: 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)

我在实施中做错了吗?

2 个答案:

答案 0 :(得分:1)

以下构造令人困惑且最终不正确:

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

答案 1 :(得分:0)

从这个意义上抽象出来:)

public class SampleClassOnly {
   public static void main(String[] args) {
     int n = 100;
     for(int j = n; j > 0; j++){
     System.out.println(j);
     }
   }
}