数组和指针:分段错误

Sel*_*all 0 c memory arrays pointers segmentation-fault

我正在玩数组和指针,并得到这个分段错误.当我在代码中将"p"指针移动到"ptr"指针下方时,任何人都可以解释为什么我在这段代码中出现了这个分段错误,当我注释掉printf语句之一时,它会消失:

 typedef struct str{
   char* ptr;
  }str_t;

copy(str_t t){
   char a[12];
   char *p;   //  <------ no error when move below ptr pointer 
   char *ptr;

   printf("t= %s p = %d ptr = %d\n", t, p, ptr);

   strcpy(a, t.ptr);
   printf("a = %s %u\n", a, &a);

   strcpy(ptr, t.ptr);
   printf("ptr = %s %u\n", ptr, &ptr); //<--- comment it error disappears

   p= t.ptr;
   printf("p = %s %u",p, &p);  //<--- comment it error disappears
 }

int main ()
{
  str_t t;
  char app[] = "hello";
  char ap[] ="world";

  t.ptr = ap;
  copy(t);

  printf("%s\n", app);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里编译代码以查看结果:http: //codepad.org/Q7zS8NaC

谢谢你访问这个问题.

tay*_*10r 5

strcpy不在指针处分配空间p,以存储字符串.您需要将其声明为一个数组或分配空间malloccalloc.

试试这个:

 int len = strlen (t.ptr);         // find length of string

 char * ptr = calloc (len + 1, 1); // allocate space for ptr
 if (!ptr) return;                 // error check calloc
 strcpy (ptr, t.ptr);              // copy the string

 char * p = calloc (len + 1, 1);   // do the same thing for p
 if (!p) return;
 strcpy (p, t.ptr);
Run Code Online (Sandbox Code Playgroud)

这将解决您的分段错误.

但是你还有一些错误,主要是格式问题.

  1. %u打印无符号整数.看起来你正在尝试打印指针,所以请%p改用它.
  2. printf("t= %s p = %d ptr = %d\n", t, p, ptr); 是完全错的.
    1. 你需要引用的成员t,即t.ptr
    2. p是一个指针,而不是一个整数.用%p而不是%d
    3. ptr也是一个指针.使用%p%s

阅读文件printf,如果你拿不准格式.事实上,阅读任何功能的文档,如果你不确定如何使用它 - 你会省去很多麻烦.