-3

我正在做这个任务,虽然我还是 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 %s\n", 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() 放在 root = balance() 函数调用上方的几行内,它们不会在段错误之前也不打印。也许这是我不理解的编译器中的一些动态?

4

1 回答 1

3

我看不到ptr变量是如何在函数中分配的balanceptr->value除非您将指针指向某处(为它分配一些内存,或将其指向一些现有内存),否则将始终导致取消引用 null。

LEAF* ptr = NULL;
printf( "in Balance" );
if ( first > last ) return NULL;

mid = first + (last - first)/2;
ptr->value = n[mid]; 
于 2012-04-23T09:26:49.193 回答