如何将二维char数组传递给类c ++

时间:2015-05-24 13:32:54

标签: c++ arrays pointers

编辑我相信问题是主要的,课程并没有像它所说的那样被传递。如果我发现错误,我会发布解决方案

编辑我忘记告诉你我在哪里得到错误 在我输入0(表示输入结束)后,我总是得到它

我只想创建一个字符串数组(char数组,是的,我知道std :: string)并将其传递给构造函数,但我一直在获取内存访问错误 编辑:

class person {
  int ID;
  char* pname;
  char* course[30];
public:
  person(){}
  person(int ID, char *pname, char* course[30]){
    if(ID<=999999 && ID>0){
        this->ID=ID;
        pname=new char[256];
        strcpy(this->pname,pname); //this works
        for(int i=0;i<30;i++){
            this->course[i]=new char[256];
            strcpy(this->course[i],course[i]); //but this doesnt
            }
    }
    else printf("\nFehler bei der ID eingabe!\n\n");
}
~person(){
    delete []pname;
    for(int i=0;i<30;i++)
        delete[] course[i];
    delete[] course;
}
};

所以这是我的班级,这是我使用它的部分:

int main(){
  person* array[1000];
  //...
 char temp[256];
 char* course[30];
 int h=0;
 while(i<30&&*temp!='0'){
    fgets(temp,256,stdin);
    if(*temp!='0'){
         while(temp[h]!='\n') h++; //have to do this because i have to  delete the \n from cin
        temp[h]='\0';
        h=0;
        strcpy(course[i],temp);
        //course[i]=temp[i];
        }
    else break;
    i++;
}
while(i<30){
    course[i]=NULL;i++;}
array[pos]=new person(ID,name,course); //pos is a int value which i calculate elsewhere in the code

它工作得很好但是char *数组当然不会工作,即使char *名称就像这样使用。 我是stackoveroflow的新手,我希望我没有过多的代码:S

1 个答案:

答案 0 :(得分:0)

更新3
在你的主要功能中

 for(int j=0;j<30;j++)
    course[j] = new char[256];
 i=0;

并确保你的while循环的i用0初始化 在此之后你的第一次为我工作

第二次,我不明白为什么你把所有的输入(当然[i])变为null,我想你应该删除它。

现在我尝试

char name[50];
strcpy(name,"naruto");
person *xyz = new person(0,name,course);

<强> SUCCESS

更新2
更准确

for(int i=0;i<30;i++)
        strcpy(this->course[i],course[i]); //but this doesnt
        //this->course[i]=course[i];

应该是

for(int i=0;i<30;i++)
{
        this->course[i]=new char[256]; //but this should fix it
        strcpy(this->course[i],course[i]); 
        //this->course[i]=course[i];
}

您之前创建的新数组是针对[i]而不是针对此 - &gt; course [i]

事实上,通过

for(int i=0;i<30;i++)
            course[i]=new char[256];

您基本上覆盖了刚收到的空白字符串输入过程[30],导致出现逻辑错误。 (删除你的代码的这一部分)

旧帖子
在你从temp复制到course [i]之前你所要做的就是

course[i] = new char[MAX_SIZE_OF_YOUR_STRING];

(同样在你的班级以及你处理指针数组的任何地方)

示例
这会崩溃

int main()
{
    char* course[30];
    for(int i=0;i<30;i++)
    {

        cin>>course[i];
    }
}

但这不会

int main()
{
    char* course[30];
    for(int i=0;i<30;i++)
    {
        course[i] = new char[256];
        cin>>course[i];
    }
}