Here is my code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct Computer
{
char * model;
char * assembler;
int processorInt;
};
int main()
{
Computer comp;
char* model;
char* assembler;
int processorInt;
cin>>model;
cin>>assembler;
cin>>processor int;
comp.model = model;
comp.assembler = assembler;
comp.processorInt = processorInt;
return 0;
}
//if i do so, it works, BUT if i do in another way, it gives Segmentation Fault
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct Computer
{
char * model;
char * assembler;
int processorInt;
};
void setValues()
{
Computer comp;
char* model;
char* assembler;
int processorInt;
cin>>model;
cin>>assembler;
cin>>processor int;
comp.model = model;
comp.assembler = assembler;
comp.processorInt = processorInt;
}
int main()
{
setValues();
return 0;
}
So what’s the reason?
My goal is to create an array of structures in which i can save some info about each “computer”, then make a possibility to edit any structure and then sort the whole array by procesorInt. But I can’t even create a normal editable structure.
Neither version works, you’re trying to read data into an uninitialized pointer. Just declaring e.g.
char* model;leaves you with a pointer that isn’t initialized: it can point to any spot in memory. When you try to store a string at that location usingcin >>you’ll be writing memory that doesn’t belong to you. This might segfault, or it might appear to work.Just declaring
char*doesn’t give you space for the string: if you’re using standard C strings then you’ll need to give them some data: make yourcharpointers arrays of a fixed size, or usemallocto allocate a string buffer:Or use malloc, but be aware that you’ll need to
freethis memory later:Now, if you’re going to use standard C strings and
cintogether, you shouldn’t use>>at all: there’s no way to limit the input size. Instead usecin.getlinewithMAX_STRING_LENGTHas the limit (see the example in the docs for details).But definitely prefer to use
std::stringinstead: if you do so then you won’t need to deal with providing space for the string yourself, and your code won’t need to change much at all.