ch3-typedef int* in C/C++
Chapter_3 Exercise_3-12 | SimpleStruct1 Exercise_3-13 |
typedef TCP1, p. 189 (typedef.c, Typedef.cpp)
typedef.c download
#include <stdio.h> // for printf()
typedef int* IntPtr;
int main()
{
int* a = 0, b = 0; // a is a null pointer, b is an integer with value 0
a++, b++; // a points to address 4 (sizeof int), b == 1
printf("a = %p, b = %p\n", a, b); // warning: b is not pointer
printf("a = %d, b = %d\n", a, b); // warning: a is not integer
IntPtr x = 0, y = 0; // null pointers
printf("x = %p, y = %p\n", x, y); // nil
x = y = a = &b; // now they point to something
*x = 0; // b = 0
printf("a = %p, &b = %p, x = %p, y = %p\n", a, &b, x, y);
printf("*a = %d, b = %d, *x = %d, *y = %d\n", *a, b, *x, *y);
return 0;
}
/*
gcc typedef.c -o typedef
./typedef
a = 0x4, b = 0x1
a = 4, b = 1
x = (nil), y = (nil)
a = 0x7ffdc61ccddc, &b = 0x7ffdc61ccddc, x = 0x7ffdc61ccddc, y = 0x7ffdc61ccddc
*a = 0, b = 0, *x = 0, *y = 0
*/
Typedef.cpp download
#include <iostream>
using std::cout;
using std::endl;
typedef int* IntPtr;
int main()
{
int* a = 0, b = 0; // a is a null pointer, b is an integer with value 0
a++, b++; // a points to address 4 (sizeof int), b == 1
cout << "a = " << a << ", b = " << b << endl;
IntPtr x = nullptr, y = nullptr; // null pointers
cout << "x = " << x << ", y = " << y << endl; // 0
x = y = a = &b; // now they point to something
*x = 0; // b = 0
cout << "a = " << a << ", &b = " << &b
<< ", x = " << x << ", y = " << y << endl;
cout << "*a = " << *a << ", b = " << b
<< ", *x = " << *x << ", *y = " << *y << endl;
return 0;
}
/*
g++ Typedef.cpp -o Typedef
./Typedef
a = 0x4, b = 1
x = 0, y = 0
a = 0x7ffef1be638c, &b = 0x7ffef1be638c, x = 0x7ffef1be638c, y = 0x7ffef1be638c
*a = 0, b = 0, *x = 0, *y = 0
*/
Chapter_3 Exercise_3-12 | BACK_TO_TOP | SimpleStruct1 Exercise_3-13 |
Comments
Post a Comment