fwrite
给出正确的o / p时,在以下代码中。虽然memcpy
无效。
typedef struct
{
char *p1;
char *p2;
} node;
char s[] = "hello";
char t[] =" there";
node t1, t2;
char str;
FILE op_f;
t1.p1 = malloc(sizeof(strlen(s));
t1.p2 = malloc(sizeof(strlen(s));
t2.p1 = malloc(sizeof(strlen(s));
t2.p2 = malloc(sizeof(strlen(s));
t1.p1 = s;
t1.p2 = t;
copy(&t1,&t2);
str = malloc(sizeof(strlen(s) + strlen(t));
/* gives o/p hello there */
fwrite(t2.p1,1,strlen(s),op_f);
fwrite(t2.p1,2,strlen(s),op_f);
/* gives o/p there */
memcpy(str,t2.p1,strlen(s));
memcpy(str,t2.p2,strlen(s));
有没有办法将缓冲区复制到str ??
PS:以上代码仅供参考而非实际代码
答案 0 :(得分:2)
您应该将str声明为char数组,而不是单个char:
char str[500];
当str声明为数组时,str是一个指针(指向数组的第一个元素)。在你的代码中 - str是一个char,但不是指针。 Memcpy需要指针作为第一和第二个参数
另外,对没有sizeof的字符串使用malloc:
t1.p2 = malloc(strlen(s)+1);
此外,fwrite使用不正确,因为op_f
未使用fopen
初始化,如:
op_f = fopen("filename.txt", "w");
答案 1 :(得分:2)
存储在char数组中的字符串需要一个额外字节用于终结符。计算尺寸时,需要增加1个额外位置:
t1.p1 = malloc(strlen(s) + 1);
此代码
t1.p1 = s;
不会将文字从s
复制到p1
,但会将p1
设置为指向与s
相同的字符串。
这部分
str = malloc(strlen(s) + strlen(t));
不起作用,因为str是单个char
而不是char*
。你可以试试
char* str = malloc(strlen(s) + strlen(t) + 1);
如果您真的打算将其标记为C ++,则应考虑使用std::string
。它处理所有这些细节。
答案 2 :(得分:1)
我只是注意到你使用'char str'而不是'char * str',所以malloc(它是一个指向字符串的指针)的结果没有正确地存储在变量中。
此外,当你使用malloc时,你需要通过以下方式计算大小:strlen(s)+ strlen(t)+ 1.额外的字节用于终止NULL字符。而且你不需要在那里使用sizeof。 finally语句如下:
str = malloc(strlen(s) + strlen(t) + 1);
答案 3 :(得分:1)
首先,你应该在使用strcpy
时使用字符串(如果它们是空终止的),因为你的代码当前有一个被'hello'隐藏的错误,'''的长度相同,修复它你应该做的(同样适用于malloc
调用):
fwrite(t2.p1,sizeof(char),strlen(t2.p1),op_f);
fwrite(t2.p2,sizeof(char),strlen(t2.p2),op_f); //was also a bug here, you used p1 instead of p2 and the size of each element should have been 1
/* gives o/p there */
memcpy(str,t2.p1,strlen(t2.p1));
memcpy(str,t2.p2,strlen(t2.p2));
您的真正问题源于memcpy
不会增加指针,因此您应该这样做:
strcpy(str,t2.p1);
strcat(str,t2.p2);
或者如果你真的想使用memcpy:
memcpy(str,t2.p1,strlen(t2.p1));
memcpy(str + strlen(t2.p1) - 1,t2.p2,strlen(t2.p2));
最后,您的malloc
返回指针,而不是char
,因此str
应该是char*
。
答案 4 :(得分:1)
/* These are static. You SHOULD NOT write to either s or t! */
char s[] = "hello";
char t[] =" there";
typedef struct
{
char *p1;
char *p2;
} node;
node t1, t2;
/* I think you wanted "*str" here... */
char *str;
/* You definitely want "length of string + 1" here */
t1.p1 = malloc(strlen(s) + 1);
strcpy (t1.p1, s);
...
/* strcpy() and strcat() might be applicable here */
/* strncpy() and strncpy() might be even better - it depends... */
str = malloc(strlen(s)+1 + strlen(t)+1);
strcpy (str, s);
strcat (str, t);