我试图弄清楚返回两个扫描字符串的正确语法,以便我可以在主要使用指针中使用它们。
void get_user_info(char* user_string_one[20] , char* user_string_two[20]) {
char string_one[20] = "";
char string_two[20] = "";
string_one = "hello";
string_two = "goodbye";
*user_string_one = string_one;
*user_string_two = string_two;
return;
}
int main(void) {
char user_string_one[20] = "";
char user_string_two[20] = "";
get_user_info(user_string_one[20], user_string_two[20]);
printf("%s %s\n", user_string_one, user_string_two);
return 0;
}
我确信我犯了一个非常简单的错误,我似乎无法弄明白。
答案 0 :(得分:2)
#include <stdio.h>
#include <string.h>
void get_user_info(char* user_string_one, char* user_string_two)
{
strcpy(user_string_one, "hello");
strcpy(user_string_two, "goodbye");
}
int main(void)
{
char user_string_one[20];
char user_string_two[20];
get_user_info(user_string_one, user_string_two);
printf("%s %s\n", user_string_one, user_string_two);
return 0;
}
答案 1 :(得分:1)
字符串不能在C中以这种方式传递。当数组作为参数传递给函数时,该函数仅接收指向第一个元素的指针。指针不是数组。
您需要使用标准标头<string.h>
中的函数来复制字符串中的数据。例如;
#include <string.h>
void get_user_info(char* user_string_one , char* user_string_two)
{
strcpy(user_string_one, "hello");
strcpy(user_string_two, "goodbye");
}
int main(void)
{
char user_string_one[20] = "";
char user_string_two[20] = "";
get_user_info(user_string_one, user_string_two);
printf("%s %s\n", user_string_one, user_string_two);
return 0;
}
请记住,字符串文字(如"hello"
)表示为char
的数组,其中附加了终止'\0'
(值{0的char
) (表示结束的标记)。因此,使用六个字符"hello"
,'h'
,'e'
,'l'
,'l'
和'o'
在内存中表示'\0'
。 strcpy()
和类似的函数ASSUME字符串以该形式提供,并依赖于目标数组(被复制的数组)足够长,可以容纳所有内容,包括'\0'
标记。