473,788 Members | 2,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pointers and nested structures

Hello,
I am really scrwed up with the following stuff:

struct employee
{
char* employee_name;
};

struct department
{
char* department_name ;
struct employee* emp; //Collection of all employees in a
department
};

In main(), I wrote
struct department* company;

I want to first enter the name of department and
then names of employees in that department. I tried with pointers but I
must hv messed up somewhere n getting segmentation faults. Tried using
array representation e.g. company[i].emp[j].employee_name . This also
failed. I used new operator but it didn't help. Please tell me how to
deal such thing in pointers.

Thanks!!!

Nov 28 '06 #1
6 5879
struct employee
{
char* employee_name;
};
employee_name is only a pointer and does not hold any memory. It may be
better to use array instead of pointer here, or you must allocate
memory for each employee and this operation can easily lead to memory
leakage.

char employee_name[MAX_LEN];
and the struct is not complete cause you want to create a list. you
should add a member
struct employee * next;

struct employee
{
char employee_name[MAX_LEN];
struct employee * next;
};
struct department
{
char* department_name ;
Here, the same as employee_name
struct employee* emp; //Collection of all employees in a
department
};

In main(), I wrote
struct department* company;
company is also a pointer. Follwing this, you should write
company = (struct department *)malloc(sizeof (struct department));
>
I want to first enter the name of department and
then names of employees in that department. I tried with pointers but I
for each time you add a new employee, allocate memory using malloc,
make its next point to emp and then make the next of emp point to the
new memory.

char temp_name[MAX_LEN];
company->emp = NULL;
while (scanf("%s", temp_name) != EOF)
{
struct employee * pe = (struct employee *)malloc(sizeof (struct
employee));
strcpy(pe->employee_nam e, temp_name);
pe->next = company->emp;
company->emp = pe;
}
must hv messed up somewhere n getting segmentation faults. Tried using
array representation e.g. company[i].emp[j].employee_name . This also
failed. I used new operator but it didn't help. Please tell me how to
deal such thing in pointers.

Thanks!!!
do not free the memory you allocate at last.
new is c++ operator and not supported by pure C.

Sorry for my poor expression.

Nov 28 '06 #2
struct employee
{
char* employee_name;
};

employee_name is only a pointer and does not hold any memory. It may be

better to use array instead of pointer here, or you must allocate
memory for each employee and this operation can easily lead to memory
leakage.

char employee_name[MAX_LEN];
and the struct is not complete cause you want to create a list. you
should add a member
struct employee * next;
struct employee
{
char employee_name[MAX_LEN];
struct employee * next;

};
struct department
{
char* department_name ;

Here, the same as employee_name

struct employee* emp; //Collection of all employees in a
department
};
In main(), I wrote
struct department* company;


company is also a pointer. Follwing this, you should write
company = (struct department *)malloc(sizeof (struct department));

I want to first enter the name of department and
then names of employees in that department. I tried with pointers but I


for each time you add a new employee, allocate memory using malloc,
make its next point to emp and then make the next of emp point to the
new memory.

char temp_name[MAX_LEN];
company->emp = NULL;
while (scanf("%s", temp_name) != EOF)
{
struct employee * pe = (struct employee *)malloc(sizeof (struct
employee));
strcpy(pe->employee_nam e, temp_name);
pe->next = company->emp;
company->emp = pe;

}
must hv messed up somewhere n getting segmentation faults. Tried using
array representation e.g. company[i].emp[j].employee_name . This also
failed. I used new operator but it didn't help. Please tell me how to
deal such thing in pointers.
Thanks!!!


do not forget to free the memory you allocate at last.
new is c++ operator and not supported by pure C.

Sorry for my poor expression.

Nov 28 '06 #3
Computer Wizard wrote:
Hello,
I am really scrwed up with the following stuff:

struct employee
{
char* employee_name;
};

struct department
{
char* department_name ;
struct employee* emp; //Collection of all employees in a department
};
As it is, employee is designed to hold the name of only one employee.
However you indicate in your comments that you want it to hold the
names of all the employees of a department. To do that, among other
methods you can do:

struct employee {
char *employee_name;
struct employee *next
};

You can use the above to maintain a linked list of employees embedded
within department.

An easier method is:

struct department {
char *department_nam e;
char **employees;
}

Then during runtime you can set employees to point to an array of
pointer of type char, each of which will point to an employee's name
string.

You can also use a static array within either employee or department if
you know in advance the number of employees and that it wouldn't need
to grow during runtime.

The linked list method is more flexible since it also allows you to
hold additional information about each employee along with the name.
In main(), I wrote
struct department* company;

I want to first enter the name of department and
then names of employees in that department. I tried with pointers but I
must hv messed up somewhere n getting segmentation faults.
<snip>

