LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 731|回复: 2

关于char*的一点求教

[复制链接]
发表于 2006-9-9 15:11:26 | 显示全部楼层 |阅读模式
问题是这样的,我在自己写一个类似于ls的命令。编译之后一切正常,但在我打开目前所在目录是出现了Segmentation fault。反复试验之后发现问题出现在这一段里:

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <dirent.h>

  7. void do_show(DIR *);

  8. int main(int argv,char *argc[])
  9. {
  10.         char sg;
  11.         int i = 1;
  12.         DIR *dp;
  13.         if(argv == 1)
  14.                 {
  15. [color=Red]                        sg = '.';
  16.                         if((dp = opendir(&sg)) == NULL){
  17.                                 perror("opendir1!\n");
  18.                                 exit(1);
  19.                         }
  20. [/color]                        do_show(dp);
  21.                 }
  22.         else{
  23.                 while(argv != 1){
  24.                         if((dp = opendir(argc[i])) == NULL){
  25.                                 perror("opendir2!\n");
  26.                                 exit(1);
  27.                         }
  28.                         do_show(dp);
  29.                         i++;
  30.                         argv--;
  31.                 }
  32.         }
  33.         closedir(dp);
  34. }

  35. void do_show(DIR *temp_dir)
  36. {
  37.         struct dirent *dir_rec;
  38.         while((dir_rec = readdir(temp_dir)) !=NULL)
  39.                 {       
  40.                         printf("%s\n",dir_rec->d_name);
  41.                 }
  42. }
复制代码

之后把红色一段改为:

  1. {
  2.         //sg = '.';
  3.         if((dp = opendir(".")) == NULL){
  4.                 perror("opendir1!\n");
  5.                 exit(1);
  6.         }
  7.         do_show(dp);
  8. }
复制代码


问题于是就出来了,opendir的格式是这样的:

  1. DIR *opendir(const char *name);
复制代码

&sg和char *是同样的类型为何会出现这样的问题,难道说就是因为缺一个'/0'导致的?
菜鸟虚心请教,希望大家别笑话
发表于 2006-9-9 15:19:24 | 显示全部楼层
你的&sg和"."不是同类型的,&sg虽然是char *但只是一个字符的引用,并不是一个字符串──没有NULL结尾,而"."是一个字符串。
ps:char *并不表示一定是字符串。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-9-10 00:00:45 | 显示全部楼层
受教 在此多谢了
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表