我试图在C中做一些简单的事情,将两个名字(从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[]){
^
我真的不知道发生了什么。
答案 0 :(得分:4)
c->name1 = buff;
在此行之后,c->name1
和buff
具有相同的值。
free(buff);
由于c->name1
和buff
相等,这相当于free(c->name1)
,这显然不是您想要的。
另外,更改
void writeNames(names* c ,char n1[], char n2[]){
到
void writeNames(names* c ,char const n1[], char const n2[]){
答案 1 :(得分:0)
发布的代码:
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-&gt; name1和c-&gt; name2是指针,但没有特别指向任何东西。
这一行:
c->name2 = buff;
将'buff'的地址复制到c-&gt; 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