为什么我的C编程代码中存在分段错误? [英] Why do I have a segmentation fault in this C programing code?

查看:70
本文介绍了为什么我的C编程代码中存在分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C语言编写简单的mergesort问题。

但我仍然存在分段错误而且我陷入其中。请帮助...!



我尝试过:



I'm trying to program simple mergesort problem with C language.
but I still have segmentation fault and I'm stuck in it. PLEASE HELP...!

What I have tried:

#include <stdio.h>
#include <stdlib.h>

void merge(int *arr, int start, int mid, int end)
{
	int i, j, k;
	int arrsize=end-start+1;
	int sm_size=mid-start+1;
	int me_size=end-mid+1;
	
	for(i=0; i < arrsize; i++)
        {
            if(j < sm_size && k < me_size)
                if(*(arr+start+j) > *(arr+mid+k))
			{
				*(arr+i) = *(arr+start+j);
				j++;
			}
			
			else
			{
				*(arr+i) = *(arr+mid+k);
				k++;
			}
		}
		
		else if(j

推荐答案

您应该考虑初始化 j k 使用它们之前。

我担心你需要快速学习调试器,因为首先看你的程序会杀死一部分值进行排序。如果我记得很清楚,合并不是在同一个数组中完成的。



你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候了看到你的代码正在执行并确保它能达到预期的效果。



调试器允许你逐行执行,检查变量,你会看到有它停止做你期望的一点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]



调试器在这里显示你的代码是什么做和你的任务是与它应该做的事情进行比较。

当代码没有达到预期的效果时,你就接近了一个错误。



建议:拿一张纸并尝试手工完成,你的程序应该使用相同的程序。
You should think about initializing j and k before using them.
I fear you need to learn the debugger quickly because on first look your program will kill a part of the values to sort. If I remember well, the merge is not done in same array.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

Advice: take a sheet of paper and try to do it by hand, your program should use the same procedure.


这篇关于为什么我的C编程代码中存在分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