The two function getData and getData2 all can get right answers, are they valid?
#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.
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.
A modern compiler won't accept such a conversion from const char*
to char*
.
Same with the char** data
parameter and *data = "error";
assignment. data
should be type as const char**
to make the assignment legal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.