首页 > 解决方案 > Why do I keep getting a segmentation dump?

问题描述

I have to create a program that sorts one word alphabetically and must be done so using arrays and pointers.

I tried removing the size of the array and allocating memory, but that gave me the same segmentation fault. I don't know if the issue is with passing the array to the function or the bubble sort. I added a print statement in the function so I assume I'm passing the array correctly. When pancake is entered it does print a within the function. I'm leaning more towards the bubble sort causing the issue because I can remove that and it gets rid of the segmentation fault.

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)];
}

I need the function to sort any string entered and return the values to the main using arrays and pointers.

标签: c

解决方案


You are cheating your compiler. You claim to provide the address of a string but instead you pass a single character for %s format specifier.

  char beginning, ending;

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

This will treat the value of that character as an address and try to read from there. This is undefined behaviour


推荐阅读