Home > OS >  Array and pointers to structures
Array and pointers to structures

Time:10-04

So I have this structure

struct Data {
int id;
string message;
};

I am trying to create an array of struct pointers and fill it with values using this

Data *stack[10];
for(int i=0; i<10; i  ){
    stack[i] = (struct Data*) malloc(sizeof(struct Data));
    stack[i]->id = i;
    stack[i]->message = "message"   i;
}

however, I keep getting an error (segmentation fault when debugging) from stack[i]->message = "message" i; Can anyone please help understand what's causing the error and how to solve it?

CodePudding user response:

Below is the working example. You can use smart pointers for automatic memory management, that is the destructor will be called automatically when reference count goes to zero.

#include <iostream>
#include <memory>
using namespace std;
struct Data {
int id;
string message;
Data()
{
    std::cout<<"default consructor"<<std::endl;
}
~Data()
{
    std::cout<<"destructor "<<std::endl;
}
};
int main()
{
   std::cout << "Hello World" << std::endl; 
   std::shared_ptr<Data> stack[10];
  for(int i=0; i<10; i  ){
    
    stack[i] = std::make_shared<Data>();
    stack[i]->id = i;
    stack[i]->message = "message"   std::to_string(i);//make sure to convert the integer to std::string 
    }
    
   //check the value of id for first element in stack
    std::cout<<stack[1]->id<<std::endl;
   return 0;
}

You can also use new instead of malloc but then you will have to call delete explicitly. Note the use of std::to_string() to convert the integer i to string.

  • Related