C C++const与数组

栏目: C++ · 发布时间: 5年前

内容简介:在常讨论问题的qq group中看到大家对一个问题争论不一,本着学习的态度,编写demo,复习和学习相关知识,如有错误欢迎指正。告警内容如下:

在常讨论问题的qq group中看到大家对一个问题争论不一,本着学习的态度,编写demo,复习和学习相关知识,如有错误欢迎指正。

const例子一:

#include <stdio.h>

int main()
{
       /*这里加*表示数组parr内容不能修改即使用下面注释的语句赋值是非法的*/
    char * const parr[] = {"abc","def"};
    char *ptr = "Helloworld";
    
    //parr[1] = ptr;

    printf("parr[0] = %s\n",parr[0]);
    printf("parr[1] = %s\n",parr[1]);

    return 0;
}

const例子二:

#include <stdio.h>

int main()
{
       /*这里加*表示数组parr元素类型是const char *,使用gcc编译没问题,使用g++有告警,见下例*/
    const char * parr[] = {"abc","def"};
    char *ptr = "Helloworld";
    
    parr[1] = ptr;

    printf("parr[0] = %s\n",parr[0]);
    printf("parr[1] = %s\n",parr[1]);

    return 0;
}

const例子三:

#include <iostream>

int main()
{
      /*这里加*表示数组parr元素类型是const char *,不加const使用g++有告警*/
    const char * parr[] = {"abc","def"};
    char *ptr = "Helloworld";
    
    parr[1] = ptr;

    printf("parr[0] = %s\n",parr[0]);
    printf("parr[1] = %s\n",parr[1]);

    return 0;
}

告警内容如下:

root@52coder:~/workspace# g++ -g  -Wall -o  const const.cpp
const.cpp: In function ‘int main()’:
const.cpp:6:33: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
     char * parr[] = {"abc","def"};
                                 ^
const.cpp:6:33: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
const.cpp:7:17: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
     char *ptr = "Helloworld";
                 ^~~~~~~~~~~~
root@52coder:~/workspace#

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Everything Store

The Everything Store

Brad Stone / Little, Brown and Company / 2013-10-22 / USD 28.00

The definitive story of Amazon.com, one of the most successful companies in the world, and of its driven, brilliant founder, Jeff Bezos. Amazon.com started off delivering books through the mail. Bu......一起来看看 《The Everything Store》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具