Hey,
So I'm trying to write this simple program in which I create a
struct that contains two string objects and an int. Through
typedef I create an instance of the
struct, initialize the 3 values, then print them. Following this, to better understand pointers I take the address of the values and assign it to a pointer to my
struct, change the values, and then print them.
Immediately below is the output I get using
cout <<, and it looks fine.
Hello
Goodbye
6
olleH
eybdooG
9
Press any key to continue . . .
|
I then tried, out of curiosity, to print it out using
printf(), and I keep getting this Run Time Error:
PRE-POINTER:
(null)
Press any key to continue . . .
|
Below is my code. If someone could just take a glance and help me see if there is anything blatantly wrong with the way I'm using
printf() or point out if the problem lies elsewhere, I would be greatly appreciative.
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
|
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
typedef struct Structure1
{
std::string str1;
std::string str2;
int int1;
} Structure1;
int main()
{
Structure1 testStruct1;
Structure1* testStruct2 = &testStruct1;
testStruct1.str1 = "Hello";
testStruct1.str2 = "Goodbye";
testStruct1.int1 = 6;
//cout << testStruct1.str1 << endl << testStruct1.str2 << endl << testStruct1.int1 << endl;
printf("PRE-POINTER:\n%s\n%s\n%d\n\n", testStruct1.str1, testStruct1.str2, testStruct1.int1);
testStruct2->str1 = "olleH";
testStruct2->str2 = "eybdooG";
testStruct2->int1 = 9;
//cout << testStruct2->str1 << endl << testStruct2->str2 << endl << testStruct2->int1 << endl;
printf("POST POINTER:\n%s\n%s\n%d\n", testStruct2->str1, testStruct2->str2, testStruct2->int1);
return 0;
}
|
Thanks to all in advance.