C++通过指针填充数组

C++ filling arrays by pointers

本文关键字:填充 数组 指针 C++      更新时间:2023-10-16

在创建用户输入大小的字符串数组时遇到问题。我得到了数组大小的用户输入,但我不能将这个值传递给另一个函数来创建字符串数组。关于我在这里做错了什么,有什么解释吗?我通过引用将用户输入的值传递给我的新函数,但我收到错误,无法将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]时,您要做的是将单词设置为指向包含新字符串数组中第一个元素的内存位置。