在下面用C语言反转字符串的代码中,当我使用索引访问字符串时,它起作用,res [i] = * p - ;
char *reverseString(char * s){
int l = strlen(s);
char *res = malloc(sizeof(s) + 1);
char *p = s + l - 1; // point to the last letter
int i = 0;
for(;i < l; i++)
res[i] = *p--;
return res;}
但是当我使用以下内容时 -
char *reverseString(char * s){
int l = strlen(s);
char *res = malloc(sizeof(s) + 1);
char *p = s + l - 1; // point to the last letter
int i = 0;
for(;i < l; i++)
*res++ = *p--;
return res;}
我得到一个空字符串作为返回值。
并且res ++ = * p--;在for()循环内导致错误:
char *reverseString(char * s){
int l = strlen(s);
char *res = malloc(sizeof(s) + 1);
char *p = s + l - 1; // point to the last letter
int i = 0;
for(;i < l; i++)
res++ = *p--;
return res;}
error: lvalue required as left operand of assignment
res++ = *p--;
^
我知道这是一个非常基本的问题,但有人可以帮我理解这个吗? 谢谢。
答案 0 :(得分:1)
因为您正在修改res
,因此返回字符串结尾的地址。您需要返回已分配的内存块的地址。
char *reverseString(char * s)
{
int l = strlen(s);
char *res = malloc(l + 1); //As suggested by BLUEPIXY. It will be optimal.
char *origAddr = res; //Store the original address of the memory block.
char *p = s + l - 1; // point to the last letter
int i = 0;
printf("Allocated addr: res[%p]\n", res);
for(;i < l; i++){
*res++ = *p--;
printf("addr: res[%p]\n", res);
}
*res = '\0'; //As suggested by BLUEPIXY to terminate the string.
return origAddr; /* Return the original address. */
}