You've simply allocated a pointer to struct of type department. Now
you'll have to initialise the pointer to point to an actual instance of
department. You'll have to use malloc() to do so:

struct employee *tmp;
company = malloc(sizeof *company);
if(company != NULL) {
company->department_nam e = malloc(SIZE_OF_ DEP_NAME);
if(company->department_nam e == NULL) DEAL_WITH_ERROR ;
company->emp = malloc(sizeof *emp);
if(company->emp == NULL) DEAL_WITH_ERROR ;
tmp = company->emp;
tmp->employee_nam e = malloc(SIZE_OF_ EMP_NAME);
if(tmp->employee_nam e == NULL) DEAL_WITH_ERROR ;
}
else DEAL_WITH_ERROR ;

Now you can store values using the -operator.

PS. 'new' is C++. If you're using new then better post in comp.lang.c++

Nov 28 '06 #4

Computer Wizard (surely some mistake - if you ask these questions
you're no Wizard) wrote:
Hello,
I am really scrwed up with the following stuff:

struct employee
{
char* employee_name;
};
OK - so employee_name points to some storage. How did you assign the
storage?
struct department
{
char* department_name ;
struct employee* emp; //Collection of all employees in a
department
};
Please don't use "//" comments in usenet postings - they wrap and mess
things up.
They are also not supported in the C standards most commonly used.

In your department structure, you have a pointer to an employee
structure - where do you assign the space for the employee structure?
(Alternatively you have a point to the first of an array of employee
structures - where do you assign the space for them?)
In main(), I wrote
struct department* company;
So company is a pointer to a department structure (is that really what
you meant?). Where do you assign the space for the department
structure. (Or again, where do you assign the space for the
array of department structures?)
>
I want to first enter the name of department and
then names of employees in that department. I tried with pointers but I
must hv messed up somewhere n getting segmentation faults.
"hv" ? "n"? Please type in English. You are clearly capable of doing
so.
Tried using
array representation e.g. company[i].emp[j].employee_name . This also
failed.
If you haven't assigned space, then whether you express your operations
directly as pointer operations or as array operations, they will still
fail.
I used new operator but it didn't help.
There is no "new" operator in C. If you want to ask about C++, go to an
appropriate newsgroup. If you want to dynamically allocate space in C,
look at using the malloc() family of functions.
Please tell me how to deal such thing in pointers.
There's a lot to do here and much of it could be better done by reading
some books or online tutorials.

However if you really want us to help you, post a complete program
showing what you have tried and describe what happened.
>
Thanks!!!
Nov 28 '06 #5
Computer Wizard wrote:
Hello,
I am really scrwed up with the following stuff:

struct employee
{
char* employee_name;
};
You'll need to allocate memory for each employee name. That's OK.
struct department
{
char* department_name ;
struct employee* emp; /* Collection of all employees in a department */
};
Your '//' comment wrapped to the next line. When posting code to Usenet
groups like comp.lang.c you're better off using traditional /* */
comments that will not prevent compilation if wrapped.

You can allocate a block of memory for emp, like an array of employees.
You then face the problem of how to know how many employees are in the
array. If you don't want to add another entry to the department struct,
you can use the employee_name pointer to determine the end of the array.
If the employee_name is null, then that is the end of the array.
In main(), I wrote
struct department* company;
Ok, similarly here you can allocate a block of memory for company, like
an array of departments. Similarly you can use a null department_name to
determine the end of the company array.
I want to first enter the name of department and
then names of employees in that department. I tried with pointers but I
must hv messed up somewhere n getting segmentation faults.
It's pretty easy to mess up in C. Make sure you initialised each pointer
properly, and that it is pointing to valid memory. Make sure there is
enough memory allocated for each item you try to store into it. If you
need to extend an allocated array to make room for more elements, you
can use realloc().
Tried using
array representation e.g. company[i].emp[j].employee_name . This also
failed. I used new operator but it didn't help. Please tell me how to
deal such thing in pointers.
company[i].emp[j].employee_name should work, so long as you allocated
memory for company, emp and employee_name.

company = malloc(sizeof *company);
if(!company) exit(EXIT_FAILU RE);

company[0].emp = malloc(sizeof *company[0].emp);
if(!company[0].emp) exit(EXIT_FAILU RE);

company[0].emp[0].employee_name
= malloc(sizeof *company[0].emp[0].employee_name) ;
if(!company[0].emp[0].employee_name) exit(EXIT_FAILU RE);

Others have suggested using a linked list. That is one option, but if
you want to use the structs you have given above without any
modification, then a realloc solution is a reasonable way to go.

Here's some example code that I think does what you're trying to do.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct employee
{
char* employee_name;
};

struct department
{
char* department_name ;
struct employee* emp; /* Collection of all employees
in a department */
};

void err_mem(void)
{
fprintf(stderr, "Error allocating memory\n");
exit(EXIT_FAILU RE);
}

/* mallocs a copy of the given string and removes
a newline character if it is present */
char *get_str(const char *buf)
{
char *p = malloc(strlen(b uf) + 1), *q;
if(!p) err_mem();
strcpy(p, buf);
q = strchr(p, '\n');
if(q) *q = 0;
return p;
}

void add_department( struct department *company)
{
char buf[128];
size_t n = 0, alloc = 8; /* initial allocation */
printf("Enter department name: ");
fflush(stdout);
fgets(buf, sizeof buf, stdin);
company->department_nam e = get_str(buf);
company->emp = malloc(alloc * sizeof *company->emp);
if(!company->emp) err_mem();
do
{
printf("Enter employee name or just hit Enter when done: ");
fflush(stdout);
fgets(buf, sizeof buf, stdin);
if(buf[0] != '\n')
{
company->emp[n].employee_name = get_str(buf);
n++;
if(n == alloc)
{
void *p;
alloc *= 2;
p = realloc(company->emp, alloc * sizeof *company->emp);
if(!p) err_mem();
company->emp = p;
}
}
} while(buf[0] != '\n');

/* NULL employee name indicates the
end of the array of employees */
company->emp[n].employee_name = NULL;
}

struct department *new_company(vo id)
{
size_t n = 0, alloc = 8;
char buf[128];
struct department *company = malloc(alloc * sizeof *company);
if(!company) err_mem();
add_department( company + n);
n++;
do
{
printf("Do you want to add another department? (yes/no) ");
fflush(stdout);
fgets(buf, sizeof buf, stdin);
if(!strcmp(buf, "yes\n"))
{
add_department( company + n);
n++;
if(n == alloc)
{
void *p;
alloc *= 2;
p = realloc(company , alloc * sizeof *company);
if(!p) err_mem();
company = p;
}
}
} while(strcmp(bu f, "no\n"));

/* NULL department name indicates the
end of the array of departments */
company[n].department_nam e = NULL;

return company;
}

void print_departmen t(const struct department *department)
{
size_t i;
printf("Departm ent %s:\n", department->department_nam e);
for(i = 0; department->emp[i].employee_name != NULL; i++)
{
printf("Employe e %d: %s\n", i + 1,
department->emp[i].employee_name) ;
}
}

void print_company(c onst struct department *company)
{
size_t i;
for(i = 0; company[i].department_nam e != NULL; i++)
{
print_departmen t(company + i);
}
}

int main(void)
{
struct department *company = new_company();
print_company(c ompany);
return 0;
}

--
Simon.
Nov 29 '06 #6

Thank you everybody for all the help. I surely can handle such stuff
now........ :)

