Structures - find output programs in C (Set 1)

This section contains find output programs on C language Structures; each question has correct output and explanation about the answer.

Predict the output of following programs.

1) Is the following declaration of structure 'tag' is correct?

int main()
{
	struct tag{
		int a;
		float b;
	};
	//other statement 
	return 0;
}

Explanation

Yes, structure tag is declared in the main() block and it is allowed in C language, the scope of tag will be local and we can access tag inside main() only.


2) Is the following declaration of structure 'tag' is correct?

int main()
{
	struct tag{
		int a=0;
		float b=0.0f;
	};
	//other statement 
	return 0;
}

Explanation

No, we cannot initialize any member of the structure with in its declaration.


3) What will be the output of following program?

#include <stdio.h>
int main()
{
	struct tag{
		int a;
		float b;
	};
	
	struct tag t={10,10.23f};
	printf("%d, %.02f\n",t.a,t.b);
	return 0;
}

Output

10, 10.23

Explanation

Structure members can be initialized while declaring its object (structure variable) like struct tag t={10,10.23f};


4) Is the following structure variable declaration is correct? If yes, what will be the output of following program?

#include <stdio.h>
int main()
{
	struct person{
		char *name;
		int age;
	};
	
	struct person p={"Mani",21};

	printf("%s, %d\n",p.name,p.age);	
	
	return 0;
}

Output

Mani, 21

Explanation

Yes, the structure variable declaration is correct, we can initialize string value like this (consider the statement struct person p={"Mani",21};).


5) What will be the output of this program?

#include <stdio.h>
int main()
{
	struct person{
		char name[30];
		int age;
	};
	
	struct person p={"Mani",21};

	//edit values
	p.name="Vanka";
	p.age=27;

	printf("%s, %d\n",p.name,p.age);	
	
	return 0;
}

Output

Error

Explanation

String cannot be assigned directly (p.name="Vanka";), we can use strcpy or memcpy to copy the string.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.