Size of int array C++ - 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

Related

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;
}
}

Can I debug a pointer as array?

For example,
I wanna watch pA
int *pA = new int[LEN];
Then in visual studio, I can see only pA[0] in watch-window
I try to view '(int (*)[LEN])pA', but it does not work
I don't want to make
int (*test)[LEN] = (int (*)[LEN])pA
to debug
How can I see dynamic allocated pointer as a static array in debugger of VS2010?
You can write pA,10 (or how many elements you want to see) in the watch window.
In the Quick Watch:
First know the value of LEN. Say, it is 100.
Then, type pA,100 to see all the 100 elements.

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.

how to represent int * as array in totalview?

How do I 'dive' an int * which points to a dynamically allocated array of integers and represent it as a fixed int[] array? Put otherwise, if I dive an int * it shows the address and the int pointed to, but instead I would like to see the array of all of the integers.
I noticed the TotalView tag on this question. Are you asking how to see the values in your array in totalview? If so then the answer is pretty easy.
Lets say you have a pointer p which is of type int * and you have it currently pointing towards an array with 10 integers.
Step 1. Dive on the pointer. That's accomplished by double clicking, clicking the middle mouse button, or using the dive option on the context menu -- all after having placed the mouse cursor on the variable int he source code pane or the stack frame pane.
This will bring up a new window that will say
Expression: p
Address: 0xbfaa1234
Type: int *
and down in the data area will say something like
0x08059199 -> 0x000001a5 (412)
This window is showing you the pointer itself, the address listed is the address of the pointer. The value (0x08059199 in the example above) is the actual value that the pointer has. Everything to the right of the arrow is just a "hint" telling you want it points to.
Step 2. Dive on the pointer again. Repeat the double click or middle mouse button, this time on the data value in the variable window. (So you are double clicking where it says 0x08059199).
This will effectively "dereference" the pointer. Now the window is focused not on pointer itself but the thing that the pointer pointed to. Notice that the address box now contains 0x08059199 which was the value before.
expression: *(((int *) p))
Address: 0x08059199
Type: int
and down in the data area it will say something like
0x000001a5 (412)
Step 3. Cast the data window to the type you want. Just click in the type field and change it to say int[10]. Then hit return.
This tells the debugger that 0x08059199 is the beginning of an array of 10 integers.
The window will grow two new fields: Slice and Filter. You can leave those alone for now, but they can be useful later.
The data area will now show two columns "field" and "value" and 10 rows.
The field column will be the index in the array [0] - [9] and the value column will tell you what data you have in each array location.
Other tips:
In more complicated data structures you can may want to dive on individual elements (which might also be pointers, diving will dereference them as well)
You can always cast to different types or lengths to look at data "as if it was" whatever
You can edit the actual data values by clicking on the value column and editing what you find there. This is useful when you want to provoke specific mis-behavior from your application
You can always undo diving operations with the "<" icon in the upper right hand corner of the variable window.
There are some online videos that you might find helpful at
http://www.roguewave.com/products/totalview/resources/videos.aspx
in particular there is one labeled "getting started with TotalView".
Don't hesitate to contact us at Rogue Wave Software for TotalView usage tips!
support at roguewave dot com is a good address for that.
Chris Gottbrath
(Chris dot Gottbrath at roguewave dot com)
TotalView Product Manager at Rogue Wave Software
It's not very hard, but i forgot how it exactly works. I found you a page which explains it tho ;). I think to point and array with ints called for example test you should get it using &test.
Just check this page out:
http://www.cplusplus.com/doc/tutorial/pointers/
You can't meaningfully do this without knowing exactly how many ints are in the array.
If you have an int *p that points to the first element in a contiguous int data, either dynamically allocated, or a static array, you can index it as if it were an array:
int *data = malloc(3 * sizeof *data);
int *p;
/* malloc error detection omitted for brevity */
data[0] = 1;
data[1] = 2;
data[3] = 42;
p = data;
assert(p[0] == 1);
assert(p[1] == 2);
assert(p[2] == 42);
You have to know the size of the valid data you are accessing this way.
So, let's say I have data as above, and want to write a function to print it. It won't do to declare the function like this:
void print_array(int *data);
because when you call print_array(data);, the function doesn't know the number of elements to print.
You could define your print_array() like:
void print_array(int *data, size_t n);
where n denotes the number of valid elements pointed to by data, that the caller has to supply. Or you could decide that every "array" will end with a sentinel value, a value that is used only at the end of the data, and is not useful value otherwise:
data[2] = 0; /* data[0] and data[1] are useful, valid values
and data[2] is 0 to signify the end of the data */
Then you can declare your print_array() as:
void print_array(int *data);
and keep indexing into data in the function definition till you hit a sentinel:
void print_array(int *data)
{
size_t i;
for (i=0; data[i] != 0; ++i)
printf("%d\n", data[i]);
}
So, to answer your question, you can already treat a pointer to a valid dynamically allocated data as an array. You have to remember the size of the allocated data of course, which you would need to do in a regular array too.