編輯:好的,我聽到你們,我已經隔離了我的代碼,這給我的問題,編譯它,並確保它仍然給了我相同的結果,在這裏它的一部分去: 像以前一樣,segfault出現在for循環的第一個實例後面 strcpy(replace [j] - > utf8,strtok(data,「\ t」));再次感謝!使用malloc,結構和可能的參數的問題
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#define max_chars 45
#define max_UTF 5
#define max_ASCII 7
#define max_word_length 30
#define max_line_length 70
#define max_texto_line 5000
typedef struct {
char utf8[max_UTF];
char ascii_seq[max_ASCII];
int count;
} Replac;
void getTable(FILE *f, char inputfile[],Replac **replace){
char data[max_line_length];
int j;
f = fopen(inputfile, "r");
if (f == NULL) {
fprintf(stderr, "Can't open input file %s!\n",inputfile);
exit(1);
}
fgets(data,sizeof data,f);
for(j=0 ; strcmp(data,"\n") ; fgets(data,sizeof data,f), j++){
if (feof(f)) {
break;
}
strcpy(replace[j]->utf8, strtok(data, "\t"));
strcpy(replace[j]->ascii_seq, strtok(NULL, "\n"));
}
fclose(f);
}
int main(int argc, char *argv[]){
Replac *replace=malloc(max_chars * sizeof(Replac));
FILE *fpr,*f,*fpw;
int carprocess = 0;
setlocale(LC_ALL,"pt_PT.UTF-8");
setlocale(LC_COLLATE,"pt_PT.UTF-8");
getTable(f,argv[1],&replace);
}
我是從被格式化像這樣
UTFCHAR \tab asciichar
前
Á 'A
編輯完複製的字符的文本文件
- # - ## - ### - #### - #### + ##### + #### p
所以我是一個初學者使用C,我試過所有我能想到的,這似乎是一個非常簡單的事情要做,但由於我有這樣的麻煩清楚地表明我有我的知識中的一些缺口。
我不會打擾你完整的代碼,因爲它完美地工作,這只是我想做不同的事情,這就是當麻煩開始時。
總之我做了收集一組UTF8類型的字符,他們的ASCII更換,並將其存儲在一個結構如
typedef struct {
char utf8[max_UTF];
char ascii_seq[mac_ASCII];
} Replac;
然後在主,我做了類似的malloc程序這
Replac *replace=malloc(max_chars * sizeof(Replac));
如果我的思維過程是正確的,這將創造可用內存到*替換爲指向起始地址塊。
然後我做了掃描幾個UTF8字符和更換和存儲他們的結構功能,像
void getTable(FILE *f, char inputfile[],Replac **replace)
現在,調試器下面,看來我要創建新的變量替換類型是Replace **,它位於完全不同的地址上,但在該地址內部將該值存儲到我通過param傳遞的原始malloced結構中。
之後,我做以下調試器,並通過內存不會忽略搜索一個
strcpy(replace[0]->utf8, something I got from the table);
,我看到我第一次這樣做,malloc的結構的第一位置確實充滿了正確的數據。
隨後
strcpy(replace[0]->ascii_seq, corresponding ascii sequence to the previous UTF8 char);
和填充在所述存儲器塊中的下一存儲器位置。
所以我得到的東西像調試時我的變量看
地址替換=(Replac **)0xbf8104fc包含0x0878a008
地址*替換=(Replac *)0x0878a008包含整個結構 所以在地址0x0878a008內部,我得到utf8 char的數據,然後在地址0x0878a00d處得到ascii seq。
在循環的下一個實例的問題,當它的時間來
strcpy(replace[1]->utf8, something I got from the table);
我得到指令後,分段錯誤。
那麼你們怎麼看?我是否正確地處理了一些事情,而且我被語法或類似的東西搞砸了,還是我的知識缺陷的基礎?
謝謝,還有一個快樂的假期!
如果沒有真碼,這段代碼描述是具有挑戰性的,而IMO不足以確定段錯誤。所有人都可以看到真實的代碼。 – chux
歡迎來到SO。請查看此https://stackoverflow.com/help/mcve以創建代碼生成錯誤的最小示例。 –
你不能使用'Replac ** replace'就像你只有一個'Replac'。 http://stackoverflow.com/questions/12462615/how-do-i-correctly-set-up-access-and-free-a-multidimensional-array-in-c – Stargateur