Strange pointer behaviour with chars - c++

I was playing around with structures and their pointers when I observed a strange behaviour. In the following code I made a structure containing: id, last_name_inital, full_name and first_name_inital. Looking at the memory addresses of the int and string works fine but looking at the chars gives broken output. I added to chars outside the structure which show the same behaviour. Looking at just a char output and it's pointer output gives the same char back so no address.
#include <iostream>
#include <string>
using namespace std;
struct entry
{
int id = 1;
char last_name_inital = 'S';
string full_name = "August Smith";
char first_name_inital = 'A';
};
int main()
{
entry aug;
entry *p_aug = &aug;
char alpha ='A';
char *p_alpha = α
char sirra ='S';
char *p_sirra = &sirra;
cout << "Printing structure address" << endl;
cout << p_aug << endl;
cout << "\n";
cout << "Printing id and it's address" << endl;
cout << p_aug->id << " " << aug.id << endl;
cout << &p_aug->id << " " << &aug.id << endl;
cout << "\n";
cout << "Printing last_name_inital and it's address" << endl;
cout << p_aug->last_name_inital <<" "<< aug.last_name_inital << endl;
cout <<&p_aug->last_name_inital<<" "<< &aug.last_name_inital << endl;
cout << "\n";
cout << "Printing full_name and it's address" << endl;
cout << p_aug->full_name << " " << aug.full_name << endl;
cout << &p_aug->full_name << " " << &aug.full_name << endl;
cout << "\n";
cout << "Printing first_name_inital and it's address" << endl;
cout << p_aug->first_name_inital <<" "<<aug.first_name_inital<< endl;
cout <<&p_aug->first_name_inital<<" "<<&aug.first_name_inital<< endl;
cout << "\n";
cout << "Printing alpha and it's address" << endl;
cout << *p_alpha << " " << alpha << endl;
cout << p_alpha << " " << &alpha << endl;
cout << "\n";
cout << "Printing sirra and it's address" << endl;
cout << *p_sirra << " " << sirra << endl;
cout << p_sirra << " " << &sirra << endl;
cout << "\n";
}
which gives the following output (compiled and written with geany, g++, linux):
Printing structure address
0x7fff01772360
Printing id and it's address
1 1
0x7fff01772360 0x7fff01772360
Printing full_name and it's address
S S
S S
Printing last_name_inital and it's address
August Smith August Smith
0x7fff01772368 0x7fff01772368
Printing last_name_inital and it's address
A A
A# A#
Printing alpha and it's address
A A
AS#w� AS#w�
Printing alpha and it's address
S S
S#w� S#w�
on every run the last output changes, so obviously something is changing.
An online search gave only this question, which sort of touches the same background but not really or I don't get it. character pointers in C++
Basically my main questions are what is happening there and is it possible to output a char pointer, so where it is stored?
Thank you
EDIT:
The quick responses solve the question of how to print out the pointer address of a char. By using:(void*)(&char_name)
However it leaves me wondering why the cout values of the normal chars change but the values of the chars inside the structure stay the same on rerun. Especially also because the behaviour for the char 'S' in the structure with cout is the mentioned operator-overloaded-just-give-back-the-char-itself but not for 'A' and also not for the normal chars outside the structure.
Can anyone explain those differences? Or even does this not occur for you?

You could cast the char * to a void *. The problem is, that the operator<< is overloaded to read char * as c_string.
cout << "Printing last_name_inital and it's address" << endl;
cout << p_aug->last_name_inital <<" "<< aug.last_name_inital << endl;
cout << (void*)(&p_aug->last_name_inital) <<" "<< (void*)(&aug.last_name_inital) << endl;
cout << "\n";

ostream& operator<< (ostream& os, const char* s); is to write sequence of char not address, cast to void* to get address.

Typically, addresses vary between program executions because the operating system happens to have different memory locations available or deliberately shuffles around data for security reasons.
Inspecting pointer values is only useful for comparing pointers in the same program instance: for example, p_aug and &aug have the same value.

Related

float vector and pointer returns different values even though they have same adress

I have a class which returns vector<vector<float>> with its getTemplates() function. My code is as follows for this case:
cout << "Get [0][0] " << s.getTemplates()[0][0] << endl;
cout << "vec addr " << &(s.getTemplates()[0][0]) << endl;
float *embFloat = s.getTemplates()[0].data();
cout << "embFloat: " << embFloat << endl;
cout << "*embFloat " << *embFloat << endl;
cout << "embFloat[0] " << embFloat[0] << endl;
and the output is as follows:
Get [0][0] 0.00191223
vec addr 0x555557973280
embFloat: 0x555557973280
*embFloat -8.71571e+33
embFloat[0] -8.71571e+33
I expect embFloat[0] and s.getTemplates()[0][0] to return exactly same value. What am I missing here?
s.getTemplates() returns a temporary which (in this particular instance) goes out of scope at the end of the statement that contains it.
float *embFloat is therefore a dangling pointer - i.e. it's pointing to an object that no longer exists.

