关于malloc和字符串常量的问题请教下大家,谢谢

zhuangshengen 2015-01-06 11:15:48
刚写代码时发现一个问题
char *Ip1=(const char *)malloc(sizeof(char)*16);
char *Ip1="192.168.0.1";
这样为什么有问题,是因为malloc分配的内存是在堆中,而字符串常量是在静态存储区中的缘故吗?如果把代码改成
//char *Ip1=(const char *)malloc(sizeof(char)*16);
char *Ip1="192.168.0.1";
这样就可以了,谁帮我解答一下,谢谢!
...全文
169 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
均陵鼠侠 2015-01-08
  • 打赏
  • 举报
回复
无链接的标识符只能声明一次。傻了吧? 6.7 Declarations 3 If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except that: — a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type; — tags may be redeclared as specified in 6.7.2.3. 4 All declarations in the same scope that refer to the same object or function shall specify compatible types.
starytx 2015-01-07
  • 打赏
  • 举报
回复
你所说的有问题是什么意思。问题描述不清
xionggch 2015-01-07
  • 打赏
  • 举报
回复
第一种不行是你重复声明变量Ip1,变量名相同当然不行 你把 char *Ip1="192.168.0.1"; 改成 Ip1="192.168.0.1"; 也是可以的,只是会出现内存泄露
Toper-Li 2015-01-07
  • 打赏
  • 举报
回复
第一种情况
char *Ip1=(const char *)malloc(sizeof(char)*16);
    char *Ip1="192.168.0.1";
=右边是const型,左为是非const 型,不可以直接赋值,可以去掉const属性。 再执行到第二行时第一行的堆内存会泄露。 第二种情况是定义一个指向常量存储区字符串的指针,没有问题。
此后三年 2015-01-06
  • 打赏
  • 举报
回复
char *ip1=(char *)malloc(sizeof(char)*16);   //不要用const char*
//char *ip1="192.168.0.1"; //malloc 分配的内存相当于数组, 数组的赋值显然不能这样
sprintf(ip1,"%s", "192.168.0.1");


第二种情况
const char *ip1 = "192.168.0.1"; //字符串的字面值是在只读常量区,要用const char *, 显式的说明这个变量不可改

69,335

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