记录错误
下面的一个简单代码:
#include <stdlib.h>
#include <string.h>
#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;
void fun(char* str){
*str = 's';
printf("%s\n",str);
printf("%c\n",*str);
}
int main(){
char *str= (char*)malloc(sizeof(char));
fun(str);
printf("%c\n",*str);
printf("%s\n",str);
}
两种方式都可以输出

原因是:c语言对于字符串常量的处理方法是:
在内存中开辟一个字符数组来村吹该字符串常量,并把开辟出的字符数组的首地址赋值给对应的字符串指针
另外:字符串数组的最后一个元素为‘\0’,否则输出有乱码


浙公网安备 33010602011771号