1

When I tried to compile the following program, it gives me no output on screen:

#include<stdio.h>
int main ()
{
struct d1
{
char arr [10];
int num;
};

struct d2
{
struct d1 name;
int age;
}p1;

p1.name={("JANE",8)};
printf ("%s",&p1.name.arr[0]);
}

I think problem is due to line p1.name={("JANE",8)}; But I think I have written everything right. By writing this line I tried to assign value to a member,"name" of variable p1 having structure type d2. And as name is itself a structure of type d1 having two members, so I assigned two values JANE and 8 to arr [10] and num members of name respectively.

I even tried with

p1.name={{"JANE",8}}; //For this it gives error

p1.name={("JANE",8),20}; //For this it compiles but no output

p1.name={{"JANE",8},20}; //again error

That 20 is value of p1's member "age". While trying to print value p1.name.age it gives 0 instead of20.

What's wrong? Is there any syntax error or a conceptual error?

3
  • You need typecast, because compiler does not know, what literal {"JANE",8} is. Use p1.name=(struct d1){"JANE",8}; Commented Jan 30, 2019 at 16:40
  • 4
    @RomanHocke It is not typecasting. It is the compound literal Commented Jan 30, 2019 at 16:45
  • @Avi - we should not answer it. You even did not bother to format the code Commented Jan 30, 2019 at 16:46

2 Answers 2

3
  1. The form you use is only allowed if you initilize the structure. You need to use compound literals.

#include<stdio.h>

int main ()
{

    struct d1
    {
        char arr [10];
        int num;
    };

    struct d2
    {
        struct d1 name;
        int age;
    }p1;

    p1.name=(struct d1){"JANE",8};
    printf ("%s",p1.name.arr);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The printf() is okay, he has &...[0].
2

if is is an initialization do directly :

#include<stdio.h>

int main ()
{
  struct d1
  {
    char arr [10];
    int num;
  };

  struct d2
  {
    struct d1 name;
    int age;
  }p1 = {{"JANE",8}, 20};

  printf ("%s",&p1.name.arr[0]);
}

p1.name.num is 8 and p1.age is 20

note &p1.name.arr[0] can be p1.name.arr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.