我正在实现一个绳索数据结构。如何传递我的字符串值?它们显示为“(null)”。我认为我的字符字设置不正确。我是 C 新手,来自 C++。这最终将成为一个文本编辑器,但现在我只是尝试按索引号在有序列表中显示输入的字符串。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct treeNode
{
int i, length;
char word;
struct treeNode *left;
struct treeNode *right;
} treeNode;
treeNode *insert(treeNode *node, int i, char word, int length)
{
printf("Insert %d :", word);
if(node==NULL)
{
treeNode *temp;
temp = (treeNode *)malloc(sizeof(treeNode));
temp->i = i;
temp->word;
temp->length;
temp->left = temp->right = NULL;
return temp;
}
if(i >(node->i))
node->right = insert(node->right, i, word, length);
else if(i < (node->i))
node->left = insert(node->left,i,word,length);
return node;
}
void PrintInorder(treeNode *node)
{
if(node==NULL)
return;
PrintInorder(node->left);
printf("%d", node->i);
printf("%s", node->word);
PrintInorder(node->right);
}
void main()
{
treeNode *root = NULL;
char word[256];
int length, a;
for(a = 0; a < 3; a++)
{
printf("Enter word: ");
scanf("%s", word);
length = strlen(word);
root = insert(root, a, *word,length);
}
printf("Print in order:\n");
PrintInorder(root);
}
最佳答案
您需要在 treeNode
中使用 char *word
来表示一个字符串(一段绳子)。您需要使用 char *word
定义 insert
,并使用 word
调用它,而不是 *word
(因为在调用上下文,这将是 word
的第一个字符)。最后,您实际上需要一些分配:temp->word = word
。
代码中还有其他逻辑错误,特别是没有以任何重要方式处理 i
或 length
,但它们至少不会阻止您按顺序打印.
编辑:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct treeNode
{
int i, length;
//char word; // this only stores a single character
char *word; // needs to be a pointer so it can point to string
struct treeNode *left;
struct treeNode *right;
}treeNode;
// this accepts a single character as `word`, not a string
// treeNode *insert(treeNode *node, int i, char word, int length){
// needs to be `*word`
treeNode *insert(treeNode *node, int i, char *word, int length)
{
printf("Insert %d :",word );
if(node==NULL)
{
treeNode *temp;
temp = (treeNode *)malloc(sizeof(treeNode));
temp->i = i;
// temp->word; // This does nothing;
temp->word = word; // This assigns the pointer
temp->length;
temp->left = temp->right = NULL;
return temp;
}
// This logic does not work correctly... What is `i` specifically?
if(i >(node->i))
node->right = insert(node->right,i,word,length); // OK because passing pointer
else if(i < (node->i))
node->left = insert(node->left,i,word,length); // OK because passing pointer
return node;
}
void PrintInorder(treeNode *node)
{
if(node==NULL)
return;
PrintInorder(node->left);
printf("%d",node->i);
printf("%s",node->word);
PrintInorder(node->right);
}
void main()
{
treeNode *root = NULL;
char word[256];
int length, a;
for(a = 0; a < 3; a++)
{
printf("Enter word: ");
scanf("%s", word);
length = strlen(word);
// root = insert(root, a, *word,length); // This would only pass the first character of `word`
root = insert(root, a, word,length); // We want to pass the word pointer
}
printf("Print in order:\n");
PrintInorder(root);
}
关于c - 在 C 中传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41993671/