Skip to contentSkip to conversation

Returning pointer to array of structures

DISCUSSION Martin Buchan 4 participants 10 messages Apr 28, 2003 – May 1, 2003

lore
Share & tools
lore
#1 lore raw
In reply to Martin Buchan

Try the modifications above.

Quoted 12 lines

Hi,

I am trying to populate an array of structures with data read in from an xml file (using libxml2). I have a few methods which parse separate chunks of the xml file, populate the array, call the next method passing it whatever is in the array so far, and then returning the array back to the original caller.I am not getting any errors but the array is never populated when i return it to the calling function ( and most importantly main() ).

Here is my struct and some of my code.

Quoted 8 lines

struct menuentry

{
	char *appsection;
	char *appsubmenu;
};

typedef struct menuentry menuentry;

- menuentry parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)
+ void parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)

Quoted 7 lines
{
	xmlChar *uri;
	cur = cur->xmlChildrenNode;
	printf("I: %d. SECOND SECTION: %s\n", i,  mePtr[i].appsection);
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"submenu")))
Quoted 8 lines
			 {
				 uri = xmlGetProp(cur, "name");
				 xmlFree(uri);
				 mePtr[i].appsubmenu = uri;
				 printf("  SUBMENU: %s\n", mePtr[i].appsubmenu);
			 }
		  cur = cur->next;
	  }

- return *mePtr;

Quoted 2 lines

}

-menuentry parseSection (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr) +void parseSection (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr)

Quoted 4 lines
{
	int i=0;
	xmlChar *uri;
	cur = cur->xmlChildrenNode;
Quoted 8 lines
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"section")))
			 {
				   uri = xmlGetProp(cur, "name");
				   mePtr[i].appsection = uri;
				   xmlFree(uri);
				   printf("SECTION: %s\n", mePtr[i].appsection); /*prints out correct */

- *mePtr = parseSubmenu(doc, cur, mePtr, i);
+ parseSubmenu(doc, cur, mePtr, i);

Quoted 5 lines
				   printf("SECOND SUBMENU: %s\n", mePtr[i].appsubmenu); /* empty */
				   i++;
			 }
		  cur = cur->next;
	  }

- return *mePtr;

Quoted 2 lines

}

-menuentry parseDoc(char *docname, menuentry *mePtr) +void parseDoc(char *docname, menuentry *mePtr)

Quoted 7 lines
{
	xmlDocPtr doc;
	xmlNodePtr cur;
	doc = xmlParseFile(docname);
	
	/* snipped all error checking code */
Quoted 7 lines
	cur = xmlDocGetRootElement(doc);
	
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"root")))
			 {
				 printf ("happened once\n");

- *mePtr = parseSection (doc, cur, mePtr);
+ parseSection (doc, cur, mePtr);

Quoted 4 lines
			 }
		  cur = cur->next;
	  }
	xmlFreeDoc(doc);

- return *mePtr;

Quoted 5 lines

}

int main(int argc, char **argv)

{
	int n = countElements("menuconfig");

- menuentry *mePtr = malloc( n * sizeof (*mePtr) ); /* Gets size of array */
+ menuentry *mePtr = malloc( n * sizeof (struct menuentry) ); /* Gets size of array */

Quoted 1 line
	printf ("number of apps: %d\n", n);

- *mePtr = parseDoc("menuconfig", mePtr); /* calls method to populate me */
+ parseDoc("menuconfig", mePtr); /* calls method to populate me */

Quoted 12 lines
	printf("SECTION: %s\n", mePtr[0].appsection); /* Always empty */
	return EXIT_SUCCESS;
}

The printf statements in the methods print out the stuff i expect it to except for the one that prints out "SECOND SUBMENU:" and also the final printf statement in main() shows the array always being empty. This tells me i am not returning my pointer properly but i cant see what im doing wrong. Can anyone see what i am trying to do and/or where the error lies?

Quoted 10 lines

Thanks for any help.

Martin

