[英]C char pointer and function argument passing
The two function getData and getData2 all can get right answers, are they valid? 两个函数getData和getData2都可以得到正确的答案,它们是否有效?
#include<stdio.h>
#include<stdlib.h>
void getData(const char** data) {
if(data == NULL) {
printf("NULL\n");
}
*data = "error";
}
const char* getData2() {
const char*p = "hello";
return p;
}
int main(){
const char *p = NULL;
getData(&p);
printf("data:%s\n",p);
printf("data2:%s\n",getData2());
}
char* p = "hello";
This is not allowed since C++11, but earlier versions allow it. 自C ++ 11起不允许这样做,但较早的版本允许。
The string literal "hello"
is stored in read-only memory that can't be modified, but a pointer to a non-const char
has the ability to let the memory be modified, which will crash during runtime when pointing at a string literal. 字符串文字
"hello"
存储在无法修改的只读内存中,但是指向非常量char
的指针具有修改内存的能力,当指向字符串文字时,它将在运行时崩溃。
A modern compiler won't accept such a conversion from const char*
to char*
. 现代的编译器不会接受从
const char*
到char*
的转换。
Same with the char** data
parameter and *data = "error";
与
char** data
参数和*data = "error";
assignment. 分配。
data
should be type as const char**
to make the assignment legal. data
类型应为const char**
以使分配合法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.