dimanche 1 mars 2015

Exercise on structures with functions


I am currently working on an assignment for practice with structures. I have created a structure and have a few different datatypes inside and I need to pass these structures into a function that modifies the members.


What I have to work with is a few templates given to me:



struct1* func1();


In func1 I am simply modifying members and returning the address of struct1. I think I have done this correctly, because when I am in main() during debugging I can see the values very clearly.


I created a structure of type struct1called struct1aand then returned &struct1a. This seemed to work just fine. Please tell me if this is not right. I am still learning how to debug in VS 2013.


The next portion of the assignment is where I am really struggling. What I essentially have to do is iterate through struct1a and another structure struct2a. struct2a is actually a new'd array inside struct1a. All of this is done in two different functions func2 and func3.


The purpose of func2 is to check to make sure that struct1a was initialized correctly and then fucn2 starts the iterations through the array inside struct1a. Here is a snippet:



struct1 *struct1a;
struct1a = fucn1();


struct2 *struct2a;
for (struct2a = func2(&struct1a); struct2a != nullptr; struct2a = func2(&struct1a))
{
cout << struct2a;
}


I simply want to print the address after each iteration to check if it is working. I can add more code to print the contents later.


I am getting an access violation error probably due to func2 not operating correctly and I think it's because my syntax isn't right. I am still learning the concepts of pointers, so here is a sample of my func3:



struct2* func3(struct1 **struct1a)
{
if ((**struct1a).loc == NOT_GOOD_VALUE)
return nullptr;
else
(**struct1a).loc =+ 1;

if ((**struct1a).loc < (**struct1a).numitems)
return &((**struct1a).items[(**struct1a).loc]);
else if ((**struct1a).loc >= (**struct1a).numitems)
return nullptr;
}


When I set some watches in debugging on these values being read, VS is reading them as uninitialized (some very small negative number). Particularly (**struct1a).numitems) but when in main, just before the function call, that value is definitely initialized to the correct value I want. If somebody could look at this and tell me why this function is not reading the values from the structures correctly I would be very happy. If indeed it is what I suspect and my understanding of pointers is really unsatisfactory, please point me (no pun intended) somewhere I can hopefully study this a little better.




Aucun commentaire:

Enregistrer un commentaire