2017-10-16 39 views
1

我有一個解析文本文件並將其存儲在指針數組中的程序。我只有一個問題。我試圖在一個char **對象中存儲一個字符串數組,但是每當我給char **賦值時,就會發生seg故障。將值賦給char ** seg錯誤

#include "database.h" 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

char **get_values(int recipe_num, char *file) { 
    int placehold_num=recipe_num; 
    char *text=parse_recipes(file); 
    int num_recipes=count_recipes(file); 
    char **array_strings; 
    int index=-1; 
    for (int i=0;*(text+i)!='\0';i++) { 
     if (*(text+i)=='R' && *(text+i+1)=='e' && *(text+i+6)==':' && (text+i+7)==' ') { 
      i+=13; 
      index++; 
      for (int j=0;*(text+i+j-1)!='\n';j++) { 
       printf("%c",*(text+i+j)); 
       *(*(array_strings+index)+j)=*(text+i+j); 
      } 
     } 

    } 

} 

這打印出下一行,我從*(text+i+j)想要的字符,但賽格故障。我非常確定這不是一個被調用的函數的問題,我認爲它必須是我提供的方式array_strings。任何幫助是極大的讚賞。

+1

請發表[mcve]。你的調試器告訴你什麼? – melpomene

+1

你從來沒有爲'array_strings'指定任何內存。 – Barmar

+1

'text + i + j'不是訪問二維數組元素的正確方法。它應該是'text +我* row_size + j' – Barmar

回答

1

的問題是在

*(*(array_strings+index)+j)=*(text+i+j); 

您創建一個變量

char** array_strings; 

它現在指向一些垃圾,你可以通過調用

print("%p\n", array_strings); 

看到當前地址我強烈建議通過NULL初始化array_strings,因爲一旦你可以rec將一個指向內存的指針指向內存,然後將其寫入某個地方,在那裏可以存儲其他數據,然後您將銷燬這兩個數據。如果是NULL,您將永遠收到segfault。所以,此時你正試圖將一個值*(text+i+j)分配給內存中的一個隨機位置。

要做到,你想要什麼,你必須

char** array_strings = (char**)malloc(n * sizeof(char*)); 

其中n是你需要串的量,然後在循環做

array_strings[some_your_index] = text+i+j; 

array_strings[some_your_index]現在char*,爲text+i+j是。

+0

請參閱:[**我施放了malloc的結果嗎?**](http://stackoverflow.com/q/605845/995714)'char ** array_strings = malloc(sizeof * array_strings);'就夠了。然後您需要分配每個字符串,例如'array_strings [i] = malloc(strlen(str)+ 1);' –

+0

謝謝你的那篇文章,真的很有意思。我可以使用我的'char *'指針來指向字符串,例如,在舊的大字符串中用'\ 0'分隔。另外,對於我來說,閱讀'sizeof * array_strings'比'sizeof char *'更困難,我認爲這樣寫並不是一個問題 – Alex