我想在不使用字符串的情况下声明一个指向字符的指针数组
I want to declare a pointer array to character without using string
以下是代码::
#include <iostream>
using namespace std;
const int MAX = 4;
int main ()
{
char key[20];
char *names[MAX];
for (int i=0; i<MAX; i++)
{
cout << " entr keysn";
cin >> key;
names[i]=key;
cout<< names[i];
}
for(int i=0; i<MAX;i++)
{
cout << names[i];
}
return 0;
}
当我输入密钥并在第一个for
循环中打印时,它们会显示正确的值,但当我在第二个for
循环中打印names[i]
时,它会一次又一次地显示最后输入的密钥。
请告诉我:我哪里错了?
运行names[i]=key;
时,并没有真正将key
的字符串值复制到names[i]
它只是使name[i]
指向密钥所在的位置(因为name[i]
和key
都是指针)。
所以总的来说,您要多次重写key
,并使所有names
指针都指向key。
您需要通过使用std::string
而不是char*
或使用strcpy
来复制这些字符串。我建议使用std::string
。
使用std::string
,您的代码应该如下所示:
#include <iostream>
#include <string>
using namespace std;
const int MAX = 4;
int main ()
{
string names[4];
for (int i = 0; i < MAX; i++)
{
cout << "entr keys" << endl;
cin >> names[i];
cout << names[i];
}
for(int i=0; i<4;i++)
{
cout << names[i];
}
return 0;
}
每次执行行时
cout << " entr keysn";
cin >> key;
您正在向key
中插入一个以null结尾的字符串,例如"hello "
。
然后,复制key
的地址,并将其存储到名称指针数组的单元格中:
names[i]=key; // Now I point to 'key'
cout<< names[i];
则循环再次开始。无论如何,从第二次开始,您将在键中插入以null结尾的字符串,从而覆盖以前的内容。第二次输入"hi "
时,key
数组的内容将变为
['h', 'i', ' ', 'l', 'l', 'o', ' ']
无论如何,您将只打印第一个字符串,因为null终止符将阻止显示其他内容。
当程序结束时,你将有四个指向同一个键数组的指针,而该数组将只包含插入的最后一个元素,该元素覆盖了前面的元素。
为了解决这个问题,你可以让你的数组成为二维数组(或者使用字符串数组):
const int MAX = 4;
int main ()
{
char key[4][20]; // <- Now this has two indices
char *names[4];
for (int i = 0; i < MAX; i++)
{
cout << " entr keysn";
cin >> key[i];
names[i]=key[i];
cout<< names[i];
}
for(int i=0; i<4;i++)
{
cout << names[i];
}
return 0;
}
实时示例
已更正程序:
#include <iostream>
using namespace std;
#include <cstring>
const int MAX = 4;
int main ()
{
char key[20];
char *names[MAX];
for (int i = 0; i < MAX; i++)
{
cout << " entr keysn";
cin >> key;
names[i] = new char[strlen(key) + 1];//names[i]=key;
strcpy(names[i], key);
cout<< names[i];
}
for(int i=0; i<MAX;i++)
{
cout << names[i];
}
for(int i=0; i<MAX;i++)
{
delete [] names[i];
}
return 0;
}
您需要为每个名称[i]分配空间,完成后,取消分配此外,将硬编码的4更改为MAX