我想动态分配结构数组“student”
struct student
{
char* name;
};
int main(int argc,char* argv[])
{
if(argc==2)
{
student* sptr=new student[4];
for(int i=0;i<atoi(argv[1]);i++)
{
cin>>*(*(sptr+i)).name;
}
for(int i=0;i<atoi(argv[1]);i++)
{
cout<<*(*(sptr+i)).name;
}
}
}
代码编译没有错误,但在运行时,输入名字后是 说“段错误(核心已转储)”并停止。我哪里出错了?
最佳答案
- 你不需要一个结构来只保存一个字符串
- 你不需要在每次迭代中调用
atoi
- 您需要分配内存以接收用户输入
工作代码如下:
int main(int argc,char* argv[])
{
// Exit if wrong number of arguments
if(argc != 2)
{
cout << "Incorrect number of argements";
return 1;
}
// Convert argument from ASCII to int once
int numberOfValues = atoi(argv[1]);
// Create array of strings (pointer of pointers to characters)
char** ppValues = new char*[numberOfValues];
// Loop to collect strings
for (int i = 0; i < numberOfValues; i++)
{
// Local variable to collect one string
char buffer[1024];
cin >> buffer;
// Allocate memory in one of the array entries to hold the current entry
ppValues[i] = new char[strlen(buffer) + 1];
// Copy value from temp string to final string location
strcpy(ppValues[i], buffer);
}
for (int i = 0; i < numberOfValues; i++)
{
cout << ppValues[i];
}
return 0;
}
关于c++ - 结构数组的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969367/