Dec 21 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
390
by: Sam | last post by:
Hi everyone I'm confused by these declarations: struct hostent *he; server *s = (server*)malloc(sizeof(server)); /* in the code * he = gethostbyname(name);
11
2014
by: Alfonso Morra | last post by:
Hi, I have the ff data types : typedef enum { VAL_LONG , VAL_DOUBLE , VAL_STRING , VAL_DATASET }ValueTypeEnum ;
0
1443
by: Andre | last post by:
Hi, I have a problem with marshaling nested structures struct a { struct b s_b; struct d s_d;
2
2469
by: samba | last post by:
I having a nested structures which are referenced with pointer variables #include <stdio.h> struct test { int i; char *mytest; }; struct sample {
3
6681
by: Amit_Basnak | last post by:
Dear Friends I have the follwoing function "tss_fe_get_own_info" which has the arguments as shows below tss_fe_get_own_info(char *user_id, tss_user_profile_t **p_buf_UserSecInfo, error_status_t *retStatus) // Structure tss_user_profile_t from the function typedef struct {
10
7521
by: bimbam | last post by:
Hi, I've been trying to allocate dynamicaly an array of pointers to structures. As it didn't work, I tried to reduce the problem as much as possible. This is what I have : #include <stdio.h> #include <stdlib.h> typedef struct {
1
3960
by: bimbam | last post by:
Hi, I wish to sort an array of pointers to structures. There must be something I don't get. Here is my code: ... typedef struct { ...
8
5943
by: Sheldon | last post by:
Hi, Can anyone help with this problem with setting up nested structures and initializing them for use. I have created several structs and placed them in a super struct that I will then pass to some functions. I have defined them in the following manner: typedef struct trans Transient; typedef struct sats Satellites;
25
4740
by: Andreas Eibach | last post by:
Hi again, one of the other big woes I'm having... typedef struct perBlockStru /* (structure) Long words per block */ { unsigned long *lword; } lwperBlockStru_t;
0
10370
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10177
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10113
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5402
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4074
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2896
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.