【问题标题】:The pointer is lost when passing to the function传递给函数时指针丢失
【发布时间】:2020-05-19 00:53:25
【问题描述】:

从文件中读取数据是正确的,owner, phone, duty 获取值并输出到控制台,但是当我将它们传递给函数时,owner 指针调用 preOrder 时由于某种原因变为空且不输出,尽管 phone 不会丢失指针并输出到控制台。可能是什么问题?

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

typedef struct node{
    char owner[10];
    char phone[12];
    int tariff; 
    struct node *left, *right;
} NODE, *pNODE;

pNODE addNode(char * owner, char * phone, int tariff, pNODE root);
void preOrder(pNODE root);

int main() {
    srand(time(NULL));

    pNODE root = NULL;

    FILE* fp;

    fp = fopen("./source/data.txt", "r");

    char owner[10];
    char phone[12];
    int tariff; 

    while(!feof(fp)){
        fscanf(fp, "%s", &owner);
        printf("%s ", owner);
        fscanf(fp, "%s", &phone);
        printf("%s ", phone);
        fscanf(fp, "%d", &tariff);
        printf("%d\n", tariff);
        root = addNode(owner, phone, tariff, root);
    }

    fclose(fp);
    printf("%s\n", root->owner);
    preOrder(root);

    return 0;
}

pNODE addNode(char * owner, char * phone, int tariff, pNODE root){
    if(!root){
        root = malloc(sizeof(NODE));
        if(root){
            strcpy(root->owner, owner);
            strcpy(root->phone, phone);
            root->tariff = tariff;
            root->left = NULL;
            root->right = NULL;
        }
    }
    else
        if(tariff < root->tariff)
            root->left = addNode(owner, phone, tariff, root->left);
        else 
            root->right = addNode(owner, phone, tariff, root->right);
    return root;
}

void preOrder(pNODE root){
    if(root){
        printf("%s %s %d", root->owner, root->phone, root->tariff);
        preOrder(root->left);
        preOrder(root->right);
    }
}

文件中的数据:

Ivan +79857465656 1
Mark +78345674534 2
Tom +78937478383 1
Petr +78293338475 3
Anna +79883743737 4

【问题讨论】:

标签: c function pointers


【解决方案1】:

char phone[12] 不够大,无法容纳您的电话号码。电话号码的长度为 12 个字符,因此该数组至少需要 13 个元素才能允许尾随空字节。

因此,您在数组边界之外写入,导致未定义的行为。

你需要增加局部变量和结构成员的大小。

【讨论】:

  • 在大多数理智的编译器中,这会搞砸tariff 而不是所有者。该结构保证按指定的顺序布局。 owner 是在 OP 的情况下搞砸的。
  • 读入本地数组时出现问题,而不是结构体。
  • 是的,可以的。
猜你喜欢
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
相关资源
最近更新 更多