-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

Rafael Costa dos Santos
ThinkFreak Comércio e Soluções em Hardware e Software Rio de Janeiro / RJ / Brazil [email protected]
+ 55 21 9432-9266

-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

#0 lore raw

Hi,

I am trying to populate an array of structures with data read in from an xml file (using libxml2). I have a few methods which parse separate chunks of the xml file, populate the array, call the next method passing it whatever is in the array so far, and then returning the array back to the original caller.I am not getting any errors but the array is never populated when i return it to the calling function ( and most importantly main() ).

Here is my struct and some of my code.

struct menuentry

{
	char *appsection;
	char *appsubmenu;
};

typedef struct menuentry menuentry;

menuentry parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)

{
	xmlChar *uri;
	cur = cur->xmlChildrenNode;
	printf("I: %d. SECOND SECTION: %s\n", i,  mePtr[i].appsection);
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"submenu")))
			 {
				 uri = xmlGetProp(cur, "name");
				 xmlFree(uri);
				 mePtr[i].appsubmenu = uri;
				 printf("  SUBMENU: %s\n", mePtr[i].appsubmenu);
			 }
		  cur = cur->next;
	  }
	return *mePtr;
}

menuentry parseSection (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr)

{
	int i=0;
	xmlChar *uri;
	cur = cur->xmlChildrenNode;
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"section")))
			 {
				   uri = xmlGetProp(cur, "name");
				   mePtr[i].appsection = uri;
				   xmlFree(uri);
				   printf("SECTION: %s\n", mePtr[i].appsection); /*prints out correct */
				   *mePtr = parseSubmenu(doc, cur, mePtr, i);
				   printf("SECOND SUBMENU: %s\n", mePtr[i].appsubmenu); /* empty */
				   i++;
			 }
		  cur = cur->next;
	  }
	return *mePtr;
}

menuentry parseDoc(char *docname, menuentry *mePtr)

{
	xmlDocPtr doc;
	xmlNodePtr cur;
	doc = xmlParseFile(docname);
	
	/* snipped all error checking code */
	
	cur = xmlDocGetRootElement(doc);
	
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"root")))
			 {
				 printf ("happened once\n");
				 *mePtr = parseSection (doc, cur, mePtr);
			 }
		  cur = cur->next;
	  }
	xmlFreeDoc(doc);
	return *mePtr;
}

int main(int argc, char **argv)

{
	int n = countElements("menuconfig");
	menuentry *mePtr = malloc( n * sizeof (*mePtr) ); /* Gets size of array */
	printf ("number of apps: %d\n", n);
	
	*mePtr = parseDoc("menuconfig", mePtr); /* calls method to populate me */
	printf("SECTION: %s\n", mePtr[0].appsection); /* Always empty */
	return EXIT_SUCCESS;
}

The printf statements in the methods print out the stuff i expect it to except for the one that prints out "SECOND SUBMENU:" and also the final printf statement in main() shows the array always being empty. This tells me i am not returning my pointer properly but i cant see what im doing wrong. Can anyone see what i am trying to do and/or where the error lies?

Thanks for any help.

Martin

#6 lore raw
Quoted 8 lines · Martin Buchan

I am trying to populate an array of structures with data read in from an xml file (using libxml2). I have a few methods which parse separate chunks of the xml file, populate the array, call the next method passing it whatever is in the array so far, and then returning the array back to the original caller.I am not getting any errors but the array is never populated when i return it to the calling function ( and most importantly main() ).

Quoted 8 lines

Here is my struct and some of my code.

The printf statements in the methods print out the stuff i expect it to except for the one that prints out "SECOND SUBMENU:" and also the final printf statement in main() shows the array always being empty. This tells me i am not returning my pointer properly but i cant see what im doing wrong. Can anyone see what i am trying to do and/or where the error lies?

You aren't returning a pointer, you're returning a structure. Moreover:

a) you always return the first element of the array (*mePtr is equivalent to mePtr[0]), and

