Generic Pointers: Void : A "Pointer To Anything"
Generic Pointers: Void : A "Pointer To Anything"
void
set_x_and_y(int *x, int *y)
{
*x = 1001;
*y = 1002; a 1001
1
}
b 1002
2
void
f(void)
{ x
int a = 1;
int b = 2; y
set_x_and_y(&a, &b);
}
int
foo(int array[],
unsigned int size)
{
… What does this print? 8
printf(“%d\n”, sizeof(array));
... because array is really
}
a pointer
int
main(void)
{
int a[10], b[5];
… foo(a, 10)… foo(b, 5) … What does this print? 40
printf(“%d\n”, sizeof(a));
}
C, … He l lo , w o r l d !\n terminator
C terminator: ’\0’
“3”
0x1020 argv[4]
“2” These are strings!!
0x1018 argv[3] Not integers!
0x1010 argv[2] “1”
0x1008 argv[1] “hello”
0x1000 argv[0]
“./program”
Alan L. Cox
[email protected]
Objectives
date.month = 1;
date.day = 18;
date.year = 2018;
foo.c1 = ’a’;
foo.c2 = ’b’;
foo.i = 0xDEADBEEF;
c1 c2 padding i
61 62 EF BE AD DE
x86 uses “little-endian” representation
int64_t i = 100000000000;
Date d = { 1, 18, 2018 };
#define SIZE 10
Define once,
int array[10]; int array[SIZE]; use throughout
the program
Date birthdays[NFRIENDS];
bool
check_birthday(Date today)
{
int i; Array index, then
structure field
for (i = 0; i < NFRIENDS; i++) {
if ((today.month == birthdays[i].month) &&
(today.day == birthdays[i].day))
return (true);
return (false);
}
Date void
create_date1(int month, create_date2(Date *d,
int day, int month,
int year) Pass-by-reference int day,
{ int year)
Date d; {
d->month = month;
d.month = month; d->day = day;
d.day = day; d->year = year;
d.year = year; }
return (d);
Date today;
}
Date *
create_date3(int month,
int day,
int year)
{
What is d pointing to?!?!
Date *d;
(more on this later)
d->month = month;
d->day = day;
d->year = year;
return (d);
}
struct widget;
#include “widget.h”
struct widget {
int x;
…
};
Bit-wise operations:
Bit-wise AND: 00100101 & 10111100 == 00100100
Bit-wise OR: 00100101 | 10111100 == 10111101
Bit-wise NOT: ~ 00100101 == 11011010
Bit-wise XOR: 00100101 ^ 10111100 == 10011001
Selecting bits:
important_bits = bit_vec & low_three_bits_mask;
Result = ?
0…00 0101 == 0…01 0101 & 0…00 0111
Setting bits:
bit_vec |= low_three_bits_mask;
Result = ?
Clearing bits:
bit_vec &= ~low_three_bits_mask;
Result = ?
Padded to be an integral
number of words f1 f2 f3
Placement is compiler- 1 1 0 1 1 0 … …
specific.
c padding
EF BE AD DE
i
?
union AnElt {
int i;
char c;
How should your program keep track
} elt1, elt2;
whether elt1, elt2 hold an int or
elt1.i = 4;
a char?
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
?
Basic answer: Another variable holds
if (elt1 currently has a char) … that info
Memory Allocation