Hello, I've been trying to access the elements of an array of a struct type, and looking at other articles on this site I thought my syntax was correct. On line 31 I want to print out values from the array, but when I run the program I get the following error: "STATIC_ACCESS_VIOLATION". I'm just trying to figure out how to access member variables within array elements. Any suggestions?
My understanding is that you cannot return an array from a function in C++, and so you have to use a pointer in combination with a void function to assign values there. Correct me if this is wrong. On line 29 I am calling the makeFriends function, passing in the pointer to the array (or at least that was the intent). On line 51 I am declaring a new object of type person, and assigning it the the first element of an array. I copied the syntax from here: http://www.cplusplus.com/forum/beginner/56820/
Also, as a side note, functions can return arrays, since arrays are just pointers after all. Just don't declare the array as an array, rather as a new allocated pointer. Here is an example:
int* makeArray() {
int* arr = newint[6];
// allocate values
arr[0] = 1;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 5;
arr[5] = 8;
// return the array
return arr;
}
int main() {
int* arr;
arr = makeArray();
// do something
// still need to delete the array!
delete[] arr;
return 0;
}
As for how to pass an array to a function taking an array as a parameter (technically a pointer), just pass the name of the array: makeFriends(friends_ptr);
Just note that doing it this way means you are passing the pointer by value, so even though the memory the pointer is pointing to will change the pointer itself can't, so you can't reallocate or 'null' the pointer this way. If you want to do this with a function, you will need to pass the pointer by reference: void doSomething(int*& arr); // reference to a pointer