b) you always store the returned structure in the first element of the array.

This isn't an error in itself, but the overall structure of the code means that you are effectively doing:

	mePtr[0] = mePtr[0];

repeatedly. As this is redundant, it seems likely that you meant to do something else.

I'm not familiar with libxml2, so I can't comment on that aspect of it. But that's probably irrelevant; your problem seems to be a fundamental misunderstanding about the nature of pointers and arrays.

Maybe you should try taking a small section of code, and explaining what you think it does.

OTOH, this is almost certainly an error:

	 uri = xmlGetProp(cur, "name");
	 xmlFree(uri);
	 mePtr[i].appsubmenu = uri;

Assuming that xmlFree() is a "destructor", you shouldn't be calling it until you have actually finished with "uri". Given that you are storing "uri" for later use, you probably either shouldn't be calling xmlFree() at all, or you should be copying the string itself (e.g. with strdup()), and not just the pointer.

Signature · 1 line
Glynn Clements <[email protected]>
#7 lore raw
Quoted 7 lines · Glynn Clements

OTOH, this is almost certainly an error:

	 uri = xmlGetProp(cur, "name");
	 xmlFree(uri);
	 mePtr[i].appsubmenu = uri;
Quoted 5 lines

Assuming that xmlFree() is a "destructor", you shouldn't be calling it until you have actually finished with "uri". Given that you are storing "uri" for later use, you probably either shouldn't be calling xmlFree() at all, or you should be copying the string itself (e.g. with strdup()), and not just the pointer.

Thanks! This was the error. I have used strdup() as you sugessted and now it all seems to be working. My structure is returned to main() successfully and i can print out each element using a for loop.

Thanks again for your help.

Martin

#8 lore raw
In reply to Martin Buchan
Quoted 30 lines · Martin Buchan

Hi,

I am trying to populate an array of structures with data read in from an xml file (using libxml2). I have a few methods which parse separate chunks of the xml file, populate the array, call the next method passing it whatever is in the array so far, and then returning the array back to the original caller.I am not getting any errors but the array is never populated when i return it to the calling function ( and most importantly main() ).

Here is my struct and some of my code.

struct menuentry

{
	char *appsection;
	char *appsubmenu;
};

typedef struct menuentry menuentry;

menuentry parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)

{
	xmlChar *uri;
	cur = cur->xmlChildrenNode;
	printf("I: %d. SECOND SECTION: %s\n", i,  mePtr[i].appsection);
	while (cur != NULL) 
	  {
		  if ((!xmlStrcmp(cur->name, (const xmlChar *)"submenu")))
			 {
				 uri = xmlGetProp(cur, "name");
Quoted 8 lines
				 xmlFree(uri);
				 mePtr[i].appsubmenu = uri;
				 printf("  SUBMENU: %s\n", mePtr[i].appsubmenu);
			 }
		  cur = cur->next;
	  }
	return *mePtr;
}

Hey, I am by no means an expert, but at my new job (1.5 months) I've just had a crash course in this for the project I'm on (C coding on linux). With that in mind, here is what I see:

1.) Your pointer *mePtr is being passed as an argument. It does not need to be returned. Your local function will modify the memory space that *mePtr points to.

2.) mePtr[i] doesn't make sense. It's equivalent to adding the size of struct menuentry to the address mePtr contains ( if i=1, eg). Not to mention that it was never declared as an array in the first place. I think you may be confusing char */array ([1] increments one byte) with pointers of different types.

3.) With malloc, it should probably be

menuentry *mePtr;
mePtr = malloc(n * sizeof(struct menuentry));
...
free(mePtr);
return...

4.) Consider this (without malloc/free)):

int main(yada yada) {
menuentry me[MAXENTRIES];

   n = countElements();

   for(i = 0; i < n; i++) {
      func_call(fnjsf, fdo, &me[i]);
   }

}
int func_call(int a, int b, menuentry *me) {

...

return 0; /*success*/
}

