传递带参数的函数也是函数

时间:2018-01-27 15:29:46

标签: c

我在完成作业时遇到了一些问题。此任务的一部分涉及创建包含给定数据的链接列表并将其打印出来。存储在列表中的数据是数据类型' Atom',可以是整数,字符串,"对"(自定义数据类型),或由节点组成的列表。

如果输入是(第一个整数表示数据的数量)

4
1 2 3 4

打印

1 2 3 4

让我感到奇怪的是,如果我像这样更改函数read_list_helper(int n)

    Node* read_list_helper(int n)
{
    Atom *atom;

    if (n == 0) return NULL;

    return combine_atom_and_list(get_atom(), read_list_helper(n - 1));
}

输出变为

4 3 2 1

为什么会这样?我尝试了几个关键字来搜索答案,但没有一个能够解决问题。

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define STRING 0
#define NUM 1
#define PAIR 2
#define LIST 3

struct Atom;

typedef struct Pair
{
    struct Atom *left;
    struct Atom *right;
} Pair;

typedef struct Node
{
    struct Atom *data;
    struct Node *next;
} Node;

typedef struct Atom
{
    int dtype;
    int val = 0;
    char str[21] = {'\0'};
    Pair *pair = NULL;
    Node *Node = NULL;
} Atom;

Node* read_list();
Node* read_list_helper(int);
Atom* get_atom();
Node* combine_atom_and_list(Atom*, Node*);

void print_atom(Atom*);
void print_pair(Pair*);
void print_list(Node*);

int main()
{
    Node *head1;

    head1 = read_list();
    print_list(head1);


    system("pause");
    return 0;
}

Node* read_list()
{
    int n;

    scanf("%d", &n);

    return read_list_helper(n);
}

Node* read_list_helper(int n)
{
    Atom *atom;

    if (n == 0) return NULL;

    atom = get_atom();

    return combine_atom_and_list(atom, read_list_helper(n - 1));
}

Atom* get_atom()
{
    int num;
    char str[21];
    int i;

    Atom* res = (Atom*)malloc(sizeof(Atom));

    if (scanf("%d", &num) == 1)
    {
        res->dtype = NUM;
        res->val = num;
    }
    else
    {
        scanf(" %20s", str);
        res->dtype = STRING;
        strncpy(res->str, str, 20);
    }
    return res;
}

Node* combine_atom_and_list(Atom* atom, Node* node)
{
    Node *res = (Node*)malloc(sizeof(Node));
    res->data = atom;
    res->next = node;
    return res;
}



void print_atom(Atom* atom)
{
    if (atom == NULL) return;

    switch (atom->dtype)
    {
    case NUM:
        printf("%d", atom->val);
        break;
    case STRING:
        printf("%s", atom->str);
        break;
    case PAIR:
        print_pair(atom->pair);
        break;
    case LIST:
        print_list(atom->Node);
        break;
    default:
        break;
    }
}

void print_pair(Pair* pair)
{
    print_atom(pair->left);
    print_atom(pair->right);
}

void print_list(Node* node)
{
    print_atom(node->data);
    if (node->next != NULL)
    {
        printf(" ");
        print_list(node->next);
    }
}

1 个答案:

答案 0 :(得分:0)

不评估函数参数in any particular order。由于您的一个参数执行I / O,因此评估顺序会影响输入的顺序。