Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
scanf ("%d", &i);
这些代码是否相同//动态分配缓冲区(字符字符串)大小=i;
char *buffer = malloc (sizeof((*buffer)*(i+1))); free(buffer); char * buffer; buffer = (char*) malloc (i+1); free(buffer);
如果是,哪个更安全(更好)?
最佳做法是:
char *buffer = malloc(i + 1);
无需转换返回值,malloc并且sizeof(char)C 标准将其定义为 1。
malloc
sizeof(char)
sizeof(char)总是 1 这是标准的。所以而不是使用
char *buffer = malloc (sizeof((*buffer)*(i+1)));
sizeof(*buffer)你可以不用as来写这个:
sizeof(*buffer)