Like I said above, I haven't been doing this too long, so I may be wrong. I don't mean to sound harsh, but it look as though you could use a crash course in pointers, arrays, and malloc/free. Don't take it the wrong way, I just learned it the hard way a month ago myself.

HTH,

Cooper.

#9 lore raw
Quoted 1 line · Jason Cooper

1.) Your pointer *mePtr is being passed as an argument.

Just to be picky: "mePtr" is a pointer; "*mePtr" is what mePtr points to, i.e. a structure; it's equivalent to mePtr[0].

Quoted 3 lines

It does not
need to be returned. Your local function will modify the memory space that *mePtr points to.

This is correct.

Quoted 1 line

2.) mePtr[i] doesn't make sense.

Sure it does; it's the i-th element of the array to which mePtr points.

Quoted 2 lines

It's equivalent to adding the size of
struct menuentry to the address mePtr contains ( if i=1, eg).

Yes; this is just array access. BTW, the following are all equivalent:

	mePtr[i]
	*(mePtr + i)
	*(i + mePtr)
	i[mePtr]

However, using the last form isn't recommended if you want other people to understand your code.

Quoted 2 lines

Not to
mention that it was never declared as an array in the first place.

It was declared as:

menuentry *mePtr = malloc( n * sizeof (*mePtr) ); /* Gets size of array */

IOW, it points to an array of n menuentry structures.

In C, arrays are passed by reference; IOW, wherever you treat an array as a value, the value is actually the pointer to the first element. So, array accesses (array[index]) actually operate upon pointers rather than arrays.

The only place where an array is actually treated as an array (rather than a pointer) is when passed to sizeof.

Quoted 3 lines

I
think you may be confusing char */array ([1] increments one byte) with pointers of different types.

No; mePtr[i] is correct.

Quoted 7 lines

3.) With malloc, it should probably be

menuentry *mePtr;
mePtr = malloc(n * sizeof(struct menuentry));
...
free(mePtr);
return...

The argument to sizeof can be either a type or a value. As the type of "*mePtr" is "menuentry", and "menuentry" is just an alias (typedef) for "struct menuentry", all of the following are equivalent:

sizeof(*mePtr)
sizeof(menuentry)
sizeof(struct menuentry)

Quoted 4 lines

4.) Consider this (without malloc/free)):

int main(yada yada) {
   menuentry me[MAXENTRIES];

This requires that the number of entries is known at compile time. If the number of entries isn't known until run time, the memory has to be allocated dynamically, e.g. with malloc().

Quoted 3 lines

Like I said above, I haven't been doing this too long, so I may be wrong. I don't mean to sound harsh, but it look as though you could use a crash course in pointers, arrays, and malloc/free.

He isn't the only one ;)

Quoted 2 lines

Don't take it the
wrong way, I just learned it the hard way a month ago myself.

I've been doing C for ~15 years, so I think I have the pointer/array issues figured out by now. But I had been (intermittently) using assembly language for ~10 years before learning C, and that helps.

Signature · 1 line
Glynn Clements <[email protected]>
#2 lore raw
In reply to Rafael Santos

Hi,

Quoted 4 lines · Rafael Santos

Try the modifications above.

- menuentry parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)
+ void parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)

Thanks. Ive done as you suggested and it all works.

As the way i had coded it before where i was returning the structure each time worked, I am assuming this is a better way to code it (seeing as you guys have suggested it and i know diddly squat :-)

Why is this so?
Is it just because i do not have the extra overhead of passing/returning the structure for each function call or is there something more fundamental?

Excuse my ignorance but this is my first C program after hello world :-)

Thanks again.

Martin

#3 lore raw
Quoted 7 lines · Martin Buchan
Quoted 4 lines

Try the modifications above.

- menuentry parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)
+ void parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)

Thanks. Ive done as you suggested and it all works.

Quoted 8 lines

As the way i had coded it before where i was returning the structure each time worked, I am assuming this is a better way to code it (seeing as you guys have suggested it and i know diddly squat :-)

