程序流程停留在功能中

时间:2015-08-05 23:53:17

标签: c

我似乎创建了一个自私的函数,它拒绝将控制权传递给我的main函数。我已经在我的代码中插入了几个输出语句来简化调试,并证明程序在我的add_node()'功能。我已将整个计划纳入其中,因为我对问题所处的位置感到非常困惑。

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

/* All-purpose error function */
void kill(char *error)
{
  if(errno != 0) {
    perror("Error: ");
  } else {
    printf("%s", error);
  }
  exit(1);
}

// A link with string data type
typedef struct slink
{
    char value[20];
    struct node* prev;
    struct node* next;
}slink;

// A link with double data type
typedef struct dlink
{
    double value;
    struct node* prev;
    struct node* next;
}dlink;

// Node structure, contains several links
typedef struct node
{
    slink name;
    dlink weight;
    dlink height;
    dlink spins;  //Place forhead on bat, count spins until fall.
    dlink chug;   //Open beer, chug. Record time.
}node;

// Creates a new node and populates it with given data arguments
void add_node(char* n, double w, double h, double s, double c)
{
    node* this = malloc(sizeof(node));
    bzero(this, sizeof(node));
    if(!this) kill("Failed to create node.\n");

    strncpy(this->name.value, n, 20);
    this->weight.value = w;
    this->height.value = h;
    this->spins.value = s;
    this->chug.value = c;

    sort_node(this);
    printf("returned flow to add_node\n");
}

/*Compares values of this node to the values of all other nodes
and assigns appropriate ptr values to the links*/
int sort_node(node* this)
{
    static bool first_sort = true;
    static node* head;

    if(first_sort){
        this->name.prev = NULL;
        this->name.next = NULL;
        this->weight.prev = NULL;
        this->weight.next = NULL;
        this->spins.prev = NULL;
        this->spins.next = NULL;
        this->chug.prev = NULL;
        this->chug.prev = NULL;
        first_sort = false;
        head = this;
        printf("first node sorted successfully\n");
    } else {
        node* current = head;

        //Traverse list searching for logical alphabetical neighbors
        while(current->name.value < this->name.value) {
            if(current->name.next) {
                current = current->name.next;
            }
        }
        this->name.next = current;
        this->name.prev = current->name.prev;
        current->name.prev = this;
    }

    return 0;
}

int main(void)
{
    add_node("Chiis Manly", 195, 66.5, 39, 23);
    printf("chiis added");

    add_node("Harrie Malaria", 253, 48, 210, 4);

    return 0;
}

该程序的输出如下:

first node sorted successfully
returned flow to add_node

请注意&#39; printf(&#34; chiis添加&#34;);&#39;在我的主要&#39;功能永远不会运行。非常感谢大家的帮助!

2 个答案:

答案 0 :(得分:1)

如果以下if语句条件为false:

if(current->name.next) {

那么你的while循环将如何终止?那是你的问题。

debugging small programs上查看。

答案 1 :(得分:1)

如果您在fflush(stdout);之后添加printf("chiis added");,您会发现printf确实已执行,并且您的程序卡在其他地方(请参阅@ i_am_jorf&#39; s)。

传递给printf()的任何内容都由标准库缓冲,以提高写入终端的性能。您可以使用fflush()手动刷新缓冲区。