Day#38 'C' Coding Challenge

Day#38 'C' Coding Challenge

What is the output of the below code?

#include <stdio.h> struct website { char name[]; int forum_pages; }; void main() { struct website site_ptr = {"forum.Talenteve.com",10}; printf("%d\n",site_ptr.forum_pages); printf("%s\n",site_ptr.name); }

----------------------------------------------------------------------------------

The above code tests below scenarios:

1. Defining a structure
2. Memory assignment for structure
3. what happens if array index is not declared?

----------------------------------------------------------------------------------

structure website has been declared with elements name[] and forum_pages.
while forum_pages has a fixed memory allocation, for example in a 32-bit system, 4 bytes shall be allocated for forum_pages as it is integer variable.
For name[], there is no index and hence compiler cannot decide the amount of memory to be allocated.
For a structure, contiguous memory allocation shall be done and in above case the memory cannot be decided and hence throws an error.
In the above case, the structure elements can be arranged in the below manner.

struct website { int forum_pages;
char name[]; };

The simplest way to eliminate this error is,

struct website { char name[50];
int forum_pages;
};

A structure variable of name site_ptr has been declared which is used to access the elements of the structure. Member access operator (.) is used to access any element of the structure using it's variable.

Post a Comment

0 Comments