【问题标题】:Parsing a char array to array with function使用函数将 char 数组解析为数组
【发布时间】:2015-04-05 21:42:58
【问题描述】:

我有以下功能:

void get_name(char *a)
{
    char format[10];

    sprintf(format, "%%%ds", SIZE-1);
    scanf(format, a);
}

然后我在另一个函数中调用它,如下所示:

CListNode *initialize_list(int n)
{

    CListNode *end, *new, *first;
    CListNode *head=NULL;
    int i;
    char new_name[10];

    first=(CListNode *) malloc(sizeof(CListNode));
    strcpy(first->name, get_name(new_name));
    first->next=head;
    head=first;


    for (i=0; i<n-1; i++) {
        end=(CListNode *) malloc(sizeof(CListNode));
        strcpy(end->name, get_name(new_name));
        first->next=end;
        end->next=NULL;
    }

    return end;

}

CListNode 所在的位置

typedef struct node
{
    char name[10];
    struct node * next;
} CListNode;

但我收到此错误“Passing 'void' to parameter of in compatible type 'const char *'”两次(每个 strcpy 1 个)。

我做错了什么?

【问题讨论】:

    标签: c arrays function


    【解决方案1】:

    代替

    strcpy(first->name, get_name(new_name));
    

    你可以的

    get_name(new_name);
    strcpy(first->name, new_name);
    

    如果您想保留strcpy(end-&gt;name, get_name(new_name)); 行,请更改函数,使其返回指向输入的指针:

    char *get_name(char *a)
    {
        char format[10];
    
        sprintf(format, "%%%ds", SIZE-1);
        scanf(format, a);
        return a;
    }
    

    问题是strcpy(a,b) 将字符串b 复制到a,但您的函数返回void,所以strcpy 空手而归。

    从外观上看,您正在尝试以 ala lisp 的函数式编程。请注意,您的函数get_name 具有破坏性,因此它会修改newname

    【讨论】:

      【解决方案2】:

      get_name 被声明为返回 void,因此在对 strcpy(first-&gt;name, get_name(new_name)); 的调用中,您试图将任何内容 (void) 复制到 first->name 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-06
        • 1970-01-01
        • 1970-01-01
        • 2013-03-16
        • 1970-01-01
        • 2018-06-24
        • 2011-06-08
        • 2016-06-06
        相关资源
        最近更新 更多