【发布时间】:2013-10-09 04:49:18
【问题描述】:
我发现这段代码运行良好。
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
char* s; /* input string */
s=malloc(sizeof(s));
int c;
if(argc==1){ // if file name not given
while (gets(s)){
puts(s);
}
}
}
我不明白的是,字符串s是如何存储在内存中的。我只为指针s分配内存,它有4个字节。现在用户给出的输入字符串存储在哪里?
【问题讨论】:
-
澄清一点:如果您在 main 中声明
s像char* s;一样,您不会使用malloc分配内存来存储该变量。该变量的内存将在堆栈上并且已经为您“分配”。对malloc的调用决定了您在该变量中存储的什么,而不是您存储该变量的何处。 -
是的。现在我明白你的意思了。谢谢