Why not print the contact variable[0]->a?

Asked

Viewed 42 times

0

Pointers still confuse me mostly in situations like this. The idea is simple. I’m trying to create a pointer vector like struct. But I must be using some misconception of pointers because the program is not displaying what I ask. I wanted to know what could be wrong. If I remedy this doubt will help me a lot. A big thank you to whoever wants and can help me.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct agenda_x
{
    char nome[50];
    char tel[10];
    int a;
};

struct agenda_x *contato[2];

int main()
{
    contato[0]->a=4;
    printf("%i",contato[0]->a);
}
  • If they confuse you, what do you think of the idea of doing something simpler until you get the hang of it and then move on to something more sophisticated?

  • It’s because it’s work so there’s no way kskskskkssk but I think I understand what happened

2 answers

0

You’re declaring a pointer to 2-position vectors and not allocating... Since it is a global variable, it is being initialized for NULL, test the following:

if(contato[0] == NULL)
    printf("valor nao inicializado");

And notice that you’re trying to reference a null pointer.

To correct I have the following suggestions:

1 - Or you add the following row before assigning the value 4:

contato[0] = (struct agenda_x*) malloc(sizeof (struct agenda_x));

2 - or you can change the whole code to the following:

struct agenda_x contato[2];

int main()
{
   contato[0].a=4;
   printf("%i",contato[0].a);
}

0

I believe that you are having some difficulty understanding the initialization of the pointer to the struct. This is normal, come on: In doing

struct agenda_x *contato[2]

You are creating an array of pointers that will point to agenda_x, not an array of 2 spaces of the scheduled struct type_x. I believe you want the space to save 2 contacts, so there are two options:

struct agenda_x *contato;
contato = (struct agenda_x *) malloc(2*sizeof(struct agenda_x);

Now we’ve allocated 2 spaces to use as a contact. We can use contact[0] and contact[1] without having memory problems. You can still do:

struct agenda_x contato[2];

If you treat this struct as a pointer, as in the first case, where you use malloc, you will use the contact->a notation to access the first element (if you want to access another, just increase the contact *contact++, otherwise you will use contact[0]. a and contact[1]. a to access the elements. I hope I’ve helped.

Note: malloc must be done inside a function, but the variable can be declared global without problems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.