2017-05-12 7 views
-3

i + 1のサイズでtempを作成しようとしましたが、iまたはsizeの値が何であっても、私のコードは常にサイズの文字列を作成しますこれはどうやって起こりうるのでしょうか?作成した配列に予期しないサイズがある

void addWord(char* word, trie* root) { 
for(int i = 0; i < strlen(word); i++) { 
    OBJTYPE v = word[i]; 
    if(root->children[(int)v] == NULL) { 
     trie* node = constructor(root); 
     node->value = v; 
     int size = i+1; 
     char temp[size]; 
     printf("The value of i is : %d\n", i); 
     printf("The value of size is : %d\n", size); 
     printf("The copy has the size of: %d\n", strlen(temp)); 
     strncpy(temp, word, i + 1); 
     printf("Now the size of the copy is: %d\n", strlen(temp)); 
     node->partWord = temp; 
     root->children[(int)v] = node; 
     root = node; 
     printf("The node has value: %c\n", root->value); 
     printf("The node stored word has size of : %d\n", strlen(root->partWord)); 
     printf("The node has stored word: %s\n", root->partWord); 
    } else { 
     root = root->children[(int)v]; 
    } 
} 
trie* end = constructor(root); 
end->value = '&'; 
char temp[strlen(word)]; 
strcpy(temp, word); 
end->partWord = temp; 
root->children[SIZE + 1] = end; 
} 

Here is the debugging message

+1

Strncpyが有効な文字列を作成するとは限りません。 – stark

+0

将来のヒント:デバッガを使用してください。この種の問題では、多くの助けになります。また、それは言語を学ぶための本当に素晴らしいツールです! – Garf365

答えて

1

strlenは、\0の最初の発生をチェックします。あなたはここで行うようにあなたは、初期化されていない配列でstrlenを呼び出すとき:

char temp[size]; 
    printf("The value of i is : %d\n", i); 
    printf("The value of size is : %d\n", size); 
    printf("The copy has the size of: %d\n", strlen(temp)); 

配列の内容はランダムであり、そしてあなたが初期化されていない変数を使用することを許可されていないので、あなたのプログラムの動作は未定義ました。

0

strlen()だけ引数ポインタから始まる非ゼロバイトをカウントします。 temp配列はどこでもゼロにならないようです。

関連する問題