0

我正在编写一个函数,它可以反转一个 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[]但无法编译。什么时候应该使用数组以及什么时候应该使用指针,这让我感到困惑。

4

3 回答 3

1

char revStr[strlen(str)];分配一个局部变量(一个数组),当您超出reverStr函数范围时,它的内存被释放,这将导致其指针的任何进一步使用成为 UB(在大多数情况下为段错误)。

正确的方法是在堆上分配字符串并像这样返回它的指针

char* x = (char*)malloc(strlen(str));
...
return x;

这需要用户负责释放内存。或者,您可以将另一个参数传递给结果字符串的函数。

于 2013-10-01T05:00:17.980 回答
1

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

创建此数组时分配的内存在哪里?(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是不可修改的左值。

这是您的固定代码。我试图做更少的修改。

于 2013-10-01T04:52:18.533 回答
0

我认为您应该使用 malloc 分配一个新字符串。

const char* reverStr(const char *str)
{
    char *revStr;//using pointer 
    int i;

    revStr = (char*)malloc(strlen(str));//dynamic allocation
    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 a[] = {1,2,3};

内存中的地址可能:

--1000

|1|</p>

--1004

|2|</p>

--1008

|3|</p>

--1012

1000、1004 和 1012 是内存中地址的值。

因此,数组 a 的值应该是 1000。

printf("%d",a);// Yes, you can do it and you may get the value of 1000.

此外,您可以使用以下代码。

int a[] = {1,2,3};
int *b;
b= a;
printf("%d",b[1]);// you will get "2".

您可以认为指针是一个集合,而数组在集合中。

因此,您不能这样做;

int a[] = {1,2,3};
int c = 0;
int *b  = &c;

a = b;//error
于 2013-10-01T06:42:43.883 回答