How to dynamically allocate an array of pointers to objects? - c++

I do not know the number of horse. I have already tried to do it, but I am getting errors and I don't know why. I am basically trying to create an array of pointers to objects. The class everything is in is called horse. Here is what I have. I am still getting errors from the c++ compiler.
horse::horse(string horse_Name, string rider_Name, int distance_Traveled, int max_Distance_Per_Second)
{
distance_Traveled = 0;
const int number_Of_Horses = 1;
horse **ptr = new horse*[number_Of_Horses];
*ptr[number_Of_Horses] =
{
horse(horse_Name, rider_Name, distance_Traveled, max_Distance_Per_Second)
};
max_Running_Distance_Per_Second(max_Distance_Per_Second);
}

distance_Traveled = 0;
Since distance_Traveled is not passed by reference, it will not change the original value. This may be one error.
horse **ptr = new horse*[number_Of_Horses];
This pointer is declared correctly; however, when you try to use iteration(or other expression, just my conjecture), you have to be careful,BECAUSE:
When it is a array, *ptr[number_Of_Horses] is illegal because an array start with 0, not 1. This is a common error. This may be a major issue.

Related

Size of int array C++

I'm trying to allocate a new array if integers (See HwGrades allocation below)
When I put the HwNum=2, the new function creates an array of size 1 only!
and when the for loop iterates 2 times it doesnt give me access violation
Help would be appreciated..
Here's the constructor
EE_Course::EE_Course(int Course_ID, char * Course_Name, int Hw_Num, double Hw_Weigh,int Factor_)
{
CourseID = Course_ID;
CourseName = new char[strlen(Course_Name) + 1];
strcpy(CourseName, Course_Name);
HwNum = Hw_Num;
HwWeigh = Hw_Weigh;
HwGrades = new int [HwNum]; // STARTING FROM HERE
for (int i = 0; i < Hw_Num; i++) { //UNTIL HERE
HwGrades[i] = 0;
}
Factor_ = 0;
ExamGrade = 0;
}
And those are the Course class private variables :
protected:
int CourseID;
int HwNum;
char* CourseName;
double HwWeigh;
int ExamGrade;
int* HwGrades;
};
The debugger does not show the whole array if it is a pointer. It shows the address of the array and the first element the array is pointing. So there is nothing wrong with your code.
You could see it if it was defined as an array:
int HwGrades[100];
If you really want to use a pointer and see it's content, you have two choices:
Define it as an array, debug it, fix/verify your code and turn back to pointer.
I don't know what is you environment, but usually there is a memory view option. You can check what's in the array any time you want. Just open the memory view of your IDE and watch the address of your pointer.
EDIT:
Apparently there is a third(and the best) option. See Rabbi Shuki's answer.
The debugger just shows one element. Here's why:
The type of HwGrades is int*. So when showing the contents of HwGrades what should the debugger do? The debugger does not know, that the pointer is actually pointing to the first element of an array. It assumes it just points to an int. Therefore, the debugger shows just the first element of the array that is actually of size 2.
If you're using the Visual Studio debugger, you can write HwGrades,2 in the watch window to see the first two elements of the array. Replace 2 by whatever your tickles your fancy. ;)
However, generally I would strongly advice to use the STL container std::vector for dynamic arrays. It will be easier to program and the debugger will be your friend without the hassle.
If you want to see the next cells of the array in the watch screen you can put the name and add a comma and the number of cells you want to see.
I.E.
HwGrades, 2

Dynamic memory allocation initialisation in C++ class

