以下代码是VC++程序员大全的范例代码:
#define ELBA "Able was I ere I saw Elba" char *pszElba = ELBA;
char ch;

size_t x = 0;
size_t max = strlen(ELBA);
printf("%s\n", pszElba);
while (x < max / 2)
{
ch = pszElba[x];
pszElba[x] = pszElba[max - x - 1]; //运行到这里就出现非法操作?
pszElba[max - x - 1] = ch;
++x;
}
printf("%s\n", pszElba);
return (0);

解决方案 »

  1.   

    pszElba[x] = pszElba[max - x - 1]; //运行到这里就出现非法操作?char *pszElba = ELBA;
    因为系统默认以上语句为const类型,也就是系统默认其为一个常量字符串所以出现非法赋值,可以改为char pszElba[]=ELBA;
      

  2.   

    可是为什么以下代码别人可以我却不可以?
    是不是上面那些代码在别的编译环境中可能也可以通过?我用的是vc++2005//用指针修改常量的值#include <stdio.h>
    #include <iostream>
    #include <string.h>
    using namespace std;const char *NETWORK = "A network can be loosely defined "\
    "as the hardware and software that "\
    "allow two entitles to communicate.";char *str1 = (char *)NETWORK;
    char *str2 = (char *)NETWORK;
    int main()
    {
    char *s = strstr(str1, " two");
    if (s != NULL)
    strcpy(s, " 2 entitles to communicate");
    cout << str1 << endl;
    cout << str2 << endl;
    return (0);
    }
      

  3.   

    是不是上面那些代码在别的编译环境中可能也可以通过?不行,char *pszElba = ELBA; 这条语句说明pszElba是一个const指针char *str1 = (char *)NETWORK;
    char *str2 = (char *)NETWORK;NETWORK是一个const指针,所以强制转换会出错