char *returnString()
{
return "hello World";
}
int main()
{
printf("\n %p ", &returnString());
return 0;
}
returnString()
在这里返回什么?它返回'h'
的地址吗?
如果是,那么 "hello world"
存储在哪里(堆栈/堆)?如何查看(打印)它的地址?
char Hello[] = "It's Hello";
char something[] = "something like ";
char *readInput(char str[]) {
char *tempStr = NULL;
if (strcmp(str, "hello") == 0)
return Hello;
tempStr = (char *)malloc((strlen(something)) + (strlen(str)) + 1);
strcpy(tempStr, something);
strcat(tempStr, str);
return tempStr;
}
int main() {
int i;
char *userInput[] = { "hello", "xyz", "hello", "abc" };
char **result = (char **)malloc(sizeof(char *) * (4));
for (i = 0; i < 4; i++) {
result[i] = (char *)malloc(15);
result[i] = readInput(userInput[i]);
}
printf("\n\n");
strcpy(Hello, "String is Changed"); // this should not affect result[0] && result[2]
for (i = 0; i < 4; i++)
printf("\t\t %s", result[i]);
printf("\n");
return 0;
}
在第二个程序中应该进行哪些修改,以便即使在此之后 ---> strcpy(Hello, "String is Changed");
result[0]
的值> 和 result[2]
不会改变。
最佳答案
语句return "hello World";
返回一个char *
:指向字符串文字第一个字符的指针"hello World"
。此字符串文字存储为 12 个 char
的空终止数组。它通常与程序的其他常量数据一起存储在内存中。
尝试修改此数组会调用未定义的行为。它应该被视为 const
并通过 const char *
进行处理。将此函数定义为会更安全
const char *returnString(void) {
return "hello World";
}
此外,您不应在 printf
语句中的函数调用中使用 &
。它应该是:
int main(void) {
printf("\n%p\n", (void*)returnString());
return 0;
}
关于你的第二个问题,你应该返回 Hello
中字符串的副本。使用这个简单的方法:
if (strcmp(str, "hello") == 0)
return strdup(Hello);
strdup()
没有在 C 标准中定义,但在 Posix 标准中指定。如果它在你的系统中不可用,它可以定义为:
char *strdup(const char *s) {
char *p = malloc(strlen(s) + 1);
if (p) strcpy(p, s);
return p;
}
关于c - 如果 C 只能返回一个值(int、char 等),那么它如何返回字符串文字(字符数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39002974/