c - 如果 C 只能返回一个值(int、char 等),那么它如何返回字符串文字(字符数组)?

标签 c string char

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/

相关文章:

c - 在 Win8 中使用 gcc 打印超出范围的数组元素

在 C 头文件中存储滤波器系数列表的最简洁方法

C++试图返回一个 double 组的字符串(有点)

c++ - 子串递归算法不起作用

ruby - 将字符分组以形成字符串

c - c中多维数组的函数传递

与 execv 通信()'ed program via pipe doesn' t 工作

c# - 如何在 C# 中使用字符串作为参数的方法

c - 如何使用 ptrace 获取 char*

c - 尝试根据 C 中的增量分配 char[] 的值