2012-03-31 55 views
-1

下面的代码给我下面的错误:反向串操作

incompatible types when assigning to type'char[10]' from type char* lvalue required as decrement operand.

什么可能会导致这样?

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

int main(void) 
{ 
    char *str1="1234"; 
    char str2[10]; 

    str2 = str2 + strlen(str1)-1;   //the str pointer is at 3rd position 
    char *p = str2+1;      //since it has to be a valid string, i assigned pointer p to give the null value at the end of the string. 
    *p = '\0'; 

    while(*(str2--) = *(str1++))   //moving the pointer of str down and pointer of str1 up and copy char from str1 to str2 

    printf("%s", str2); 

    return 0; 
} 

回答

3

STR2是一个数组,而不是一个指针,所以在左手侧str2 = ...是没有意义的C表达式。

要么STR2必须是指针,或使用一个额外的变量,如P,以获得表达

char *p = str2 + strlen(str1); 

同样(str2--)是没有意义的。使用额外的字符指针str2,并改变它。

将数组名称视为常量指针。它不能被改变,但可以在表达式的=的右侧使用。

+0

非常感谢你,现在就工作。 我想我搞砸了如何定义一个字符串的概念。例如, char * string =“123”; 不同于 char string [] =“123”; ? – 2012-03-31 16:38:48

+0

是的,声明的这两个'string'变量的类型是不同的。究竟“123”变成什么也不一样。通常,将'char * string =“123”'指向的字符视为常量。 – gbulmer 2012-03-31 16:44:42

+0

哦,我很抱歉,我是这个网站的新手。 现在被接受。非常感谢! – 2012-03-31 20:14:15