我是一个C++新手,我试图把实践中的指针与字符串。我所做的程序只是将用户类型的字符串存储在命令行中。但我得到段错误,不知道为什么。使用字符串指针的分段错误
这是代码:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
//This code is meant to learn how to use pointers and strings
//Ask the user for who are they in the family and save it in string array!
void print_string (string* Value, int const nSize);
int get_names(string* Family_input);
int main (int nNumberofArgs, char* pszArgs[])
{
cout << "Tis program stores your family members\n";
cout<< "Type the names and write 0 to exit\n";
string familia_string;
string* familia = &familia_string;
int family_number;
family_number=get_names(familia);
cout << "The family members are: ";
print_string(familia, family_number);
cout << endl;
return 0;
}
int get_names(string* Family_input)
{
int i=0;
string input="";
string old_input="";
while (input!="0")
{
cout << "type " << i <<" member\n";
//cin >> *(Family_input+i);
//input=*(Family_input+i);
cin >> input;
*(Family_input + old_input.length()) = input;
old_input=input;
i++;
}
return i;
}
void print_string (string* Value, int const nSize)
{// I don't want to &psValue to be changed!
for (int i=0; i<nSize; i++)
{
cout << *(Value+i) << " ";
//&psValue++;
}
}
我不知道这是否是因为我不接受字符串的正确尺寸,或者我没有使用正确的指针或者是我有在使用偏移量之前分配内存。
显示代码在这里(最小但完整的例子),而不是在外部网站上。另外,C和C++不是同一种语言,一个中的“自然”解决方案可能无法在另一个中工作(所以只能标记正在编写/编译的语言)。 – crashmstr 2014-09-12 16:34:23
“*(Family_input + old_input.length())= input'背后的想法是什么? – NPE 2014-09-12 16:34:44
[GDB](http://www.gnu.org/software/gdb/)和IDE调试器是你的朋友。了解如何使用它们,您将能够搜索导致段错误的确切线路。 – skrrgwasme 2014-09-12 16:35:37