关于malloc分配内存的问题
zhyrs 2011-03-15 01:48:52 #include <iostream>
using namespace std;
int main()
{
char *p=NULL;
p="hello\n";
printf("---%s---%0x\n", p,&p);
p="world\n";
printf("---%s---%0x\n", p,&p);
p=NULL;
char *q = "nice to see you!";
p = q;
printf("---%s---%0x\n", p,&p);
char *ps[10];
char *ss;
for (int i=0; i<10; i++)
{
ss = (char *)malloc(10*sizeof(char));//此处需要重新分配内存?若没有这行将段错误?
sprintf(ss,"hello%d",i);
printf("%0x\n",&ss);
ps[i] = ss ;
}
for (int j=0; j<10; j++)
{
printf("------%s------\n",ps[j]);
}
return 0;
}
程序如上,为什么指针P可以随便用,不用申请内存也不会发生错误,而ss若不动态申请会发生段错误?
malloc什么时候必须用而什么时候可以不用?