[char []到char *在结构中

问题描述 投票:0回答:2

我试图在结构体中将char []转换为char *,当我将其分配给p->name2=name时,它会向我显示正确的单词,但是当我尝试使用for循环遍历链接列表时,它仅显示了我的最后一个单词,因此很多时候文件中有多少字。为什么会发生?而且我不能使用字符串或库。我真的需要将每个单词都用作char符号(getchar())吗?

#include<iostream>
#include<fstream>
using namespace std;
struct elem{
    char* name2;
    elem* next;
};
int main(){
    elem *first = NULL, *last = NULL,*q=NULL, *p;
    fstream fin,fout;
    char name[255];
    fin.open("pasts.txt",ios::in);
    fin>>name;
    while (fin){
        p = new elem;
        p->next=NULL;
        p->name2=name;
        if(first==NULL){
            first=last=p;
        }
        else{
            p->next=last;
            last=p;
        }
        fin>>name;
    }
    fin.close();
    for(p=last;p!=NULL;p=p->next){
        cout<<p->name2<<" ";
    }
c++ struct char
2个回答
0
投票

您已声明局部变量name数组数组类型>>

char name[255];

在此声明中

p->name2=name;

所有已分配节点的数据成员name2指向字符数组name的相同第一个字符。

因此,此数组中存储的是所有节点的数据成员name2指向的内容。

您必须通过为其动态分配内存和分配给数据成员name2的地址来复制数组名称中存储的字符串。


0
投票

而且我不能使用字符串或库。

© www.soinside.com 2019 - 2024. All rights reserved.