为什么我不断收到分段转储?

时间:2019-04-10 13:52:50

标签: c

我必须创建一个程序,该程序按字母顺序对一个单词进行排序,并且必须使用数组和指针来做到这一点。

我尝试删除数组的大小并分配内存,但这给了我同样的分段错误。我不知道问题出在将数组传递给函数还是冒泡排序。我在函数中添加了一条print语句,因此我假设我正确传递了数组。输入薄煎饼时,它会在函数中打印。我更倾向于引起问题的气泡排序,因为我可以删除它,从而摆脱了分段错误。

void main(void)
{
  int num;
  double swap1 = 18.4 , swap2 = 95.73;
  char theString[50];
  char beginning, ending;
  printf("Enter a number:\n");
  scanf("%d", &num);
  doubleme(&num);
  printf("%d is the value you entered doubled.\n", num);
  printf("Before swapping value a is %lf and value b is %lf\n", swap1, swap2);
  swap(&swap1, &swap2);
  printf("After swapping value a is %lf and value b is %lf\n", swap1, swap2);
  printf("Enter a word and I will tell you the first and last character of the alphabet within it.\n");
  scanf("%s", theString);
  firstLast(theString, &beginning, &ending);
  printf("%s is the first character and %s is the last.\n", beginning, ending);
}

void doubleme(int *x)
{
  *x = 2 * *x;
}

void swap(double *a, double *b)
{
  double temp;
  temp = *a;
  *a = *b;
  *b = temp;
}

void firstLast(char theString[], char *first, char *last)
{
  int i, j, n;
  n = strlen(theString);
  char temp;
  printf("%c\n", theString[4]);
  for(i = 0; i < (n - 1); i++)
  {
    for(j = 0; j < (n - 1); j++)
    {
      if(theString[j] > theString[(j+1)])
      {
        temp = theString[j];
        theString[j] = theString[(j+1)];
        theString[(j+1)] = temp;
      }
    }
  }
  *first = theString[0];
  *last = theString[(n-1)];
}

我需要函数对输入的所有字符串进行排序,然后使用数组和指针将值返回给主函数。

1 个答案:

答案 0 :(得分:4)

您正在欺骗您的编译器。 您声称提供了字符串的地址,但是您为%s格式说明符传递了一个字符。

  char beginning, ending;

  printf("%s is the first character and %s is the last.\n", beginning, ending);

这会将那个字符的值当作一个地址,并尝试从那里读取。 这是不确定的行为

相关问题