(I'm not posting my code as this is for a project, however I have tried to get help for this issue but have had no luck)
Hi there, I am trying to initialise the size of an array of pointers (char*) which is a private member variable of my class class A
I'm using the constructor to set the size by setting an integer variable (also a member variable) which will then be used to create my array of pointers.
I have done this so far:
// Constructor - 'int value' is set to a value
private:
int value;
char ** myArray = new char*[value];
So basically I want an array of pointers in which each element can point to a string. I am passing string variables to myArray by using (char*) stringVar.c_str();
Although all of this works, I am getting some pretty weird errors when trying to store variables and have even gotten this error:
free (): invalid next size (fast)
It's weird because even when myArray is of size 4, when I try to access, say, the 3rd element, I get the same error as above.
I am very new to C++ and am very intent on solving these issues. I've had to resort to this forum for help and am looking forward to some ideas from you guys :)
if you are new C++ programmer and want work with C++ String list is better work with std::vector<std::string> for complete tutorial of how using vectors see:
http://www.cplusplus.com/reference/vector/vector/
but in you question is String list size fixed?or not?
if string list is not fixed you must malloc space for array first time in constructor and then realloc array when you want insert a string in your string list for example:
class A{
private:
char** arrayy;
int arrayysize;
A(){
arrayy = (char**)calloc(1,sizeof(char*));
arrayysize = 1;
}
insertToarrayy(char* data){
strcpy(arrayy[arrayysize-1],data);
arrayy = (char**)realloc(arrayy,arrayysize+1);
arrayysize += 1;
}
}

Initialize obj then pass into a function <bad ptr>

I'm trying to initialize the values of an object, then pass it into a function, but visual studio tells me at this point that my two variables (question and answer) inside my object have "bad pointers" and cannot be evaluated. Unfortunately, I need to access both later on.
I've tried displaying question[i] and answer[i] right before calling enqueue() and it echoes correctly.
It's as if when I call the enqueue() function it doesn't remember what values I gave the card object when I called the constructor right before.
I'm not sure why my code breaks here, do I need to make a dynamic object?
card::card(char *q_input, char *a_input)
{
char * question = new char [75];
char * answer = new char [25];
strncpy(question,q_input,strlen(q_input)+1);
strncpy(answer,a_input,strlen(a_input)+1);
}
...
int queue::fill_deck(char **question, char **answer)
{
for(int i = 0; i < 9; i++)
{
card Card(question[i],answer[i]);
enqueue(Card); //ERROR!
}
return 0;
}
Thank you for the help!
Please let me know if you need more information.
EDIT: the problem was that I was redeclaring two variables with my constructor. A syntax mistake on my part!
One huge issue: This code does nothing except cause a memory leak:
card::card(char *q_input, char *a_input)
{
char * question = new char [75];
char * answer = new char [25];
strncpy(question,q_input,strlen(q_input)+1);
strncpy(answer,a_input,strlen(a_input)+1);
}
question and answer are local variables. Not only that, you then allocate memory and assign the returned pointer to these local variables. When that function exits, those locals go away, plus any chance of deallocating the memory you allocated goes away with it, causing a memory leak.
Before doing anything else, why are you using new[] instead of std::string? You tagged this as C++, but all of your coding is 'C'.

Pointer to int array, passing and using it from another method

I haven't cemented my learning of C++ arrays and have forgotten how to do this properly. I've done it with char array before but its not working as well for int array.
I declare a new blank int array:
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Then I assign a pointer to this array:
int *pMyArray = myIntArray
Hopefully thats correct to there.
Then I pass this to another method elsewhere:
anotherMethod(pMyArray)
where I want to assign this pointer to a local variable (this is where I'm really not sure):
anotherMethod(int *pMyArray){
int myLocalArray[];
myLocalArray[0] = *pMyArray;
}
I'm not getting any compilation errors but I'm not sure this is right on a few fronts. Any and all help and advice appreciated with this.
Edit:
I should have said what I am trying to do.
Very simple really, I'd just like to modify a local array from another method.
So I have:
Method 1 would contain:
int myArray1[10] = {0};
Method 2 would be passed the pointer to myArray:
Then some code to modify the variables in the array myArray.
int myIntArray[10];
This is an uninitialized array. It doesn't necessarily contain 0's.
int *pMyArray = myIntArray
Okay, pMyArray points to the first element in myIntArray.
anotherMethod(int *pMyArray){
int myLocalArray[10];
myLocalArray[0] = *pMyArray;
}
This doesn't assign your pointer to anything, it assigns the first value of the local array to the int pointed to by pMyArray, which, remember, was uninitialized. I added the 10 there because you can't have an array of unknown size in C++.
To modify what pMyArray points to, you need to pass it by reference:
anotherMethod(int *& pMyArray)
Also, if you assign it to some values in automatic storage, it will result in undefined behavior, as that memory is no longer valid when the function exits.
int myIntArray[10];
So this should be an array of nulls for the moment correct?
No, this is an array of 10 integers containing values depending on the storage specification.
If created locally, it has random garbage values.
If created globally it is value initialized which is zero initialized for POD.
Besides that your method just assigns the local array with the first vale of the array you pass.
What are you trying to do exactly? I am not sure.
int myIntArray[10];
So this should be an array of nulls for the moment correct?
Not correct, it is an array of 10 uninitialized ints.
int *pMyArray = myIntArray
Hopefully thats correct to there.
Not quite correct, pMyArray is a pointer to the 1st element, myIntArray[0].
where I want to assign this pointer to a local variable (this is where
I'm really not sure):
If you really need to assign the pointer, you have to use this code
int *p_myLocalArray;
p_myLocalArray = pMyArray;
There are a few mistakes here.
First, array of zeros (not nulls) is achieved by using the initializer syntax:
int myIntArray[10] = {0};
Second, int myLocalArray[]; has a size of 0. And even if it did have a size of, say, 10, writing myLocalArray[0] = *pMyArray; will assign the first int from pMyArray into mLocalArray, which is not what you meant.
If you want to assign a pointer of the array, then simply:
int *myLocalPointer;
myLocalPointer = pMyArray;
If you want a local copy of the array, you will need to copy it locally, and for that you also need the size and dynamic allocation:
void anotherMethod(int *pMyArray, int size){
int *myLocalArray = (int *)malloc(size * sizeof(int));
memcpy(myLocalArray, pMyArray, size * sizeof(int));
...
free(myLocalArray);
}

Pass character array by value and return a new character array from the function?

I apologise if I'm completely misunderstanding C++ at the moment, so my question might be quite simple to solve. I'm trying to pass a character array into a function by value, create a new array of the same size and fill it with certain elements, and return that array from the function. This is the code I have so far:
char *breedMutation(char genome []){
size_t genes = sizeof(genome);
char * mutation = new char[genes];
for (size_t a = 0 ;a < genes; a++) {
mutation[a] = 'b';
}
return mutation;
}
The for loop is what updates the new array; right now, it's just dummy code, but hopefully the idea of the function is clear. When I call this function in main, however, I get an error of initializer fails to determine size of ‘mutation’. This is the code I have in main:
int main()
{
char target [] = "Das weisse leid"; //dummy message
char mutation [] = breedMutation(target);
return 0;
}
I need to learn more about pointers and character arrays, which I realise, but I'm trying to learn by example as well.
EDIT: This code, which I'm trying to modify for character arrays, is the basis for breedMutation.
int *f(size_t s){
int *ret=new int[s];
for (size_t a=0;a<s;a++)
ret[a]=a;
return ret;
}
Your error is because you can't declare mutation as a char[] and assign it the value of the char* being returned by breedMutation. If you want to do that, mutation should be declared as a char* and then deleted once you're done with it to avoid memory leaks in a real application.
Your breedMutation function, apart from dynamically allocating an array and returning it, is nothing like f. f simply creates an array of size s and fills each index in the array incrementally starting at 0. breedMutation would just fill the array with 'b' if you didn't have a logic error.
That error is that sizeof(genome); will return the size of a char*, which is generally 4 or 8 bytes on a common machine. You'll need to pass the size in as f does since arrays are demoted to pointers when passed to a function. However, with that snippet I don't see why you'd need to pass a char genome[] at all.
Also, in C++ you're better off using a container such as an std::vector or even std::array as opposed to dynamically allocated arrays (ones where you use new to create them) so that you don't have to worry about freeing them or keeping track of their size. In this case, std::string would be a good idea since it looks like you're trying to work with strings.
If you explain what exactly you're trying to do it might help us tell you how to go about your problem.
The line:
size_t genes = sizeof(genome);
will return the sizeof(char*) and not the number of elements in the genome array. You will need to pass the number of elements to the breedMutation() function:
breedMutation(target, strlen(target));
or find some other way of providing that information to the function.
Hope that helps.
EDIT: assuming it is the number of the elements in genome that you actually want.
Array are very limited.
Prefer to use std::vector (or std::string)
std::string breedMutation(std::string const& genome)
{
std::string mutation;
return mutation;
}
int main()
{
std::string target = "Das weisse leid"; //dummy message
std::string mutation = breedMutation(target);
}
Try replacing the second line of main() with:
char* mutation = breedMutation(target);
Also, don't forget to delete your mutation variable at the end.