Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic allocation of struct 1

Status
Not open for further replies.

sedawk

Programmer
Feb 5, 2002
247
US
Hello,

This structure needs to be dynamic allocated. For instance,

Code:
#define NUM 10

struct node {
        char *NodeName;
        int index;
}

struct structname {
	struct node nodes[NUM];
	bool matrix[NUM][NUM];
	int nNodes;
};

In this example, MaxNodes has been defined before structname. Now, if want to made strucname dynamic allocation (because the number of structname may exceed NUM=10). The matrix[NUM][NUM] is the problem. This one shouldn't work

Code:
typedef structname *strucptr;

structptr DynaStruct;

DynaStruct = (strucptr *) malloc(1 * sizeof(structptr));
 
Why not simply replace the structures with pointers?

Code:
struct structname {

    struct *node nodes;
    bool   *matrix;
    int    nNodes;
};

Then you can "malloc" blocks of memory elsewhere and just point to them.


Trojan.
 
Code:
#include<stdio.h>
#include <stdlib.h>

typedef int bool;
struct node {
        char *NodeName;
        int index;
};
struct structname {
    struct node *nodes;
    bool **matrix;
    int nNodes;
};
typedef struct structname structname;

bool **makeBool ( int size ) {
  bool **rp = malloc( size * sizeof *rp );
  bool  *cp = malloc( size * size * sizeof *cp );
  int i;

  for ( i = 0 ; i < size ; i++ ) {
    rp[i] = cp;
    cp += size;
  }
  return rp;
}
structname *makeStruct ( int size ) {
  structname *result = malloc ( sizeof *result );
  if ( result ) {
    result->nodes = malloc ( size * sizeof *result->nodes );
    result->matrix= makeBool ( size );
  }
  return result;
}

int main ( void ) {
  structname *foo = makeStruct(10);
  int i, j;
  for ( i = 0 ; i < 10 ; i++ ) {
    foo->nodes[i].index = 0;
    for ( j = 0 ; j < 10 ; j++ ) {
      foo->matrix[i][j] = 0;
    }
  }
  free ( foo->matrix[0] );
  free ( foo->matrix );
  free ( foo->nodes );
  free ( foo );
  return 0;
}

--
 
excuse my intrusion

Code:
bool **makeBool ( int size ) {
  bool **rp = malloc( size * sizeof *rp );
  bool  *cp = malloc( size * size * sizeof *cp );
  int i;

  for ( i = 0 ; i < size ; i++ ) {
    rp[i] = cp;
    cp += size;
  }
  return rp;
}

in the for loop we are using pointer math to add
the next available memory space (size of) to the array.
there is not a check for the validity of this space
or of its availabilty or its usage status. would not
this be potentially dangerous as far as memory acces
and utilization.

this could be a solution or am I just showing one
of the areas I need to work on. I see a problem that
may not actually be there. I dont after all know
everything.

;-)
Code:
bool **makeBool ( int size ) {
  bool **rp = malloc( size * sizeof *rp );
  int i;

  for ( i = 0 ; i < size ; i++ ) {
    rp[i] = malloc( size * size * sizeof *cp );    
    }
  return rp;
}

one more display of ignorance here and Ill shut up.

what is this

Code:
  bool **rp = malloc( size * sizeof *rp );

I dont understand the reason for a declaration of a
bool type.

tomcruz.net
 
> there is not a check for the validity of this space
Look at how many elements were allocated to cp - namely size*size
Hence you can chop this up into size blocks for size iterations of the loop.
If the malloc actually succeeds, then there will be no problem stepping through the memory as described.

Imagine
Code:
char *buff = malloc(12);
rp[0] = &buff[0];
rp[1] = &buff[4];
rp[2] = &buff[8];

> rp = malloc( size * size * sizeof *cp );
You allocate way too much for each row here - you only need size * sizeof(bool)

If you had written
rp = malloc( size * sizeof *rp );
the end result would be the same as what I had written, except you've made size+1 calls to malloc, and I've made 2 calls to malloc.

If you print out each rp pointer, you'll see that with my method all the pointers are consecutive, with no gaps between them (it is after all one block of memory chopped up). With a malloc per row, each one could be allocated from very different memory addresses.
Not that it matters if you use the normal [row][col] access mechanism.

