这是一个简单的程序,其中函数abc返回一个数组。但输出是
Thanks
abcdefThanks
为什么这样?我希望 Thanks 只打印一次。 此外,我需要将 a 的大小设为6.在这个程序中,它并不重要,但我正在进行原始套接字编程,我需要它。 size = 6在那里的预定义头文件中声明。我该如何实施呢?
char *abc()
{
unsigned char *ch;
unsigned char a[7],c[6];
strncpy(a,"Thanks",strlen("Thanks"));
strncpy(c,"abcdef",strlen("abcdef"));
ch=malloc(50);
memset(ch,0,50);
memcpy(ch,&a,strlen(a));
memcpy(ch+strlen(a)+1,&c,strlen(c));
return ch;
}
int main()
{
char *a;
a=abc();
printf("\n%s\n",a);
printf("\n%s\n",(a+7));
fflush(stdout);
return 0;
}
谢谢:)
答案 0 :(得分:1)
调用strlen(a)
并未停止在您认为应该停止的地方,因为没有零终结符,垃圾内存会破坏您的结果。 strlen(字符串)不包括零终止符的计数
您应该执行以下操作(查看评论)
char *abc()
{
char *ch;
char a[7],c[7];
strncpy(a,"Thanks",strlen("Thanks")); // Watch out, strlen(string) doesn't include null terminator
a[6] = '\0'; // Prevent garbage from uninitialized memory to pester your ch and strlen(a)
strncpy(c,"abcdef",strlen("abcdef"));
c[6] = '\0';
ch=malloc(50);
memset(ch,0,50);
memcpy(ch,&a,strlen(a));
memcpy(ch+strlen(a),&c,strlen(c)); // No -1 because you want to cut the terminator off
return ch;
}
int main()
{
char *a;
a=abc();
printf("\n%s\n",a);
printf("\n%s\n",(a+7));
fflush(stdout);
return 0;
}
以上内容是用C ++编译的,但几乎可以通过一些调整来实现。
这里有类似内存的转储,其中#表示垃圾
char *abc()
{
char *ch;
char a[7],c[7];
strncpy(a,"Thanks",strlen("Thanks")); // Watch out, strlen(string) doesn't include null terminator
// a = "Thanks##################################.."
a[6] = '\0'; // Prevent garbage from uninitialized memory to pester your ch and strlen(a)
// a = "Thanks\0############################"
strncpy(c,"abcdef",strlen("abcdef"));
// c = "abcdef############################"
c[6] = '\0';
// c = "abcdef\0############################"
ch=malloc(50);
// ch = "###############################"
memset(ch,0,50);
// ch = "000000000000000000000000000000"
memcpy(ch,&a,strlen(a));
// ch = "Thanks000000000000000000000000"
memcpy(ch+strlen(a),&c,strlen(c)); // No -1 because you want to cut the terminator off
// ch = "Thanksabcdef00000000000000000"
return ch;
}
答案 1 :(得分:0)
您忘记通过附加0字节来终止字符串。
unsigned char a[7], c[7]; // 7 = 6+1 since "Thanks" and "abcdef" have 6 bytes
strncpy (a, "Thanks", 6);
a[6] = (char)0;
strncpy (c, "abcdef", 6);
c[6] = (char)0;
你的c
字符串太短而且未明确地为0结尾。因此,strlen(c)
为undefined behavior