[英]What is wrong with this concatenation function in C?
这是使用结构的作业分配的一部分,我似乎无法理解这一功能。 该函数为string_t * concat(string_t * s1,string_t * s2),它返回新的字符串结构。 到目前为止,这就是我所拥有的,只要到达编译器,它就会崩溃。 程序已编译,但是执行时出现“ file” .exe停止工作错误。 任何帮助将不胜感激。 谢谢!
typedef struct string{ //String struct (in .h file)
char *line;
int length;
} string_t;
string_t* concat(string_t *s1, string_t *s2) { //actual function (in .c)
int len1, len2;
len1 = length(s1);
len2 = length(s2);
int i, j, s;
string_t *newStr;
newStr = (string_t*)malloc(sizeof(string_t)*2);
for (i = 0; i<len1; i++) {
*((newStr->line)+i) = *((s1->line)+i);
}
for (j=0; j<len2; j++) {
*((newStr->line)+(i+j)) = *((s2->line)+j);
}
*((newStr->line)+(i+j))='\0';
return newStr;
}
concat(s1, s2); //tests function
newStr = (string_t*)malloc(sizeof(string_t)*2);
您为newStr
分配了内存,但没有为newStr->line
分配内存。 尝试类似:
newStr = malloc(sizeof *newStr);
newStr->line = malloc(s1->length + s2->length + 1);
旁注: *((newStr->line)+i)
可以写为newStr->line[i]
。
顺便说一句,这是一种无需使用丑陋的ptr数学语法的方法:
char* dest = newStr->line;
const char* src = s1->line;
while (*src)
{
*dest = *src;
++dest;
++src;
}
src = s2->line;
while (*src)
{
*dest = *src;
++dest;
++src;
}
*dest = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.