C++通过指针填充数组
C++ filling arrays by pointers
在创建用户输入大小的字符串数组时遇到问题。我得到了数组大小的用户输入,但我不能将这个值传递给另一个函数来创建字符串数组。关于我在这里做错了什么,有什么解释吗?我通过引用将用户输入的值传递给我的新函数,但我收到错误,无法将string
转换为string*
using namespace std;
#include <iostream>
#include <fstream>
#include <string>
//function prototypes
void getSize(int &arraySize);
void getSpace(int arraySize, string *word);
//Calls other functions otherwise does nothing
int main()
{
int numStrings;
string *words;
getSize(numStrings);
getSpace (numStrings, *words);
}//end main
// asks the user how many strings they want
void getSize(int &arraySize){
cout << "How many strings do you want? ";
cin >> arraySize;
}
// gets an array in the heap of the size requested by the user
void getSpace(int arraySize, string *word){
word = new string [arraySize];
}
忽略房间里的大象,std::vector
,
void getSpace(int arraySize, string *word);
指定采用CCD_ 4和指向CCD_ 5的指针的函数。在函数中,您将一个数组分配给string
s的指针。
但是
指针是一个包含地址的变量,该地址通过值传递到函数中。在getSpace
内部word
是由呼叫者提供的地址的副本。两者都具有相同的值,指向相同的位置,但如果更改其中一个指向的位置,则该更改不会反映在另一个中。更改word
的值不会改变调用函数中的原始值。您需要通过引用传递指针,以便能够在调用方中更新回指针。
您可以将getSpace
定义为
void getSpace(int arraySize, string * & word);
并称之为
getSpace (numStrings, words);
但定义会更容易
string * getSpace(int arraySize);
并称之为
words = getSpace (numStrings);
省去麻烦。阅读起来也更容易。通过返回指针,该函数清楚地为调用者提供了一个指向字符串的指针。以前的版本可能使用了一个字符串,导致Mikhail Genkin在对另一个答案的评论中提到了未初始化的变量警告。
完成后请记住delete[] words;
。
您只需要在getSpace
函数中通过引用而不是通过值传递word
。即将CCD_ 14改变为CCD_。
请记住,如果您计划更改指针指向的位置,则需要通过引用传递它。
当您在getSpace
中说word = new string[arraySize]
时,您要做的是将单词设置为指向包含新字符串数组中第一个元素的内存位置。
相关文章:
- C++ 填充数组时遇到问题
- 如何使用同时设置计数和填充数组的函数
- 如何使填充数组的函数发送到函数?而不是其参数中的数组
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 使用 memset 填充数组会显示垃圾
- Visual Studio从文件中填充数组时中断
- 分段 填充数组时出错
- 用不同的值填充数组/矢量的边缘和中心
- 使用相同的数据填充数组对象或使用指针
- 是否可以使用三元运算符"?"在 C/C++ 中填充数组列表?
- 填充数组(写入位置0x00000000的访问冲突)
- 从文件中读取输入并填充数组以存储数据供以后使用
- c++当循环在填充数组时没有正确终止时,希望能帮助退出此循环
- 填充数组会导致数组周围的堆栈损坏
- Cuda有效地将数据插入到未排序的填充数组中
- 填充数组的 C++ 函数
- 访问部分填充数组上的第一个打开元素
- 将一个字节数组从C#传递到C++填充数组的C++com对象中
- 如何使用向量中的信息填充数组并从数组中选择随机项
- C,填充数组使用dec2bin转换器