【问题标题】:C and string handlingC 和字符串处理
【发布时间】:2013-05-15 08:31:14
【问题描述】:

完整代码http://pastebin.com/6bdVTyPt 我的树代码运行良好,直到我发现我需要验证它不是文本的 id 所以它必须是字符串 插入函数 90 和 129 的字符串比较返回 8 尝试使用 (atoi) 并比较为整数不起作用 任何帮助表示赞赏
谢谢 这里是使用 atoi 代替 strcomp 的插入函数 http://pastebin.com/yeuktyAF 还是不行 插入函数

   struct node * insert2(struct node *root, char x[],char id[])
 {
if(!root)
{
    root=(struct node*)malloc(sizeof(struct node));
    free( root->data );
    free( root->id );// free previously allocated memory, if any
    root->data = strdup( x ); // malloc and copy
    root->id=strdup(id);
    root->left = NULL;
    root->right = NULL;
    //   printf("1\n");
    return(root);
}
printf("string comp %d of %s of %s\n",strcmp(root->id,id),root->id,id);
if((strcmp(root->id,id))>0){
    root->left = insert(root->left,x,id);
    printf("go left\n");
}
else
{
    if(strcmp(root->id,id)<0){
        printf("go right\n");
        root->right = insert(root->right,x,id);}
}
return(root);
}

【问题讨论】:

    标签: c data-structures tree


    【解决方案1】:

    线

    root=(struct node*)malloc(sizeof(struct node));
    

    root 分配内存但不初始化它。这意味着以下几行

    free( root->data );
    free( root->id );
    

    尝试释放未初始化(如此不可预测)的指针。这几乎肯定会崩溃。

    由于您刚刚分配了root,因此dataid 中不可能有任何先前的值可以释放。这意味着您可以将这三行简化为

    root=malloc(sizeof(*root));
    

    【讨论】:

    • 我是内存分配的新手,这是 stackflow 上某人的提示,因为它不起作用
    • 恐怕将呼叫添加到free 的建议非常糟糕。如果您之前为root-&gt;data 分配了内存,则必须这样做;在这种情况下,您不得对未初始化的指针执行此操作。
    • 你知道如何比较字符串中的数字吗?
    • 如果你的字符串只包含数字,为什么不改成int呢?如果确实需要将其存储为字符串,可以使用atoi 将其转换为int 内的insert2
    • pastebin.com/yeuktyAF @simonc 尝试这样做不起作用:(对不起你的时间
    【解决方案2】:

    您无法使用strcmp() 比较数字字符串。你应该将你的 ID:s 存储为整数,如果它们是这样的话,那么你可以直接比较它们。

    这还具有降低复杂性的好处,因为整数是固定大小的(假设unsigned long 足够长)您不需要使用strdup()

    另外,don't cast the return value of malloc() in C

    【讨论】:

    • 是的,我需要使用code int validid(char a[]){int c,flag=0; 来验证 id for(c=0; (a[c])!='\0'; c++) { if(isalpha(a[c])) flag=1; } if (flag==1) { 返回 0; } 否则返回 1; }
    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多