473,884 Members | 2,315 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic Allocation of an array/struct data structure

3 New Member
Howdy folks,

I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or deleted, however it must be initialized by a function during run-time to contain so many users which each contain so many directories of which each contain so many files. I've completed the program and have it running flawlessly without implementing dynamic memory allocation with this data structure.

struct File
int file_permission ;
struct Directory
char directory_name[64];
struct File filenum[10];
struct User
char user_name[64];
int group_status;
struct Directory directorynum[10];
struct Api
char api_name[64];
struct User usernum[10];

As you can see, all the struct arrays are initialized to 10. My problem is converting this to be initialized dynamically. Keep in mind, The initialization is only done with a function that only returns 0 on success and -1 on error. Additionally the only parameters in the function are the sizes of the arrays. So main looks something like this:
int main() {
sfs_init(5, 5, 5, 5);
return 0;
where it has the parameters sfs_int(int us, int ds, int fs, int gs);
us = number of users,
ds = number of directorys,
fs = number of files,
gs = number of groups.
Although I have groups implemented by a simple status int for each user. This is why I have a global variable setup as a pointer:

struct Api *SFS_Ptr;

In the function itself, I also intialize a struct Api:

sfs_int(int us, int ds, int fs, int gs); {
struct Api SFS;

To link the global pointer and the struct in the function i use:

SFS_Ptr = &SFS;

Then it's just a matter of initializing everything to the parameters:
for(i = 0; i < us; i++)
{ strcpy(SFS_Ptr->usernum[i].user_name, "u");
sprintf(buf1, "%d", i);
strcat(SFS_Ptr->usernum[i].user_name, buf1);
SFS_Ptr->usernum[i].group_status = 0;

for(j = 0; j < ds; j++)
{strcpy(SFS_Ptr->usernum[i].directorynum[j].directory_name , "d");
sprintf(buf2, "%d", j);
strcat(SFS_Ptr->usernum[i].directorynum[j].directory_name , buf2);

for(k = 0; k < fs; k++)
{ SFS_Ptr->usernum[i].directorynum[j].filenum[k].file_permissio n = 700;


The username and directory names get strcpy'd u0 or d0 respectively. The filename gets an int 700, which represents a file permission.

All of this works perfectly. Now how the heck can I implement this with dynamic memory allocation. I've come up with a partial solution but it probably just needs something very minor to work properly. So, the first thing I've done is change the arrays in the structs.
struct User usernum[10] to struct User* usernum
struct Directory directorynum[10] to struct Directory* directorynum
struct File filenum[10] to struct File* filenum

After doing this, I went in the function to add the mallocs like so:
SFS_Ptr->usernum = (struct User*) malloc(us * sizeof(struct User));

SFS_Ptr->usernum->directorynum = (struct Directory*) malloc(ds * sizeof(struct Directory));

SFS_Ptr->usernum->directorynum->filenum = (struct File*) malloc(fs * sizeof(struct File));

What does this produce? Not what was working before. Essentially, using printfs I've discovered that this does indeed allocate memory but it's not the way I want. This is the layout I need, and what I had working before:
u0 ...... ui
d0 ... dj d0 ... dj
f0...fk f0...fk f0...fk f0...fk

Instead I'm getting this:

u0 ...... ui
d0 ... dj

So it's mallocing the correct size for the files, directory, and users based on the parameters in the sfs_int(initial ization function); however, it's completely killing the links between the different levels. For example if you scrolled backup and inserted a printf("DEBUG\n "); in the inner most for loop, running off variable k, which initializes the file_permission 's to 700, after the actual initialization and you run the program you'd get:
Segmentation Fault

Because! The number of files in each directory is set to 5 and the struct array pointers are not pointing the files to any of the directories beyond the first one, as illustrated by the diagram above. Just like the directories are not pointed to any of the users beyond the first one, but this doesn't generate a problem for the user because there are no levels above the initial 5 users. So if anyone can possibly point me in the right direction I'd really appreciate it. I've experimented with the casting of the malloc numerous times with no success so I'm guessing this is a problem with the actual structure setup. Keep in mind nothing can be added to main other then the initializing function, and no parameters can be changed. Based on what I've had to relearn regarding pointers it seems like transforming the arrays into pointers is the right way to go in the structures but nothing goes indepth about handling this with arrays that point to arrays that point to arrays...

Thanks for your time, sorry for so much writing. You guys emphasize explaining hehe.
Dec 5 '06 #1
4 5077
3 New Member
Sorry, diagram above didn't come out right this is what it should look like:
************u0> >>>>>>>>>>>>>>> >>>>>>>>>>>>>>> ui************* *************
***d0>>>>>>>>>> dj************* *************** ***d0>>>>>>>>>d j************** ****
*f0>>>fk******* ***f0>>>fk***** *************** ****f0>>>fk**** ****f0>>>fk**** **********

Instead I'm getting this:

************u0> >>>>>>>>>>>>>>> >>>>>>>>>>>>>>> ui************* *************
***d0>>>>>>>>>> dj************* *************** *************** *************** **********
*f0>>>fk******* *************** *************** *************** *************** ***************
Dec 5 '06 #2
1,806 Top Contributor
How do you iterate through the structs? I suspect you are not chnaging your pointer correctly between different instances of structs.

I also think your structurs should contain arrays of pointers to structs not the structs themselves (although I always manage to confuse myself when it comes to pointers....).
Dec 5 '06 #3
3 New Member
Iterating through the structure depends on what you want to access, for example if you want to access a file permission you would use

SFS_Ptr->usernum[i].directorynum[j].filenum[k].file_permissio n

This can be done anywhere in the program. However, I can only get this to work with static arrays. When I try the dynamic implementation of it, it doesn't work. Could you possibly be more specific about arrays of pointers to structs? The struct pointing to a struct pointing to a struct works as long as you intialize it before compiling, however I don't know how to implement it dynamically. Like I said, in the struct's I changed
struct User usernum[10] to struct User* usernum
because you have to convert the array into a pointer if you want to allocate memory to it dynamically. However, I'm probably doing it wrong and I don't know what to do...
Dec 5 '06 #4
1,806 Top Contributor
declare, for example

Expand|Select|Wrap|Line Numbers
  1. struct User 
  2. {
  3.   char user_name[64];
  4.   int group_status;
  5.   struct *Directory directorynum[10];
  6. };
and repeat this for the rest of the structs
you can alloctate the memory for each struct as you create it and should be able to do something like this:

usernum[i]->directorynum[j]->filenum[k]->file_permissio n
Dec 6 '06 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Roman Hartmann | last post by:
hello, I do have a question regarding structs. I have a struct (profil) which has a pointer to another struct (point). The struct profil stores the coordinates of points. The problem is that I don't know how many points there will be in every struct in the end, so I have to allocate memory dynamically for them and can't use an array of fixed size, unfortunately. I would like to know if there is a better way to access struct members...
by: Geetesh | last post by:
Recently i saw a code in which there was a structer defination similar as bellow: struct foo { int dummy1; int dummy2; int last }; In application the above array is always allocated at runtime using malloc.In this last member of the structer "int last" is not
by: swarsa | last post by:
Hi All, I realize this is not a Palm OS development forum, however, even though my question is about a Palm C program I'm writing, I believe the topics are relevant here. This is because I believe the problem centers around my handling of strings, arrays, pointers and dynamic memory allocation. Here is the problem I'm trying to solve: I want to fill a list box with a list of Project Names from a database (in Palm this is more...
by: Steve Chow | last post by:
I have two structures; struct cordsys { int y, x, length }; struct provinces { int number; int type; struct cordsys cord;
by: nayannovellus | last post by:
As per my knowledge i know that when a structure is defined, no memory is assigned to its members but when a variable of that structure is declared memory is allocated and also this allocation takes place at runtime. Now my issue is that how is dynamic memory allocation different in case of structures(when variable of that structure is declared) and classes(where memory is allocated dynamically using new operator). whats the difference it both...
by: googlinggoogler | last post by:
Hi, Im new to C++ and trying to self teach myself whilst I sit at my unentertaining day job (thought i'd put that across before im accused of cheating on my homework, im 45...) Anyway I'm trying to dynamically assign a structure whilst I read from a file, however my program crashes, and im not sure why other than that its to do with my memory operations using new and delete.
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
by: ranjeetasharma81 | last post by:
Hi all, I have a big C-cod, in which there are lots of dynamic memory allocation used. I want to replace dynamic memroy allocation by static arrays. The following are the problems that i am facing: 1- From structure and dynamic memory allocation point of view, the code is very complicated. The code has various “nested structures” with a number of levels. The size of memory allocated for pointer to structure or its pointer...
by: Opteron64 | last post by:
Hi, I'm trying to create and initialise a dynamic array within a nested structure. The structure is defined as followed: (C++ code) typedef unsigned char uchar; typedef unsigned int uint; struct Results_list {
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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...
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...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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.