【问题标题】:What is wrong with this concatenation function in C?C中的这个连接函数有什么问题?
【发布时间】:2013-02-27 04:13:47
【问题描述】:

这是使用结构的家庭作业的一部分,我似乎无法理解这一功能。该函数是 string_t *concat (string_t *s1, string_t *s2),它返回新的字符串结构。这就是我到目前为止所拥有的,只要达到它就会使编译器崩溃。程序可以编译,但是执行时出现“file”.exe has stop working 错误。任何帮助将不胜感激。谢谢!

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

【问题讨论】:

  • 我建议你使用 size_t 作为你的 string.length
  • 你搜索过 strncpy 和 strcat 吗?你可以使用标准函数吗?
  • 不,我不能使用任何提供的功能。
  • @user2041197 我假设malloc() 不受该声明的约束。
  • 谁提供了malloc? :-) j/k

标签: c string concatenation


【解决方案1】:
newStr = (string_t*)malloc(sizeof(string_t)*2);

您为newStr 分配内存,但您没有为newStr-&gt;line 分配内存。尝试类似:

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

旁注:*((newStr-&gt;line)+i) 可以写成newStr-&gt;line[i]

【讨论】:

  • 是的,我知道第二部分,但是我们的教授不允许我们使用索引,只能使用指针算法
  • @user2041197 :( 谁付钱给这些人?
  • 我按照你说的做了,但是当我尝试测试它时,我做了 s3 = concat(s1,s2) 其中 s3 是 string_t* 并且我收到一个错误,说赋值使指针从没有 a 的整数演员
  • 同样,您可能会丢失 strlen() 调用(假设您已明智地确保您的 .length 成员是准确的)。
  • 我第二个,我没有注意到有一个 length 字段。
【解决方案2】:

顺便说一句,这是一种不用那种难看的 ptr 数学语法的 cat 方法:

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

【讨论】:

  • @modifiablelvalue,我不喜欢 C 中的后自增运算符,因为创建了一个临时运算符。大多数时候,几乎完全使用预增量运算符更加清晰和明显(恕我直言)。如果你喜欢人工解析,寻找程序员可以打包到一行中的所有可能的疯狂,那么它绝对没有错。
  • @modifiablelvalue,我也同意它确实有效,我只是不会在我自己编写的代码中使用它。
  • @modifiablelvalue,这对于第一个循环也不太适用,因为它会插入一个'\0'。不过它适用于第二个循环。
  • 所有人。根据您的批评,至少我的循环不会调用未定义的行为。只看你的,我就知道你没有费心去测试它。
  • @modifiablelvalue,被指控有罪,感谢您的帮助。我已经更正并测试了上面的行。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
相关资源
最近更新 更多