Why is this so?
Is it just because i do not have the extra overhead of passing/returning the structure for each function call or is there something more fundamental?

The main issue is that it's unnecessary in this case. That lead me (and probably others) to suspect that you might have misunderstood what was happening and/or meant to do something else.

E.g. parseSection() calls parseSubmenu(), passing mePtr as an argument. parseSubmenu() stores data in the elements of mePtr, and also returns the first element (*mePtr, equivalent to mePtr[0]) as a result. parseSection() then stores the result in *mePtr, even though the value it's storing is bound to be exactly what's already there.

In general, there are two ways to return values from a function:

1. Return the value as the function's result.

2. Pass in a pointer to where you want the value to be stored, and have the function store it there.

Option 2 is normally chosen if you want to return:

a) multiple values,
b) an array, or
c) large structures.

Option 1 is normally chosen if you only want to return a single, small value (usually a primitive type such as int, float etc).

Case a) is due to C functions only being able return a single value. Case b) is because arrays are always passed by reference (a pointer to the first element of the array). Case c) is for efficiency; returning a result typically involves the callee copying it onto the stack, then the caller copying it from the stack.

Signature · 1 line
Glynn Clements <[email protected]>
#4 lore raw

Excelente explanation.... Totally Agreed
Better than just fixing as I have done.

Great.

Quoted 42 lines · Glynn Clements
Quoted 7 lines · Martin Buchan
Quoted 4 lines

Try the modifications above.

- menuentry parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)
+ void parseSubmenu (xmlDocPtr doc, xmlNodePtr cur, menuentry *mePtr, int i)

Thanks. Ive done as you suggested and it all works.

Quoted 8 lines

As the way i had coded it before where i was returning the structure each time worked, I am assuming this is a better way to code it (seeing as you guys have suggested it and i know diddly squat :-)

Why is this so?
Is it just because i do not have the extra overhead of passing/returning the structure for each function call or is there something more fundamental?

The main issue is that it's unnecessary in this case. That lead me (and probably others) to suspect that you might have misunderstood what was happening and/or meant to do something else.

E.g. parseSection() calls parseSubmenu(), passing mePtr as an argument. parseSubmenu() stores data in the elements of mePtr, and also returns the first element (*mePtr, equivalent to mePtr[0]) as a result. parseSection() then stores the result in *mePtr, even though the value it's storing is bound to be exactly what's already there.

In general, there are two ways to return values from a function:

1. Return the value as the function's result.

2. Pass in a pointer to where you want the value to be stored, and have the function store it there.

Option 2 is normally chosen if you want to return:

a) multiple values,
b) an array, or
c) large structures.

Quoted 17 lines

Option 1 is normally chosen if you only want to return a single, small value (usually a primitive type such as int, float etc).

Case a) is due to C functions only being able return a single value. Case b) is because arrays are always passed by reference (a pointer to the first element of the array). Case c) is for efficiency; returning a result typically involves the callee copying it onto the stack, then the caller copying it from the stack.

Signature · 5 lines
Glynn Clements <[email protected]>
-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html

Rafael Costa dos Santos
ThinkFreak Comércio e Soluções em Hardware e Software Rio de Janeiro / RJ / Brazil [email protected]
+ 55 21 9432-9266

-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

#5 lore raw
In reply to Glynn Clements
Quoted 10 lines · Glynn Clements
Quoted 6 lines

As the way i had coded it before where i was returning the structure each time worked, I am assuming this is a better way to code it (seeing as you guys have suggested it and i know diddly squat :-)

Why is this so?

The main issue is that it's unnecessary in this case. That lead me (and probably others) to suspect that you might have misunderstood what was happening and/or meant to do something else.

Yep. :-)

I think i have a better understanding now though and am very grateful to the list for sorting me out, as i have also been thrown into C programming by my boss.

arrghh, bring back Perl!

Thanks again.

Martin