简体   繁体   English

C中的此串联函数有什么问题?

[英]What is wrong with this concatenation function in C?

this is part of a homework assignment using structs and I can't seem to understand this one function. 这是使用结构的作业分配的一部分,我似乎无法理解这一功能。 The function is string_t *concat (string_t *s1, string_t *s2) and it returns the new string struct. 该函数为string_t * concat(string_t * s1,string_t * s2),它返回新的字符串结构。 This is what I have so far, and it crashes the compiler whenever it's reached. 到目前为止,这就是我所拥有的,只要到达编译器,它就会崩溃。 The program compiles but, "file".exe has stopped working error comes up when executing. 程序已编译,但是执行时出现“ file” .exe停止工作错误。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

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);

You allocate memory for newStr but you don't allocate memory for newStr->line . 您为newStr分配了内存,但没有为newStr->line分配内存。 Try something like: 尝试类似:

newStr = malloc(sizeof *newStr);
newStr->line = malloc(s1->length + s2->length + 1);

Side note: *((newStr->line)+i) can be written as newStr->line[i] . 旁注: *((newStr->line)+i)可以写为newStr->line[i]

BTW, here's a way to cat without that ugly ptr math syntax: 顺便说一句,这是一种无需使用丑陋的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM