2016-11-05 5 views
-3

私はこのコードを持っている:C - fscanfは文字ポインタでは動作しますが、2重字ポインタでは動作しません。

#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を1文字のポインタに変更し、*stringstringに変更すると動作します。どうしてこれなの?そして、ポインタの配列でfscanfを使うにはどうすればいいですか?

ありがとうございました。あなたは、ポインタへのポインタを割り当てると

+0

短い回答:mallocを間違って使用しています – Isaiah

+0

文字列の配列が必要ですか? 'string [0]'のように文字列であり、 'string [0] [0]'はcharですか?あなたは、配列char *と各文字列char *のためにmallocを行う必要があります。 – cpatricio

+0

Gotcha。ありがとう。 – 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を使用している理由は、私の実際のアプリケーションで(上記のコードは私のエラーをテストしているだけです)私は同時に3つの異なるダブルポインタをスキャンしています。 – Pen275

0

使用簡単char *ポインタ:

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

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

ダブルポインタは、文字列(または文字列の配列)へのポインタであり、第1のポインタは、元のコード内の任意の場所に初期化されません。さらに、最初のmallocmalloc(sizeof(char *)*20)のようになり、20文字列の配列を返します(ループ内で正しく初期化する必要があります)...

また、文字列の最大サイズを指定しないとバッファオーバーフローエラーが発生する可能性があるため、限界値や戻り値などについても検討する価値があります。

0

このソリューションは文字列の配列用ですが、別の文字列を配列に追加するたびに再割り当てすることもできます。

#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; 
} 
関連する問題