在C中返回和断言字符串时出现问题
我的目标是编写两个子程序,一个用于将两个字符串组合在一起,另一个用于断言它。但即使我在打印结果时没有任何问题,with return语句仍然会不断给出错误 这是我的密码:在C中返回和断言字符串时出现问题,c,return,assert,C,Return,Assert,我的目标是编写两个子程序,一个用于将两个字符串组合在一起,另一个用于断言它。但即使我在打印结果时没有任何问题,with return语句仍然会不断给出错误 这是我的密码: #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> char task5(char string1[50], char string2[50]) { char un
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
char task5(char string1[50], char string2[50])
{
char united[50];
int i, j, length1, length2;
for (i=0; string1[i]!='\0'; i++);//here we determine the length of inputted word
{
length1 = i;
}
for (j=0; string2[j]!='\0'; j++);//here we determine the length of inputted word
{
length2 = j;
}
for(i=0; i<length1; i++)
{
united[i]=string1[i];
}
for(j=0; j<length2; j++)
{
united[i+j]=string2[j];
}
return united;
}
void test_task5()
{
assert(task5("Hello", "World")=="HelloWorld");
}
int main()
{
task5("Hello", "World");
test_task5();
return 0;
}
task5返回一个char单字母,但您希望它返回带有断言的字符串 你对tas5的论点是char[50]。它们降级为指针,因此最好将其写为:
task5(const char *string1, const char *string2)
当您试图用==比较两件事时,您比较的是地址,而不是值。使用strcmps,改为s2
更改了task5的签名,以使其更安全地使用,即dest_len,并使用dest是按值传递的事实,因为我们可以在task5中前进指针,并且地址在调用方上下文中保持不变:
#include <assert.h>
#include <stdio.h>
#include <string.h>
void task5(const char *src, const char *src2, char *dest, size_t dest_len) {
assert(strlen(src) + strlen(src2) + 1 <= dest_len);
// strcat(dest, src);
for(int i = 0; src[i]; *dest++ = src[i++]);
// strcat(dest, src2);
for(int i = 0; src2[i]; *dest++ = src2[i++]);
*dest = '\0';
}
int main() {
const char src[] = "Hello";
const char src2[] = "World";
char dest[sizeof(src) + sizeof(src2) - 1];
task5(src, src2, dest, sizeof(dest));
assert(!strcmp(dest, "HelloWorld"));
return 0;
}
不能从函数返回本地数组。请参阅,您应该会收到有关return united的编译器警告。返回类型为char,但return united尝试返回char*。您正在从函数task5返回局部变量的地址谢谢您的代码,但是我不能使用strcat来完成这项任务,我知道这很愚蠢,但这是老师的要求。你可以自己实现一个版本的strcat。更新答案,以strcat作为注释:-