#include <stdio.h>
#include <string.h>
int main()
{
char* buf = "hello world";
printf("sizeof:{%d, %d}\n", sizeof(buf), strlen(buf)+1);
char buf2[32] = {0};
printf("sizeof:{%d, %d}\n", sizeof(buf2), strlen(buf2)+1);
return 0;
}
输出的结果是8, 13 \n 31,1
char*虽然表示字符串,但是本质上还是指针,指针就是4,8个字节
char buf[32]就不是指针了,起码sizeof出来是我们预想的效果
#include <stdio.h>
#include <string.h>
char* test(){
char buf[32] = {0};
//char* buf = (char*)malloc(sizeof(char)*32);
memset(buf, 0, sizeof(buf));
char* testString = "hello zs";
memcpy(buf, testString, strlen(testString)+1);
printf("{%s}\n", buf);
return buf;
}
int main()
{
char* tmp = test();
printf("{%s}", tmp);
//free(tmp);
return 0;
}
这个输出是
{hello zs} \n {(null)},因为数组是一个栈变量,已经被释放了,如果想不被释放
1.使用malloc,但是后续要free,见上述代码注释部分
2.使用char* 这个是字符串常量,是可以return出去的,但是字符变量只能在初始化的时候赋值,其他时候操作都会导致段错误,实际项目中字符串都要进行操作再return,所以只能是使用malloc
3.或许换一个编译器可能有效,用的是c++的编译器,可能老式的c语言的编译器在返回的时候使用char buf[32]; 接收到的也不是(null),有时间可以去尝试一下
#include <stdio.h>
#include <string.h>
char* test(){
char buf[32] = {0};
memset(buf, 0, sizeof(buf));
char* testString = "hello zs";
memcpy(buf, testString, strlen(testString)+1);
printf("{%s}\n", buf);
char* testString2 = NULL;
memcpy(testString2, buf, 32); //直接死机
char* testString2 = testString;
memcpy(testString2, buf, 32); //也是一样,直接死机
return buf; //return testString;
}
int main()
{
char* tmp = test();
printf("{%s}", tmp);
return 0;
}