C语言字符 串注意事项
下面这段代码是可以正常运行的
#include <stdio.h>
#include <math.h>
int main()
{
char str[80];
sprintf(str, "Pi 的值 = %%f", M_PI);
puts(str);
return(0);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
换成下面这种方式就不行了
#include <stdio.h>
#include <math.h>
int main()
{
char* str;
sprintf(str, "Pi 的值 = %%f", M_PI);
puts(str);
return(0);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
再换成下面这样又可以了
#include <stdio.h>
#include <math.h>
int main()
{
char* str = (char*)malloc(20);
sprintf(str, "Pi 的值 = %%f", M_PI);
puts(str);
return(0);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
推荐阅读