c - 指向字符的指针

标签 c string

我对如何将指针分配给字符有疑问

示例程序:

#include <stdio.h>

void main()
{
    const char str1[]="MANCHESTER";
    char *q;
    q=str1;
    *q='A';
    printf("%s\n",q);
}

在上面的程序中,我将一个字符指针分配给字符串“str1”,

当我用 gcc 编译程序时,收到以下警告:

ptr3.c: In function ‘main’:
ptr3.c:7:3: warning: assignment discards qualifiers from pointer target type

我无法理解该警告的含义。

最佳答案

我收到的警告:

2: warning: return type of 'main' is not 'int'
: In function 'main':
7: warning: implicit declaration of function 'printf'
7: warning: incompatible implicit declaration of built-in function 'printf'

添加 include stdio.h 和返回类型 int,修复了这些问题。

#include <stdio.h>

int main()
{
    char str1[]="MANCHESTER";
    char *q;
    q=str1;
    *q='A';
    printf("%s\n",q);
    return 0;
}

编辑: 我猜你不应该将 char 数组声明为 const,如果你打算直接或间接通过另一个指针修改它

关于c - 指向字符的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8871910/

相关文章:

c - 打印指针值

c++ - 如何设置 lua.dll 以便 lua.exe 不会在每个目录中都要求它?

ruby - Ruby 中的字符串是可变的吗?

c++ - 如何获取卫星资源 DLL 的模块句柄? (C++ Visual Studio )

c - 在 C 中随机填充结构类型的二维数组的问题

objective-c - 为 C 数组赋值

sql-server - 如何在列内保存 "\r"和 "\n"

php - 轻松从以特定方式格式化的字符串中提取数据

C:初始化字符指针(字符串)数组并使用 fgets 遍历文件以将值放入这些字符串

C 中的复杂数据类型给算法带来麻烦