结构体中的指针

Pointers in structures

本文关键字:指针 结构体      更新时间:2023-10-16

首先告诉你我的问题:

我写了一个基于这个结构体的程序…

typedef struct{ 
    char firstname [40];    
    char lastname [40]; 
    char address [100]; 
    char phone[11];
}contact;

将要求用户输入,然后将其写入文件。除了当我写入文件时,它写的是名字,剩下的40个字符所以所有的东西都是间隔的。

我的一个同事建议创建一个指针结构,但我对这个概念完全不熟悉。到目前为止,我用这个来代替上面的结构:

typedef struct{ 
    char* firstname;    
    char lastname [40]; 
    char address [100]; 
    char phone[11];
}contact;

在这种情况下,我现在只处理名字。我见过创建单独数组

的例子
char comm[100];
fgets(entry.firstname, 40, stdin);
entry.firstname = new char[strlen(comm)];

之类的,但这让我很难受。我想要的是让人输入一个条目和字段的大小增长和缩小到什么是由用户输入。任何修复将是感激!

抱歉没写了:/:

pFile = fopen("C:\contacts.txt", "r+");
if(!pFile){
    puts("File could not be open.");
    return 1;
    }
fwrite(&entry,1,sizeof(entry),pFile); 

问题是您只是将整个contact结构转储到一个文件中。相反,您要做的是只写出用户输入的字符。幸运的是,这很简单。首先,让我们打印出第一个名字:

fprintf(pFile, "%sn", entry.firstname);

如果你正在使用c++,你应该使用std::string而不是字符数组。你的结构现在看起来像

typedef struct{ 
    std::string firstname;    
    std::string lastname; 
    std::string address; 
    std::string phone;
}contact;

你可以用fstream

写文件
std::ofstream outfile("C:\contacts.txt");
outfile << contact.firstname << std::endl
        << contact.lastname << std::endl
        << contact.address << std::endl
        << contact.phone << std::endl;
outfile.close();

如果您有new,那么您正在使用c++,而不是C。如果是这样,您应该使用std::string来存储字符串。

首先,我不认为在c中有new。其次,如果entry是一个指针,你必须得到firstname这样:

entry->firstname;

如果你想把指针指向一个新的字符数组,你可以:

char comm[100];
entry->firstname = &comm;