2016-11-05 129 views
-3

我有這樣的代碼:C - fscanf可以使用字符指針,但不能使用雙字符指針?

#include<stdio.h> 
#include<stdlib.h> 

int main(void) 
{ 
    char **string = malloc(sizeof(char) * 20); 
    FILE *fp = fopen("input.txt", "r"); 
    fscanf(fp, "%s", *string); 

    printf("%s\n", *string); 

} 

此代碼生成段故障。但是,如果我將**string更改爲單個字符指針,並將其*string s更改爲string,它就會起作用。爲什麼是這樣?我怎樣才能使用指針數組fscanf?

謝謝。

+0

簡答:你使用的是malloc錯誤 – Isaiah

+0

你想要一個字符串數組嗎?像'string [0]'是一個字符串,'string [0] [0]'是一個char?你需要爲數組char **做一個malloc,然後爲每個字符串char *。 – cpatricio

+0

哎呀。謝謝。 – Pen275

回答

2
char **string = malloc(sizeof(char*)); // Pointer to pointer --> Alloc size of a POINTER 
*string = malloc(sizeof(char) * 20); // Dereference and then you can malloc chars 

當您分配一個指針的指針,你分配指針第一的規模。然後您可以取消引用該變量並分配指針內容的大小,在這種情況下指定它指向的字符數。

此外,您使用fscanf不僅不安全,而且完全不需要。

使用fgets代替:

fgets(*string, 20, fp); 

如果你想指針數組分配給字符,然後分配指針到指針時數項相乘的sizeof的char *。您還必須使用for循環爲每個字符指針分配內存,如上所示。

// Example code 
char **string = malloc(sizeof(char*) * 10); // Allocates an array of 10 character pointers 
if (string == 0) { 
    fprintf(stderr, "Memory allocation failed."); 
    exit(1); 
} 
int i = 0; 
FILE *fp = fopen("input.txt", "r"); 
if (fp == 0) { 
    fprintf(stderr, "Couldn't open input.txt for reading."); 
    exit(1); 
} 
for (; i < 10; ++i) { 
    string[i] = malloc(sizeof(char) * 20); // For each char pointer, allocates enough memory for 20 characters 
    if (string[i] == 0) { 
    fprintf(stderr, "Memory allocation failed."); 
    exit(1); 
    } 
    fgets(string[i], 20, fp); 
    printf("%s\n", string[i]); 
} 
+0

啊,我明白了,謝謝。我認爲分配雙指針就和單指針一樣。我使用fscanf的原因是,在我的實際應用程序(上面的代碼只是測試我的錯誤),我同時掃描到三個不同的雙指針。 – Pen275

0

使用簡單char *指針代替雙指針:

char *string = malloc(sizeof(char) * 20); 
FILE *fp = fopen("input.txt", "r"); 
fscanf(fp, "%s", string); 

printf("%s\n", string); 

雙指針是指向一個字符串(或字符串數​​組),和第一指針不會在原始代碼的任何地方進行初始化。此外,第一個malloc將必須看起來像malloc(sizeof(char *)*20) - 這將提供20個字符串的陣列(然後將需要在循環中正確初始化)...

此外,未指定字符串的最大大小是容易出現緩衝區溢出錯誤,所以值得查看的限制,返回值和類似的東西也是如此。

0

此解決方案適用於字符串數組,也可以在每次我們要向數組中添加另一個字符串時執行realloc。

#include<stdio.h> 
#include<stdlib.h> 

int main(void) 
{ 
    char **string = (char**)malloc(sizeof(char*) * 2); // array with 2 strings 

    string[0] = (char*)malloc(sizeof(char)*20); 
    FILE *fp = fopen("input.txt", "r"); 
    fscanf(fp, "%s", string[0]); 
    fclose(fp); // Remember to close after you don't need file handle anymore 
    printf("%s\n", string[1]); 

    string[1] = (char*)malloc(sizeof(char)*20); 
    FILE *fp2 = fopen("input2.txt", "r"); 
    fscanf(fp2, "%s", string[1]); 
    fclose(fp2); 
    printf("%s\n", string[1]); 

    return 0; 
}