结构体中的指针
Pointers in structures
首先告诉你我的问题:
我写了一个基于这个结构体的程序…
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;
相关文章:
- C++ 使用成员函数返回结构体指针属性的值
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 如何使用结构体作为接口从函数返回指向数组的指针
- 如何在结构体中传递指向CURL的指针到向量
- 使用c++中从IDA导出的带有指针的结构体
- 设置两个结构体相等后,指针为NULL
- 结构体中的指针
- 指向结构体的向量指针错误
- 指向结构体的Void *指针
- 返回指向类定义的结构体的指针,多个作用域操作符
- 带有指针的结构体向量
- 你能解释一下指针和递归结构体吗?
- c语言中具有指针数组的结构体
- c++用数组、结构体和指针排序
- 初始化没有指针的结构体
- 如何在不激怒编译器的情况下传递指向结构体的指针?
- 如何释放一个结构体的内存,每次循环迭代的指针
- 如何根据结构体的字段之一对结构指针列表进行排序?
- 从c#调用c++函数-结构体,指针,函数指针
- /a.检测到Glibc.out: munmap_chunk():无效指针- c++结构体的动态数组