Hello i tried to compile my code but i get acess violation error. Im trying to make an agenda that i can insert values using a list. What is the error in my code?
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct ap_agenda{
char *name;
char *telefone;
struct ap_agenda *proximo;
};
void init(ap_agenda* lista){
lista = NULL;
}
void insere(char *nome, char *telefone, ap_agenda* lista){
ap_agenda *p;
p = (ap_agenda*) malloc(sizeof(ap_agenda*));
p->name = nome;
p->telefone = telefone;
if(lista == NULL){
lista = p;
}else{
lista->proximo = p;
}
}
void imprime(ap_agenda *lista){
cout << lista[0].name << endl;
}
int main(){
ap_agenda agenda;
init(&agenda);
insere("test","123456",&agenda);
imprime(&agenda);
system("pause");
}
Thanks !
Hello, thanks for the answers! I changed my code and now its “working” but when i try to print the list, its jump one line.
void insere(std::string nome, std::string telefone, ap_agenda* lista){
ap_agenda *p = new ap_agenda;
p->name = nome;
p->telefone = telefone;
p->proximo = NULL;
if(lista == NULL){
lista = p;
}else{
while(lista->proximo != NULL)
lista = lista->proximo;
lista->proximo = p;
}
}
void print(ap_agenda* lista){
ap_agenda *p;
for(p=lista; p!=NULL; p=p->proximo)
cout << p->name.c_str() << endl;
}
The output is:
[blankline]
test1
test2
The access violation probably comes from your call to
inserewhich isn’t working like you think it does.When this is passed to init:
At this point
agendahad not been modified or initialized in any way. Now you pass the address ofagendaoff toinsere.insereis definedNote that when this returns,
nomeandtelefoneof the stack variableagendahave not been initialized.When the address of the stack variable
agendais passed toimprimeit tries to print the value ofnamewhich has not been initialized.If instead, you passed in the
proximomember ofagendawhich was initialized ininsereyou would see thenamevalue printed.However, as others have pointed out, there are a lot of other issues in this code.