将字符串传递给 C 中的结构

Passing strings to a struct in C

我正在尝试在 C 中做一些简单的事情,即将 2 个名称(从 argv[])传递给一个结构。 我觉得我到处都是这个。 这是我的代码:

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

typedef struct
{
    char *name1;
    char *name2;

}names;

void writeNames(names* c ,char n1[], char n2[]){
    char* buff;

    buff = malloc(strlen(n1)*sizeof(char)+1);
    strcpy(buff, n1);
    c->name1 = buff;
    free(buff);
    buff = NULL;

    buff = malloc(strlen(n2)*sizeof(char)+1);
    strcpy(buff, n2);
    c->name2 = buff;
    free(buff);
    buff = NULL;
}

int main(int argc, char const *argv[])
{
    names card;
    writeNames(&card,argv[1],argv[2]);
    printf("%s %s\n",card.name1,card.name2);
    return 0;
}

这就是我得到的:

naming.c: In function ‘main’:
naming.c:31:2: warning: passing argument 2 of ‘writeNames’ discards ‘const’ qualifier from pointer target type [enabled by default]
  writeNames(&card,argv[1],argv[2]);
  ^
naming.c:12:6: note: expected ‘char *’ but argument is of type ‘const char *’
 void writeNames(names* c ,char n1[], char n2[]){
      ^
naming.c:31:2: warning: passing argument 3 of ‘writeNames’ discards ‘const’ qualifier from pointer target type [enabled by default]
  writeNames(&card,argv[1],argv[2]);
  ^
naming.c:12:6: note: expected ‘char *’ but argument is of type ‘const char *’
 void writeNames(names* c ,char n1[], char n2[]){
      ^

我不太明白发生了什么。

c->name1 = buff;

在这一行之后,c->name1buff 具有相同的值。

free(buff);

因为c->name1buff是相等的,所以这相当于free(c->name1),这显然不是你想要的。

另外,改变

void writeNames(names* c ,char n1[], char n2[]){

void writeNames(names* c ,char const n1[], char const n2[]){

发布代码:

void writeNames(names* c ,char n1[], char n2[]){
    char* buff;

    buff = malloc(strlen(n1)*sizeof(char)+1);
    strcpy(buff, n1);
    c->name1 = buff;
    free(buff);
    buff = NULL;

    buff = malloc(strlen(n2)*sizeof(char)+1);
    strcpy(buff, n2);
    c->name2 = buff;
    free(buff);
    buff = NULL;
}

胡说八道。

原因是c->name1和c->name2是指针,并没有具体指向什么。

这一行:

c->name2 = buff;

将'buff'的地址复制到c->name2

的首地址

这似乎不是我们想要的。

始终检查系统错误

总是在退出前清理内存分配

sizeof( char ) 始终为 1,因此对 malloc

没有影响

建议:

void writeNames(names* c ,char n1[], char n2[])
{
    c->name1 = malloc(strlen(n1) +1);
    if( NULL == c->name1 )
    { // then, malloc failed
        perror( "malloc for name1 failed");
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    strcpy(c->name1, n1);


    c->name2 = malloc(strlen(n2) +1);
    if( NULL == c->name2 )
    { // then, malloc failed
        perror( "malloc for name2 failed");
        free( c->name1 );
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    strcpy(c->name2, n2);
} // end function: writeNames