Hello, i'm working on data structures and linked lists, and for the most part i am understanding these concepts. My question is, what exactly is the best way to describe this line of code - numbers* nums = getNewNumbers(); in my program? what exactly is it doing? I apologize in advance if this is a stupid question, sometimes simple things can elude me and drive me nuts, like this.
#include <iostream>
usingnamespace std;
// structure with linked list
struct numbers
{
int x;
int y;
int z;
numbers *p_next_numbers;
};
numbers* getNewNumbers();
// getNewNumbers - gets new numbers from the linked list in the data structure that the pointer is pointing to
// @return numbers* - returns the fields in the linked list that the pointer is pointing to
void increment(numbers*);
// increment - function that will increment the fields with the giving numbers
// @param numbers* - pointer that points to the linked list that include the fields
int main()
{
numbers* nums = getNewNumbers();
// loop to show that the fields are being incremented by the giving
// value each time
for (int i = 0; i < 5; i++)
{
cout << nums->x << "\n";
cout << nums->y << "\n";
cout << nums->z << "\n";
cout << nums->p_next_numbers << "\n\n";
increment(nums);
}
cout << "\n\n";
system("PAUSE");
return 0;
}
numbers* getNewNumbers()
{
numbers* p_nums = new numbers;
p_nums->x = 1;
p_nums->y = 5;
p_nums->z = 10;
p_nums->p_next_numbers = NULL;
return p_nums;
}
void increment(numbers* p_nums)
{
p_nums->x++;
p_nums->y += 5;
p_nums->z += 10;
}
Line 52 declares a pointer p_nums, then allocates dynamic memory to hold one occurrence of the struct numbers and assigns the address of that memory to p_nums.
Line 54-57 initialize that structure.
Line 59 return the pointer to the dynamically allocated memory.
Line 27 declares a pointer to a struct of type numbers and initializes that pointer to the address return by getNewNumbers().
#include <iostream>
usingnamespace std;
// structure with linked list
struct numbers
{
numbers(int px, int py, int pz) {
x = px;
y = py;
z = pz;
p_next_numbers = NULL;
}
void increment() {
x++;
y += 5;
z += 10;
}
int x;
int y;
int z;
numbers *p_next_numbers;
};
int
main()
{
numbers *nums = new numbers(1,5,10);
// loop to show that the fields are being incremented by the giving
// value each time
for (int i = 0; i < 5; i++) {
cout << nums->x << "\n";
cout << nums->y << "\n";
cout << nums->z << "\n";
cout << nums->p_next_numbers << "\n\n";
nums->increment();
}
cout << "\n\n";
system("PAUSE");
return 0;
}