【发布时间】:2017-02-12 20:29:50
【问题描述】:
我正在开展一个项目,该项目需要将两个字符串“交织”在一起,以便它们交替使用每个字符。 示例:“Apple”和“BEAR”将变为“ABpEpAlRe”
这是我目前的功能:
void printMessage(char name[], char num[])
{
char eticket[(sizeof(name)/sizeof(char))+((sizeof(num))/sizeof(char))] = ""; //make array with enough space for both strings
int i;
for(i=0;i<(sizeof(eticket)/sizeof(char));i++)
{
char tmp[1] ={name[i]}; // i have to change the char name[i] and num[i] to its own char array so i can use it in strcat
char tmp2[1] ={num[i]};
if(i<(sizeof(name)/sizeof(char))-1) //if name string is finished, don't concatenate
{
strcpy(eticket,strcat(eticket, tmp));
}
if(i<(sizeof(num)/sizeof(char))-1) //if num string is finished, don't concatenate
{
strcpy(eticket,strcat(eticket, tmp2));
}
}
printf("Your name is %s and your flight number is %s.\nYour e-ticket is: %s.\n\n", name, num, eticket);
}
其中 eticket 是最后一个字符串。
结果:
Your name is Connor and your flight number is MIA1050.
Your e-ticket is: CMMoIInAAn11o00r550.
*** stack smashing detected ***: ./a.out terminated
Aborted
我知道堆栈粉碎意味着缓冲区溢出,但更让我担心的是,由于某种我无法弄清楚的原因,num[] 数组在最终字符串中的字符加倍。 而不是“CMMoII ...”应该是“CMoI ...” 这可能是缓冲区溢出的副作用吗?
提前致谢。
【问题讨论】:
-
sizeof(name)和sizeof(num)是指针的大小,而不是调用函数中数组的大小。你可以删除所有sizeof(char),因为它的定义是1。 -
您需要使用
strlen()而不是sizeof()。对于初学者;可能还有其他问题。 -
等等等等调试器等等等等
标签: c arrays string buffer concatenation