> I dont understand the reason for a declaration of a bool type.
Standard C doesn't have a bool type.
C99 gets a _Bool type, but C99 compilers aren't too common yet.

--
 
sorry

I did not see the typedef for the bool.

I still have trouble reading other programmers
style and code. thats why I spend so much time here.
despite what some may think, I am actually endeavoring
to improve my own code by reading yours. maybe I spend
to much time with builder.

thanks for your time :)

TC
 
I was tryin to use your code:

Code:
structname *makeStruct ( int size ) {
  structname *result = malloc ( sizeof *result );
  if ( result ) {
    result->nodes = malloc ( size * sizeof *result->nodes );
    result->matrix= makeBool ( size );
  }
  return result;
}

1) structname declaration has to be struct structname.
2) malloc(sizeof *result) dosn't work also, malloc(sizeof result) works, but result var is a pointer so you will just get size of the pointer but not the size of the object (structure) that pointer points to.

So, please how to make all this work. Or where am I missing my point?

I am C beginner and I need similar function InitList which will do malloc and reserve some space, and I need function which will do realloc once when I run out of space.. I don't know how to see sizeof structure from withing the function.
And one more thing... What is ** *(two stars) in front of variable.... can you explain that...

Thanks...
 
> 1) structname declaration has to be struct structname.
Didn't you see the typedef's?

> 2) malloc(sizeof *result) dosn't work also, malloc(sizeof result) works
Wrong twice - you want the size of what it points to, not the size of the pointer itself.
Also, when you say 'doesn't work', is that based on your beginner understanding of how sizeof works, or from some actual error messages from trying to compile some code?

> And one more thing... What is ** *(two stars) in front of variable.... can you explain that...
It's a pointer to a pointer.

int *a = malloc ( 10 * sizeof *a ); // 10 ints
int **a = malloc ( 10 * sizeof *a ); // 10 pointers to int

With the 2nd one, you can then go on to
a[0] = malloc ( 100 * sizeof *a[0] );// a[0][0] to a[0][99] are int's

Try here

--
 
Thanks for info....

As you noticed I am pretty much beginner c world....

I am trying to create dynamic list of strings with all functionalities that dynamic links should have.
I want to extend list if I need (by 5) and I want to be able to extend char array (string) if I need. For example I would start with string of size 5 characters and I would increase by 5 every time I need.

I was using above example (yours) ... to learn and to possibly finish my project.... I am stuck now...

Code:
struct structname {
    int elemsnumber;    //elements number
    int listsize;       //size of the list
    char **mystring;
};

I would do malloc the same whay you did above.

Code:
char **makeChar ( int size ) {
  char **rp = malloc( size * sizeof *rp );
  char  *cp = malloc( size * size * sizeof *cp );
  int i;
  for ( i = 0 ; i < size ; i++ ) {
    rp[i] = cp;
    cp += size;
  }
  return rp;
}
struct list  *makeStruct ( int size ) {
  struct list *result = malloc ( sizeof *result );
  if ( result ) {
    result->mystring = makeChar ( size );
  }
  return result;
}

The problem is when I finally initialize my struct list

Code:
struct list *lp = makeStruct(5);

I can't do anything with this pointer after.
I mean I can assign value like this
lp->mystring[0] = "somestring";, but I can't do anything dynamically. For example, I am reading lines from some text files and I would like to put them into list.
How to do that.
I would do:

Code:
for (n=0; n < 3; n++) {
    fget(myline, 1024, filein);
    lp->mystring[n] = myline;
}

But problem here is I am copying just pointers, not content.
I do it the way above I get all mystring pointers pointing to last value of myline. How I move content of myline to the adress where mystring[n] is pointing to????

Whatever else I do I would trigger segmential error.
Thanks....
 
Use strcpy() to copy a string.

However, I'd guess that your makeChar isn't really doing what you want. Salem's version (makeBool) was OK, because a bool is of fixed size. The makeChar version has single characters that are obviously the same size (1 byte), but try to store line of text from a file into the array, and you're now looking at variable lengths. You need to rethink how that is going to work before you overflow the buffer.
 
I think I am going off the subject of this thread.
I'll start new one thread205-1137638.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top