C Programming - Structures, Unions, Enums - Discussion

Discussion Forum : Structures, Unions, Enums - Yes / No Questions (Q.No. 4)
4.
Will the following code work?
#include<stdio.h>
#include<malloc.h>

struct emp
{
    int len;
    char name[1];
};
int main()
{
    char newname[] = "Rahul";
    struct emp *p = (struct emp *) malloc(sizeof(struct emp) -1 +
                    strlen(newname)+1);

    p->len = strlen(newname);
    strcpy(p -> name, newname);
    printf("%d %s\n", p->len, p->name);
    return 0;
}
Yes
No
Answer: Option
Explanation:
The program allocates space for the structure with the size adjusted so that the name field can hold the requested name.
Discussion:
9 comments Page 1 of 1.

CBee said:   1 decade ago
When allocating space for p, +1 & -1 cancel, leaving space for 'emp' plus 'newname'
Hence it is now possible to copy newname to p->name, since p->name, now has the exact number of bytes to accommodate 'newname'
Hence code works

Gaurav said:   1 decade ago
The possibility that a structure might contain a union makes it hard to compare such structures; the compiler can't tell what the union currently contains and so wouldn't know how to compare the structures.

Austin said:   8 years ago
Sorry this code won't run as string.h is not included. It would throw an error that strlen() is undefined. I got this wrong for that reason, even though this code wouldn't run.

Akku said:   3 years ago
@Roddur.
It says char p[1].
So it stores only one char value right?
Then how it's storing "rahul" as a whole? Please explain your answer in detail.

Thenu said:   8 years ago
Please anone explain the meaning of this line.

struct emp *p = (struct emp *) malloc(sizeof(struct emp) -1 strlen(newname)+1)

Roddur said:   5 years ago
It says char p[1].
So it stores only one char value right?
Then how it's storing "rahul" as a whole?

Prakash said:   1 decade ago
Please anyone can explain brifly this code. Please help me.

Salvatores said:   3 years ago
What is the output of this code? Explain, please.

Bavu said:   8 years ago
I run the code but it gives me errors.

Post your comments here:

Your comments will be displayed after verification.