我正在编写一个函数来反转不在适当位置的 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/