【发布时间】:2015-10-15 19:02:48
【问题描述】:
我必须初始化一个字符串指针数组以指向 4 个工作人员名称。然后我想调用一个函数 func1() 打印出所有的名字。 我必须使用通过referebce 或值传递或者可能是这些的混合来做到这一点,任何事情都可以。
我已经通过以下类似类型的查询
how to initialize string pointer?
c++ initialization of an array of string pointers
returning array of string from function not working as expected
还尝试使用 Books Deitel 和 deitel 和 C++ 入门 然而,无法理解或澄清我对字符串指针数组的理解,以至于现在我什至对它的基本原理感到困惑。
虽然根据我在下面编写的代码,我在网上经历了许多类似的问题,但我只能做到这一点。
我的代码:-
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void func1(string *str, int *num)
{
for (int i = 0; i <= (*num); i++)
{
cout<<"\n"<<str[i]<<"\n";
}
cout<<"reached to the end of calling function\n\n";
}
int main()
{
int num;
cout<<"\nplease input your prefered size of array\n";
cin >> num; // Number of names elements
cout<<"\nplz enter the desired names\n";
string *str = new string[num];
for (int i=0;i<num;i++)
{
getline(cin, str[i]);
}
cout<<"now printing all the names through a calling function\nusing appropriate parameters\n";
func1(str, &num);
return 0;
}
当前行为:-
代码执行并接受我的输入,但只要我给出倒数第二个值,它就会提示错误提示“file1.exe 已停止工作”。但是,它会继续执行剩余的任务并调用 func1() 并打印被调用函数的结束行。
输出:
请输入您喜欢的数组大小
4
请输入所需的名称
普拉提克
普拉提克维亚斯
Pratik Vyas A
现在通过调用函数打印所有名称 使用适当的参数
普拉提克
普拉提克维亚斯
Pratik Vyas A
进程在 14.24 秒后退出,返回值 255 按任意键继续 。 . .
而且我必须关闭终端,因为我一输入第三个名称 Pratik Vyas A 就会收到提示错误,如上所述。
我知道这可能是一些非常基本的问题,但只有当我的大脑可以处理在线给出的其他多种方式时,我才会将这个问题空间留给其他一些有价值的重要问题。 任何高度赞赏的帮助。
【问题讨论】:
-
你为什么要通过指针传递
num? -
如果您没有遇到
std::string和std::vector,您就读错书了;) -
@CodeMan 但为什么呢?为什么不按值传递
int? -
你有读取数字的代码,但你想要的是读取一行。
-
func1的for循环转到<= num,它位于数组末尾之后。
标签: c++ arrays string function pointers