将返回的cstring分配给变量

时间:2013-10-01 04:50:02

标签: 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;
}

给出 warning:函数返回局部变量的地址[默认启用] | 警告:初始化从指针目标类型[默认启用] |

中丢弃'const'限定符

我尝试将char* tmp更改为char tmp[],但无法编译。当我应该使用数组并且应该使用指针时,它会让我感到困惑。

3 个答案:

答案 0 :(得分:1)

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
}

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

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

你可以这样做:

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

但你不能这样做:

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

因为它们(数组和指针)类型不相同而数组p是不可修改的l值。

这是您固定的code。我试图减少修改。

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分: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 |

- 1004

| 2 |

- 1008

| 3 |

- 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
相关问题