2016-10-19 22 views
1

です。わかりましたので問題があります。私はtab_stringと呼ばれる関数でCで文字列の配列を作成しようとしています。次のコードを実行しようとすると、テスト番号2のsegfaultがあることがわかります。最初のテストが動作する理由はわかりません。事前のおかげで文字列の配列は

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

#define NB_STRING 2 

void create_tab_string(char chaine[], char*** p_tab_string) { 
    char test[] = "Hey"; 
    char test2[] = "blabla"; 

    // Allocation 
    *p_tab_string = (char **)(malloc(NB_STRING*sizeof(char*))); 

    // Test 
    *p_tab_string[0] = test; 
    printf("%s \n", *p_tab_string[0]); 

    // Test 2 ERROR ????? 
    *p_tab_string[1] = test2; 
    printf("I have the second string \n"); 
    printf("%s \n", *p_tab_string[1]); 

} 




int main() { 
    int i; 
    char string_test[] = "I am a test"; 
    char **tab_string; 
    create_tab_string(string_test, &tab_string); 
    for(i = 0; i < NB_STRING; i++) 
     printf("%s \n", tab_string[i]); 
    return 0; 

} 
+2

テスト文字列は関数内でローカルであり、関数スコープ外では使用できません。 – LPs

+1

testとtest2に文字列を割り当てるには 'strdup'を使います –

答えて

0

あなたの機能は、あなたのテストのc-文字列(配列)の全てのアドレスの

void create_tab_string(char chaine[], char*** p_tab_string) { 
    char *test = "Hey"; 
    char *test2= "blabla"; 

    // Allocation 
    *p_tab_string = malloc(NB_STRING*sizeof(char*)); 

    // Test 
    (*p_tab_string)[0] = test; 
    printf("%s \n", (*p_tab_string)[0]); 

    (*p_tab_string)[1] = test2; 
    printf("I have the second string \n"); 
    printf("%s \n", (*p_tab_string)[1]); 
} 

まずあるべきでは外部からアクセスできる機能しないようにローカルです。 私は文字列リテラルへの単純なポインタに変更したので、文字列リテラルは関数の外部からアクセス可能です。

第2のことは、ポインタを参照解除する方法です。

*p_tab_string[1]を使用すると、存在しないp_tab_stringの2番目の項目を参照解除しています。 (*p_tab_string)[1]を使用して

あなたは*p_tab_stringが指すものの2番目の項目を参照解除、それはあなたが演算子の優先順位の問題を抱えているmain

+0

ありがとう、ありがとうございます。したがって、tab_stringにはcreate_tab_stringに文字列initializeを含めることはできませんか?たとえ私がstrdupを使用しても? – aurel94100

+0

'strdup'を使うことはできますが、この場合は文字列リテラルでメモリを2倍にします。他のシナリオでも役に立ちます。 – LPs

0

tab_string宣言されることができます。

あなたが使用する必要があります。

(*p_tab_string)[1] 

ない*p_tab_string[1]

また、コメントに書かれているように、テスト文字列は関数内でローカルであり、関数スコープ外では使用できません。それらを複製するか、ポインタを使用する必要があります。