使用指针将两个字符数组连接成一个字符数组
concatenate two char arrays into single char array using pointers
我正在尝试使用一个名为(例如:john doe)的文本文件,并查找名字和姓氏。然后,我想取这两个char数组,并使用指针将它们连接在一起。被注释掉的代码是工作代码,它将两个字符数组放在一个字符数组中,即将它们连接在一起这个项目要求我使用指针,并使用字符数组我不是要求你为我做这件事,但请帮助我意识到我做错了什么。感谢
编辑:我得到的错误是seg错误。。所以我在想我的球员Ptr在哪里出界了??
void readPlayer(char *finName2, player *playerPtr)
{
player *playerHome = playerPtr;
ifstream fin;
char *tempfName= new char[20];
char *templName= new char[20];
char *tempName= new char[20];
char *tempNameHome = tempName;
fin.open(finName2);
if(!fin.good())
{
cout << "Error with player file!" << endl;
}
else
{
fin >> tempfName;
fin >> templName; //prime file
cout << tempfName << templName;
while(fin.good())
{
for(int i =0;i<5;i++)
{
//find the length
//int index =0, length=0;
while(*tempfName != ' ')
//while(tempfName[length] != ' ')
{
tempfName++;
}
strcopy(tempName,tempfName);
//now add space after first name
*tempName = ' ';
tempName++;
//tempfName[length] = ' ';
//tempfName++;
//length++;
while(*templName != ' ')
//while(templName[index] != ' ')
{
templName++;
//tempfName[length] = templName[index];
//length++;
//index++;
}
strcopy(tempName,templName);
//tempName++;
//tempfName[length]=' ';
strcopy((*playerPtr).name,tempName);
playerPtr++;
fin >> tempfName;
fin >> templName;
}
}
}
delete[] tempfName;
delete[] templName;
delete[]tempName;
}
您的tempfName&templName会一直递增,并且它们会移动到分配的内存之外。你需要重置他们的位置
另外,我可以看到
fin >> tempfName;
fin >> templName;
在for循环中,意思是鳍。Good每5次只检查一次。
我看到的问题(也在评论中提到):
增加循环中的tempFName
和tempLName
while(*tempfName != ' ')
{
tempfName++;
}
strcopy(tempName,tempfName);
在上面循环的末尾,tempFName
指向字符串的末尾——它指向终止的null字符。strcopy
不应向tempName
复制任何内容。
循环也有同样的问题:
while(*templName != ' ')
{
templName++;
}
strcopy(tempName,templName);
在第一次循环后设置*tempName
的值
//now add space after first name
*tempName = ' ';
tempName++;
只有当tempName
在调用strcopy
之后指向复制字符串的末尾时,这才有效。如果不是,则只是将tempName
中第一个字符的值设置为' '
。递增tempName
只有指向复制字符串末尾的tempName
才有意义。否则,它将指向第二个字符。
由于上述错误,在for
循环的第一次迭代之后,您的代码可能会出现由于内存访问超出限制而导致的错误。在那之后,任何事情都不能指望以合理的方式行事。
我建议进行以下更改以修复上述错误。
根本不增加变量tempFName
和tempLName
你根本不需要。
删除行:
while(*tempfName != ' ')
{
tempfName++;
}
仅使用:
strcopy(tempName,tempfName);
使用临时指针转到tempName
的末尾
第一次调用strcopy
后,使用:
char* temp = tempName;
while ( *temp != ' ' ) ++temp;
*temp = ' ';
++temp;
*temp = ' ';
将临时指针用于第二个strcopy
删除行:
while(*templName != ' ')
{
templName++;
}
更换线路:
strcopy(tempName,templName);
带有
strcopy(temp,tempfName);
备用策略
如果您实现strcat
版本,您可以简单地使用:
tempName[0] = ' ';
strcat(tempName, tempFName);
strcat(tempName, " ");
strcat(tempName, tempLName);
这将去除for
循环中的大部分杂波。
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?