#include <iostream>
#include <string>
using namespace std;
//create a struct to have model number and name and a pointer to next book
struct comp
{
string nam;
int mnum;
comp* next;
};
// define comp pointer to compPtr
typedef comp* compPtr;
int main()
{
compPtr head = NULL;
compPtr last = NULL;
if (head == NULL)
{
compPtr temp;
temp->nam = "Dell";
temp->mnum = 45215;
temp->next = NULL;
head = temp;
last = temp;
}
if (head != NULL)
{
compPtr temp1;
temp1->nam = "Mac";
temp1->mnum = 1255;
temp1->next = NULL;
last->next = temp1;
last = temp1;
}
compPtr compnext;
compnext = head;
if (compnext == NULL)
{
cout<<"NO COMPUTERS";
}
else
{
while(compnext != NULL)
{
cout<<compnext->nam<<endl;
cout<<compnext->mnum<<endl;
compnext = compnext->next;
}
}
}
Why is there a Segmentation Fault in this code?
Don't "hide" pointers behind a typedef -- it will only confuse you.
Your code is equivalent to:
comp *temp; // Note: does not point *anywhere*.
temp->nam = "Dell"; // Dereferencing uninitialized pointer, undefined behavior,
// often crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With