c - 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.
解决方案
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
推荐阅读
- ionic-framework - Ionic3 Fileopener 插件对象(…)不是函数错误
- image-processing - 将 Cifar10 数据集转换为 Amazon SageMaker 的 RecordIO 格式
- game-maker - GML 向点移动使对象向右移动
- deep-learning - CNN 的预处理图像?
- android - 从应用的插件访问文件
- html - 如何在每个部分制作此边框底部曲线?
- php - PHP重命名具有无法识别字符的文件
- firebird - 从 FB3.0 连接到 FB2.5
- ios - 在iOS中语言切换后未调用Tableview cellForRowAt indexPath
- batch-file - 如何将用户输入传递给批处理脚本中的参数?