考虑这段代码(为简洁起见删除了错误检查):
int main()
{
int fd, nread;
struct stat st_buff;
/* Get information about the file */
stat("data",&st_buff);
/* Open file data for reading */
char strbuff[st_buff.st_blksize];
fd = open("data",O_RDONLY);
/* read and write data */
do {
nread = read(fd,strbuff,st_buff.st_blksize);
if (!nread)
break;
write(STDOUT_FILENO, strbuff, nread);
} while (nread == st_buff.st_blksize);
/* close the file */
close(fd);
return 0;
}
此代码在堆栈上为缓冲区分配内存(如果我没有误解的话。)还有 alloca()
函数,我可以将其用于相同的目的(我猜)。我想知道我是否有任何理由想要选择一个而不是另一个?
最佳答案
您通常希望使用上面的 VLA,因为它干净且标准,而 alloca
丑陋且不符合标准(好吧,无论如何不符合 C 标准 - - 它可能在 POSIX 中)。
关于c - 为字符缓冲区分配可变长度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10284841/