题: * 已知 int lstat(const char *file, struct stat *buf); 则请判断下面正误 * * A) * struct stat *statbuf; * lstat("a.txt", statbuf); * * B) * struct stat statbuf; * lstat("a.txt", &statbuf); * * 答案请选择空白区域(做为学习用,贻笑大方了) * * 答案: * 1)错误 * 由lstat原型知道第二个参数是要一个 struct stat 结构变量的指针(即变量内存地址) * 上面只是由 struct stat *statbuf; 定义了一个指针,此时指针所指内容未知,所以不能直接 lstat("a.txt", statbuf); 这样等于把lstat函数的结果放入未知内存,所以引起错误, 只有给它一个已经定义好的结构变量才可用 * * 可以如下修正 * struct stat *statbuf; * struct stat buf; * statbuf = &buf; * * lstat("a.txt", statbuf); * * 2)正确 * 因为上面定义了变量,而直接传递结构变量地址 &statbuf, 所以正好正确 */示例:1)#include <sys/stat.h>#include <unistd.h>#include <stdio.h>int main(int argc, char **argv){ struct stat *statbuf; struct stat buf; statbuf = &buf; int i=1; while(lstat(argv[i++], statbuf)==0) { printf("%s: %d\n", argv[i-1], statbuf->st_size); } return 0;}2)#include <sys/stat.h>#include <unistd.h>#include <stdio.h>int main(int argc, char **argv){ struct stat statbuf; int i=1; while(lstat(argv[i++], &statbuf)==0) { printf("%s: %d\n", argv[i-1], statbuf.st_size); } return 0;}.结果[root@localhost file]# ./lstat lstat.c lstatlstat.c: 1236lstat: 4966

评论