Jonathan Vazquez
Jonathan Vazquez

Reputation: 53

Segmentation Fault when utilizing struct array dereference

I'm working on a school assignment. It is an assignment in which every 2 weeks, we have to either expand or change the layout of it. This week, we are forced to use pointers. I'm having a hard time understanding memory and how to allocate it properly without having segmentation faults.

I've created a struct array which is initialized to a char pointer. Every time i loop, after the 1st loop i get "segmentation faults". I simply don't understand why?

I could include the whole code but according to gdb my issue is pertaining to 1 specific line.

const int arraySize = 100;
int counter = 0;

struct contacts{
  char * name;
  char * date;
  char * note;
};

contacts * contactList[arraySize] = 
contactList = new contacts;

for(int i = 0; i <= counter; i++){
  contactList[i]->name = new char[20];  //Segmentation Fault here
  std::cout <<  contactList[i]->name << std::endl; 
  //first 1 outputs = fine
  //2nd output = segmentation error
  counter++;
}

The code is simplified and minimilized for easy reading. If anyone wants it i can insert the whole code. Just be wary that is relatively big. I have set breakpoint through my code to narrow it down. It has come down to that specific statement. Everything else i perfectly fine, especially since it all compiles perfectly fine.

Any hints or assistance with it can be great.

Also I'm not allowed to use any vectors, strings, etc., only cstrings. User mentioned that i only create 1 contact.

contacts * contactList[arraySize];
contactList = new contacts;
//Instead it should be like this:
contacts * contactList[arraySize];
contactList = new contacts[arraySize];

Update: I've tried using what everyone recommended.

contacts* contactList[arraySize];
contactList = new contacts[arraySize];

But i get this error:

error: incompatible types in assignment of‘ContactClass::contacts*’ to ‘ContactClass::contacts* [100]’

Upvotes: 1

Views: 247

Answers (1)

user0042
user0042

Reputation: 8018

Your first problem is in this line:

contacts * contactList[arraySize] = new contacts;

it should be

contacts* contactList = new contacts[arraySize];

next problem is here

for(int i = 0; i <= counter; i++){

should be

for(int i = 0; i < arraysize; i++){
    contactList[i].name = new char[20];
}

Upvotes: 2

Related Questions