-2

What is the difference between ptr->Name = (struct rec*)malloc(sizeof(struct rec)); from ptr->Name = malloc(sizeof(struct rec)); Why is it I'm receiving an error whenever I include (struct rec*) on malloc.

struct rec {
 char *Name;
}emp[100];

int main() {

int x;
int i;

struct rec *ptr = NULL;
ptr = emp;

printf("Enter Number of Clients: ");
scanf("%d", &x);
getchar();

for(i=0; i!=x; i++)
{
printf("Enter Name: ");
//I'm receiving an error whenever I add this
ptr->Name = (struct rec*)malloc(sizeof(struct rec));

//Code below is working
ptr->Name = malloc(sizeof(struct rec));
  • 2
    `ptr->Name` is a `char *`, not a `struct rec *`. You probably intend to allocate to just `ptr`. The second `malloc()` then allocates storage for the name (8 bytes if you're lucky; 4 if you're not) for the name in `ptr[0]`. – Jonathan Leffler Aug 31 '19 at 06:21
  • Your allocation sizeof is wrong too – Antti Haapala -- Слава Україні Aug 31 '19 at 06:23
  • look at this https://stackoverflow.com/questions/47193926/c-malloc-casting-error – samini Aug 31 '19 at 06:26
  • OT: regarding: `struct rec { char *Name; }emp[100];` it is best to separate a struct definition from any instances of that struct – user3629249 Aug 31 '19 at 14:51
  • regarding: `ptr = emp;` results in `ptr` pointing to an array of `struct rec`. Then `ptr->Name = (struct rec*)malloc(sizeof(struct rec));` should be saying: `ptr[0].Name = (struct rec*)malloc(sizeof(struct rec));` Note that `Name` is a pointer to character, not a pointer to an instance of a `struct rec` The result is the compiler outputs an error message – user3629249 Aug 31 '19 at 14:56

1 Answers1

3

ptr->Name is of type char *.

ptr->Name = (struct rec*)malloc(sizeof(struct rec)) explicitly converts the return value from malloc() to a struct rec *. A struct rec * cannot be implicitly converted to a char *, so the assignment to ptr->Name is invalid.

If there is a preceding #include <stdlib.h> in your code, ptr->Name = malloc(sizeof(struct rec)) works because malloc() return void *, and a void * can be implicitly converted to any pointer type, including to a char *. Without the preceding #include <stdlib.h> (or another header which provides a declaration of malloc(), the conversion is also invalid.

void * is the ONLY pointer type in C that can be converted implicitly to another pointer type. Hence the difference between your two options.

The argument of malloc() is also wrong i.e. sizeof(struct rec) should not be used to dynamically allocate an array of char, in most circumstances.

Peter
  • 35,646
  • 4
  • 32
  • 74