Reputation: 33
//The struct
typedef struct {
int nr;
char *nume, **mesaj;
} utilizator;
void citire_mesaje(utilizator *user, int n)
{
user->nr = malloc (n * sizeof(int));
scanf("%d", &user[0].nr);
printf("user[0].nr = %d\n", user[0].nr);
}
int main()
{
int n;
utilizator *user = malloc (sizeof(utilizator));
citire_mesaje(user, n);
return 0;
}
What am I doing wrong? I used user[0].nr just to test it more easily. I can get it work if I only use one element of type struct (utilizator user;), but I can't figure it out if I use a pointer. I get:
warning: assignment makes integer from pointer without a cast [enabled by default]
user->nr = malloc (n * sizeof(int));
^
Any suggestions?
Upvotes: 2
Views: 98
Reputation: 7424
You are allocating the memory for your variables the wrong way. You should use the casting
(change the type of the value returned by malloc
to the type of the variable):
// In the citire_mesaje function
user->nr = (int) malloc (n * sizeof(int));
// In the main function
utilizator *user = (utilizator *) malloc (sizeof(utilizator));
Your final code should look like this:
//The struct
typedef struct {
int nr;
char *nume, **mesaj;
} utilizator;
void citire_mesaje(utilizator *user, int n)
{
user->nr = (int) malloc (n * sizeof(int));
printf("Enter a value for user[0].nr: ");
scanf("%d", &user[0].nr);
printf("user[0].nr = %d\n", user[0].nr);
}
int main()
{
int n; // make sure to inisialize the n variable
utilizator *user = (utilizator *) malloc (sizeof(utilizator));
citire_mesaje(user, n);
return 0;
}
Upvotes: 0
Reputation: 5389
First, you do not need to user->nr = malloc (n * sizeof(int));
because nr
is just an int
and it have its own memory space of length sizeof(int) bytes
.
Secondly and most important,
You are not including the header file
#include <stdlib.h>
. Beacuse of this, the malloc function is implicitly declared to return int. Since you are treating the result as a pointer, there is a type-mismatch warning there.
All you have to do is, include the file stdlib.h
.
void*
will be safely promoted to any other pointer type in this case.
So, your code should be something like this::
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int nr;
char *nume, **mesaj;
} utilizator;
void citire_mesaje(utilizator *user, int n)
{
scanf("%d", &user[0].nr);
printf("user[0].nr = %d\n", user[0].nr);
return ;
}
int main()
{
int n = 0 ;
utilizator *user = malloc (sizeof(utilizator));
citire_mesaje(user, n);
free( user ) ;
return 0;
}
Upvotes: 0
Reputation: 24528
It seems, nr
is an array of int
and not just int
. Fix it's declaration:
typedef struct {
int * nr;
char *nume, **mesaj;
} utilizator;
If you only want one int
, don't call malloc
. It will be allocated as part of your utilizator
object (funny word btw).
Upvotes: 1