我正在做这个任务,虽然我还是不熟悉 C 语言编程的新手,但我认为我已经更好地掌握了内存参考和指针的使用......
我正在尝试做的是从排序数组创建一个平衡的二叉树。当我尝试调用我的树构建函数时,我抛出分段错误。如果我不去掉该函数调用并只打印我的数组,那么一切都可以编译并以预期的输出运行良好。
我已经像这样构建了树的节点:
typedef struct leaf{
int value;
struct leaf* left;
struct leaf* right;
} LEAF;
我的排序/建树函数库:
LEAF* balance( int n[], int first, int last ){
int mid;
LEAF* ptr = NULL;
printf( "in Balance" );
if ( first > last ) return NULL;
mid = first + (last - first)/2;
ptr->value = n[mid];
ptr->left = ( balance( n, first, mid-1 ) );
ptr->right = ( balance( n, mid+1, last ) );
return ptr;
}
void ins ( int* n, int length ){ //Don't THINK the problem lies here,
I've used the algorithm before and can
print out the sorted array
int i, j, key;
for( i = 0; i < length; i++ ){/*all indexes*/
key = n[i]; /*pick out index and store in variable*/
for( j = i-1; j >= 0; j = j-1 ){/*all objects left of i*/
if ( n[j] < key) break;/*stop and insert*/
n[j + 1] = n[j];/*shifting all objects left*/
}
n[j + 1] = key;/*insertion expression*/
}
}
回到main(),我构建我的数组n[]并像这样调用balance():
int main (void){
/****** initializations */
int* n;
char buffer[20];
FILE* fp;
int numMax = 5;
int lastIndex = 0;
int j;
char* filename = "numbers.txt";
LEAF* root = NULL;
n = malloc ( numMax * sizeof(int*) );
if ( ( fp = fopen(filename, "r")) == NULL ){
printf( "cannot open %sn", filename );
exit( 1 );
}
/****** allocating storage array and inputting */
printf( "initial array size: %d", numMax );
while( fgets( buffer, sizeof(buffer), fp ) != NULL){
n[lastIndex] = atoi( buffer );
lastIndex++;
if ( lastIndex == numMax ){ /*When max num reached, double allocation*/
numMax = numMax * 2;
if ( ( n = realloc( n, numMax * sizeof(int) ) ) == NULL ){
printf( "Cannot allocate more mem." );
exit( 1 );
}
printf( "nReached limit... increasing array to %d possible indexes.", numMax );
}
}
lastIndex--;
/****** sort*/
ins( n, lastIndex+1 );
/****** build tree*/
root = balance( n, 0, lastIndex );
我知道这里有很多代码可能不需要解决我的问题。我把几乎所有的代码都放在这篇文章中,只是因为我在意想不到的地方搞砸了。我希望这可能是一个非常简单的解决方案,会让我感到愚蠢。 我想我感觉越笨,我犯两次错误的可能性就越小!
奇怪的是:我什至看不到 printf( "in Balance" ) 语句,如果我把其他 printf() 放在我的根 = balance() 函数调用上方的几行内,它们也不会在段错误之前打印。也许这是编译器中的一些我不明白的动态?
我看不出ptr
变量是如何在balance
函数中分配的。 ptr->value
将始终导致取消引用 null,除非您将指针指向某个位置(为其分配一些内存,或将其指向某个现有内存)。
LEAF* ptr = NULL;
printf( "in Balance" );
if ( first > last ) return NULL;
mid = first + (last - first)/2;
ptr->value = n[mid];