我的任务是使用结构将短语从猪拉丁语翻译成英语。到目前为止,我的项目接受了一个字符串,除了结尾的标点符号之外,删除了所有大写字母,所有标点符号,并将字符串拆分为由单词组成的数组结构。然后,我应该通过return语句特别返回一个指向我的结构数组的指针。回到主界面时,我想创建另一个与我的pigLat函数中相同的结构数组,以便能够发送给我的项目的第二部分的新函数(这将包括将拉丁文翻译成英文) 。指向C++结构数组的指针的问题
问题:尝试使用指针创建新数组会导致核心分段错误。
任何帮助解释为什么这不起作用,并解释什么可能会更好地工作,将不胜感激!
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
struct Word //Variable type to hold each word
{
string piglatin;
string english;
};
Word *pigLat(int &);
int main()
{
int size;
Word *phrase;
phrase = pigLat(size); //Passes value of size by reference, and returns ptr to structure
Word pigSent[size];
//THIS IS WHERE I GET SEGMENTATION FAULT************************************
for (int count = 0; count < size; count++)
{
pigSent[count].piglatin = phrase[count].piglatin;
}
//*************************************************************************
return 0;
}
//Receives a phrase in pig latin, finds # of words in phrase, seperates pig latin from english, returns pig latin
Word *pigLat(int &sizeOf)
{
string phrase; //Variable to hold pig latin phrase
cout << "Enter a phrase in pig latin: "; //User enters pig latin phrase
getline(cin, phrase);
char punctuation = phrase[phrase.length() - 1]; //Assumes last char is punctuation, and saves it
//Removes all characters besides last period
char removch[] = "&,'?.!-";
for (int count = 0; count < 7; count++)
{
phrase.erase(remove(phrase.begin(), phrase.end(), removch[count]), phrase.end());
}
int length = phrase.length(); //Number of elements in updated string
phrase.insert(length, 1, punctuation); //Inserts final punctuation at end of phrase
//Removes all capitalization
for (int count = 0; count < length; count++)
{
if(phrase[count] >= 'A' && phrase[count] <= 'Z')
{
phrase[count] = tolower(phrase[count]);
}
}
int index = 0;
int count = 0;
int *spaceElements = 0;
spaceElements = new int[length]; //Dynamically allocates spaceElements memory
for (count; count < length; count++) //Gives number of white spaces in phrase
{
if (phrase.find(' ', count) != -1)
{
int space = phrase.find(' ', count);
count = space;
spaceElements[index] = space;
index++;
}
}
sizeOf = (index + 1);
Word sentence[sizeOf];
int start = 0;
int end = 0;
count = 0;
//Copies, word by word, into Word array sentence
for (count; count < sizeOf; count++)
{
for (count; count < index; count++)
{
end = spaceElements[count] - start;
sentence[count].piglatin = phrase.substr(start, end);
start = spaceElements[count] + 1;
}
sentence[count].piglatin = phrase.substr(start, length);
}
//Testing***************************************************
for (count = 0; count < sizeOf; count++)
cout << endl << sentence[count].piglatin << endl;
//**********************************************************
delete [] spaceElements;
Word *ptrToSet = sentence; //assigns pointer to memory address of sentence array
return ptrToSet;
}
标准C++中不允许使用'Word pigSent [size];'。编译时必须知道数组的维数。相反,你可以使用'std :: vector pigSent(size);'。在其他功能 –