Selecting an array value using a random number generator

its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.

Why does a char seem to take more space in an array than by itself

char testChar = 'a';
char myCharString[] = "asd";
char *pointerToFirstChar = &(myCharString[0]);
char *pointerToSecondChar = &(myCharString[1]);
cout << "A char takes " << sizeof(testChar) << " byte(s)";
cout << "Value was " << pointerToFirstChar << ", address: " << &pointerToFirstChar << endl;
cout << "Value 2 was " << pointerToSecondChar << ", address:" << &pointerToSecondChar << endl;
this outputs:
"A char takes 1 byte"
"... address: 00F3F718"
"... address: 00F3F70C",
I'm thinking the difference between addresses should be 1 byte, since that would be the size of the data separating them. Why is it not so?
&pointerToFirstChar and &pointerToSecondChar, you're not taking the address of the elements of the char array, but the address of the local variable pointerToFirstChar and pointerToSecondChar. Note they've been pointers themselves.
You might want:
cout << "Value was " << pointerToFirstChar << ", address: " << static_cast<void*>(pointerToFirstChar) << endl;
cout << "Value 2 was " << pointerToSecondChar << ", address:" << static_cast<void*>(pointerToSecondChar) << endl;
Note you need to cast them to void* to print out the address instead of the string.
You're looking at the addresses of the pointers pointerToFirstChar and pointerToSecondChar. They are pointers to char; compare their values and those will differ by 1. You seem to have edited that out in your text.
you are printing address of pointer variable and not the address currently pointer is holding.
for example:
&myCharString[0] = 0xFE20
&myCharString[1] = 0xFE21
&myCharString[2] = 0xFE23
char *pointerToFirstChar = &(myCharString[0]);
Address of pointerToFirstChar = 0xF8C2 and it holds the address &myCharString[0] = 0xFE20
so you are printing, 0xF8C2 rather than printing 0xFE20
Update your code as follows to get the correct result.
cout << "Value was " << pointerToFirstChar << ", address: " << (void *)&pointerToFirstChar[0] << endl;
cout << "Value 2 was " << pointerToSecondChar << ", address:" << (void *)&pointerToSecondChar[0] << endl;
For more information please follow the below link
print address of array of char

memory address prints aswell as string?

I'm trying to print out the contents of my array, however it also prints the memory address of each element, then prints the element.
void generateEndOfDayReport(taxiDetails taxiDataStore[], fareDetails reportArray[])
for (int i = 0; i < 14; i++)
{ cout << "Here is a list of the taxi drivers in ascending last name order: " <<
cout << taxiDataStore[i].taxiDriverSurname << endl << "And here is the money they took in over the course of today: £" << taxiDataStore[i].fareDetailsForTaxi.overAllFareDetails << endl << endl;
}![enter image description here][1]
By the look of your code, you've got a typo, it reads:
cout << some-text << cout << variable << endl << some-more-text << variable << endl << endl;
Note that you are streaming cout into cout. Is that really what you intended?

Program won't Print a string array C++

I have been working on this program for awhile, but it refuses to cooperate on this last little stretch. The point of the program is to sift a data file into three arrays, sort the arrays, then print them out into a table. The problem I'm having appears to be with the table. The program is divided into four functions, and when I attempt to debug, it won't show the productName array in the function.
The malfunctioning segment of code looks like this:
void printReport (string productName[], int numberinStock[], float price[], int number_of_products)
{
float totalPrice;
cout << setw(18) << " " << "Friendly Grocer Store Inventory" << setw(17) << " " << endl;
cout << setw(18) << "Inventory Item" << setw(16) << "Number in Stock" << setw(16) << "Unit Price" << setw(16) << "Total Sales" << endl;
for (int count=0; count <number_of_products-1; count++)
{
cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << setw(16) << std::setprecision(2) << price[count] << setw(16) << std::fixed << std::setprecision(2) << price[count]*numberinStock[count] << endl;
}
cout << "Total Price: " << totalPrice;
}
It will print everything else, but not the productName.
Some debugging statements outside of the for loop like cout << productName[1] will print out the proper productName but it's completely blank on the actual report.
After some debugging it seems like after printing the productName in the for loop every item after that overwrites the product name.
For example just leaving cout << setw(18) << productName[count] << setw(16) << numberinStock[count] << endl;
will produce
" 3s"
" 10h"
" 2a"
The product names there are Mangoes, Sandwich, and pizza.
I'm at a loss. Where did I mess up?
You might have screwed up passing the data into the function. If you set up test arrays in the function it should be printing correctly.
To pass arrays in C++ use the arrayname.
eg
int main ()
{
string productName[] = {"mango"};
...
printReport(productName, numofProduct);
return 0;
}