[英]Error in appending two string pointers using strncat()
我有一个函数应该返回一个带有char *first_str
& char *N
的字符串
char *append(char *N) {
char *first_str = "first";
return strcat(*first_str, *N);
}
int main(void) {
char *N = "second";
printf("%s", append(N));
return 0;
}
它在最后给出以下警告消息和段错误:
temp.c: In function ‘appendOneChar’:
temp.c:7:17: warning: passing argument 1 of ‘strncat’ makes pointer from integer without a cast [-Wint-conversion]
7 | return strncat(*first_str, *N, 1);
| ^~~~~~~~~~
| |
| char
In file included from temp.c:3:
/usr/include/string.h:133:40: note: expected ‘char * restrict’ but argument is of type ‘char’
133 | extern char *strncat (char *__restrict __dest, const char *__restrict __src,
| ~~~~~~~~~~~~~~~~~^~~~~~
temp.c:7:29: warning: passing argument 2 of ‘strncat’ makes pointer from integer without a cast [-Wint-conversion]
7 | return strncat(*first_str, *N, 1);
| ^~
| |
| char
In file included from temp.c:3:
/usr/include/string.h:133:71: note: expected ‘const char * restrict’ but argument is of type ‘char’
133 | extern char *strncat (char *__restrict __dest, const char *__restrict __src,
| ~~~~~~~~~~~~~~~~~~~~~~~^~~~~
Segmentation fault
那么这是怎么回事?
预期输出: firstsecond
为了演示,工作代码如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *append(char *N) {
char *first_str = malloc(strlen(N) + 6); // 6 = strlen("first") + 1 (null terminator)
if (first_str== NULL) {
// malloc failed, handle error
return NULL;
}
strcpy(first_str, "first");
return strcat(first_str, N);
}
int main(void) {
char *N = "second";
char *concat = append(N);
if (concat == NULL) {
// append function returned an error
return 1;
}
printf("%s", concat);
free(concat); // Free the dynamically allocated memory
return 0;
}
来自 strcat 手册: char *strcat(char *destination, const char *source)
注意:当我们使用 strcat() 时,目标字符串的大小应该足够大以存储结果字符串。 如果不是,我们将得到分段错误。 这就是为什么您需要一个大小为 12 (5+6+1) 的数组的原因,请注意存储在连接字符串末尾的 '\0' 的 +1。
注意 2:您需要 malloc 将内存分配给堆,以便内存保持不变,直到您使用“free”清除它。 您在函数中创建的变量将分配在堆栈上,并在函数返回时自动释放。 因此,在您的示例中,当函数“append”返回时,内存不再可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.