c - 将返回的 cstring 分配给变量

标签 c arrays return-value cstring

我正在编写一个函数来反转不在适当位置的 cstring 但返回反转的 cstring。返回类型究竟应该是什么?

#include <stdio.h>
#include <string.h>

const char* reverStr(const char *str)
{
    char revStr[strlen(str)];
    int i;
    for(i = strlen(str)-1; i >= 0; i--)
        revStr[strlen(str)-1-i] = str[i];
    printf("returned value should be %s\n", revStr);
    return revStr;
}

int main()
{
    char aStr[] = "hello";
    char aStr2[] = "goodbye";
    printf("%s %s", aStr, aStr2);
    char* tmp = reverStr(aStr);//tmp now has garbage
    printf("\n%s", tmp);
    printf(" %s", aStr);
    return 0;
}

给予 警告:函数返回局部变量的地址[默认启用]| 警告:初始化从指针目标类型中丢弃“const”限定符[默认启用]|

我尝试将 char* tmp 更改为 char tmp[] 但无法编译。我很困惑什么时候应该使用数组,什么时候应该使用指针。

最佳答案

revStr 是一个数组,在reverStr 函数退出后不复存在。更多内容请阅读:

Where is the memory allocated when I create this array? (C)

const char* reverStr(const char *str)
{
    char revStr[strlen(str)];

    return revStr;  /* Problem - revStr is a local variable trying to access this address from another function will be erroneous*/
}


const char* reverStr(const char *str)
{
    const char * revStr = str;

    return revStr;  //ok
}

可修改的左值不能有数组类型。左值是可以出现在赋值左侧的表达式。当您想要声明许多相同类型的变量时,您可以使用数组,并且您可以轻松地对其进行索引,因为它的布局在某种意义上是连续的。

当您想要不断更改变量指向的地址的值时,您可以使用指针。

你可以这样做:

char * p = "test";
p = "new";

但是你不能这样做:

    char p[] = "test";
    char *p1 ="test1";
    p = p1; //error

因为它们(数组和指针)的类型不同,并且数组 p 是不可修改的左值。

这是您的固定 code .我尽量减少修改。

关于c - 将返回的 cstring 分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19108227/

相关文章:

c - 如何在C中获取当前时间与时区变化的匹配

c - 无法旋转半立方体

php - 重复的数组键(通知 : member variable "a" returned from __sleep() multiple times)

java - 使用 Java 和 Hibernate 从存储过程获取返回值(标量),而不是结果表

c - 嵌套循环比较数组中的整数

c - 使用 malloc 函数的随机数

arrays - Powershell中的奇怪脚本问题

c++ - 使用 cin 更改二维字符串数组值

c# - 如何将键值从字典保存到字符串

vb.net - 正确的编程——一个函数应该在所有代码路径上返回一个值吗?