简体   繁体   English

为什么我会遇到细分错误:11?

[英]Why am I getting Segmentation fault: 11?

I'm trying to learn c, so I have been trying to figure out why I have segmentation fault for the last 2 hours; 我正在尝试学习c,所以我一直在试图弄清楚为什么最近2个小时出现细分错误; On paper it looks like the code should work.. 在纸上看起来代码应该可以工作。

So the purpose of the procedure is to ask the user to enter the size they need in heap, then ask them to enter the numbers, but the numbers must be unique. 因此,该过程的目的是要求用户输入堆中所需的大小,然后要求他们输入数字,但是数字必须唯一。

Please excuse me if this is badly indented code, I'm still a beginner 如果这是缩进代码,请原谅,我仍然是初学者

int size ; // The size to allocate
int input ; // the number the user will enter from keyboard
int count  = 0 ; // how many numbers have been added


printf ("Enter the number of integers to process: \n");
scanf ("%d" , &size) ;
int* t;
int* c= (int*)malloc (size* sizeof (int));

if ((t = c))
while (count<size)
{
  printf("Enter value #%d\n" , count+1) ;
  scanf ("%d" , &input) ;

  if (count != 0)
  while (t<= t+count-1)
  {

      if (*t == input)
      {
         printf ("You have entered %d already\n", input);
         printf("Enter value #%d\n" , count+1) ;
         scanf ("%d" , &input) ;
         t = c ;
      }
    else
     t++;
  }

  t = c ;
  c[count] = input ;
  sum += c[count] ;
  count ++ ;
}

应该是while (t<= c+count-1)而不是while (t<= t+count-1)后一种情况始终为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM