Arrays and Pointers in C Programming

undefined
 
Arrays and Pointers in C
 
 
Alan L. Cox
alc@rice.edu
 
Objectives
 
Be able to use arrays, pointers, and strings in
C programs
 
Be able to explain the representation of these
data types at the machine level, including
their similarities and differences
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
2
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
3
Arrays in C
No bounds checking!
Allowed – usually causes no 
obvious
 error
  array[10] may overwrite b
Unlike Java, array size in definition
int array[10];
int b;
array[0]   = 3;
array[9]   = 4;
array[10]  = 5;
array[-1]  = 6;
All elements of same type – homogenous
First element (index 0)
Last element (index size - 1)
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
4
 
Array Representation
 
Homogeneous 
 Each element same size – s bytes
An array of m data values is a sequence of m
s bytes
Indexing: 0
th
 value at byte s
0, 
1
st
 value at byte s
1, …
 
m and s are 
not
 part of representation
Unlike in some other languages
s known by compiler – usually irrelevant to programmer
m often known by compiler – if not, must be saved by
programmer
int a[3];
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
5
 
Array Representation
char    c1;
int     a[3];
char    c2;
int     i;
 
Could be optimized by
making these adjacent,
and reducing padding
(by default, not)
 
Array aligned by
size of elements
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
6
Array Sizes
What is
sizeof(array[3])
?
sizeof(array)
?
int  array[10];
4
40
returns the size of 
an object in bytes
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
7
 
Multi-Dimensional Arrays
int  matrix[2][3];
 
matrix[1][0] = 17;
 
Recall: no bounds checking
 
What happens when you write:
 
  matrix[0][3] = 42;
 
R
o
w
 
M
a
j
o
r
O
r
g
a
n
i
z
a
t
i
o
n
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
8
 
Variable-Length Arrays
int
function(int n)
{
    int  array[n];
 
New C99 feature: Variable-length arrays
defined within functions
 
Global arrays must still have fixed (constant) length
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
9
 
Memory Addresses
 
Storage cells are typically viewed as being
byte-sized
Usually the smallest addressable unit of memory
Few machines can directly address bits individually
Such addresses are sometimes called 
byte-
addresses
Memory is often accessed as words
Usually a word is the largest unit of memory access
by a single machine instruction
CLEAR
s word size is 8 bytes (= 
sizeof(long)
)
A 
word-address
 is simply the byte-address of the
word
s first byte
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
10
10
 
Pointers
 
 
Special case of bounded-size natural numbers
Maximum memory limited by processor word-size
2
32
 bytes = 4GB, 2
64
 bytes = 16 exabytes
 
A pointer is just another kind of value
A basic type in C
int *ptr;
 
The variable 
ptr
 stores a pointer to an 
int
.
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
11
11
 
Pointer Operations in C
 
Creation
&
 
variable
  
Returns variable
s memory address
Dereference
*
 
pointer
  
Returns contents stored at address
Indirect assignment
*
 
pointer
 
=
 
val
 
Stores value at address
 
Of course, still have...
 
Assignment
pointer
 
=
 
ptr
 
Stores pointer in another variable
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
12
12
Using Pointers
int  i1;
int  i2;
int *ptr1;
int *ptr2;
 
i1 = 1;
i2 = 2;
 
ptr1 = &i1;
ptr2 = ptr1;
 
*ptr1 = 3;
i2 = *ptr2;
1
2
0x1000
0x1000
3
3
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
13
13
Using Pointers (cont.)
Type check warning:  
int_ptr2
 is not an 
int
int1
 becomes 8
int  int1     = 1036;   /* some data to point to  */
int  int2     = 8;
int *int_ptr1 = &int1;  /* get addresses of data  */
int *int_ptr2 = &int2;
*int_ptr1 = int_ptr2;
*int_ptr1 = int2;
What happens?
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
14
14
Using Pointers (cont.)
Type check warning:  
*int_ptr2
 is not an 
int *
Changes 
int_ptr1
 – doesn
t change 
int1
int  int1     = 1036;   /* some data to point to  */
int  int2     = 8;
int *int_ptr1 = &int1;  /* get addresses of data  */
int *int_ptr2 = &int2;
int_ptr1 = *int_ptr2;
int_ptr1 = int_ptr2;
What happens?
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
15
15
Pointer Arithmetic
pointer
 + 
number
  
pointer
number
E.g., 
pointer
 
+ 1
 
   adds 1 
something
 to a pointer
In each, p now points to b
(Assuming compiler doesn
t
reorder variables in memory)
Adds 1*sizeof(char) to
the memory address
Adds 1*sizeof(int) to
the memory address
Pointer arithmetic should be used 
cautiously
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
16
16
 
A Special Pointer in C
 
 
Special constant pointer 
NULL
Points to no data
Dereferencing illegal – causes 
segmentation fault
 
To define, include 
<stdlib.h>
 or 
<stdio.h>
 
C23 introduces 
nullptr
 as a better alternative
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
17
17
Generic Pointers
void *: a 
pointer to anything
Lose all information about what type of thing
is pointed to
 Reduces effectiveness of compiler
s type-checking
 Can
t use pointer arithmetic
void   *p;
int     i;
char    c;
p = &i;
p = &c;
putchar(*(char *)p);
type cast: tells the compiler to
change
 an object
s type (for type
checking purposes – does not modify
the object in any way)
Dangerous!  Sometimes necessary…
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
18
18
Pass-by-Reference
void
set_x_and_y(int *x, int *y)
{
   *x = 1001;
   *y = 1002;
}
void
f(void)
{
   int a = 1;
   int b = 2;
   set_x_and_y(&a, &b);
} 
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
19
19
Arrays and Pointers
Dirty 
secret
:
Array name 
 a 
pointer to the
initial (0th) array element
a[i]  
  *(a + i)
An array is passed to a function
as a pointer
The array size is lost!
Usually bad style to interchange
arrays and pointers
Avoid pointer arithmetic!
Really 
int *array
int 
foo(int array[],
    unsigned int size)
{
   … array[size - 1] …
}
int
main(void)
{
   int a[10], b[5];
   … foo(a, 10)… foo(b, 5) …
}
Must explicitly
pass the size
Passing arrays:
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
20
20
Arrays and Pointers
int
foo(int array[],
    unsigned int size)
{
   printf(
%d\n
, sizeof(array));
}
int
main(void)
{
   int a[10], b[5];
   … foo(a, 10)… foo(b, 5) …
   printf(
%d\n
, sizeof(a));
}
What does this print?
What does this print?
8
4
0
... because 
array
 is really
a pointer
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
21
21
Arrays and Pointers
int  i;
int  array[10];
for (i = 0; i < 10; i++) {
  array[i] = …;
}
int *p;
int  array[10];
for (p = array; p < &array[10]; p++) {
  *p = …;
}
These two blocks of code are functionally equivalent
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
22
22
 
Strings
 
In C, a string is just an array of characters
Terminated with 
\0
 character
Arrays for bounded-length strings
Pointer for constant strings (or unknown length)
char  str1[15] = 
Hello, world!\n
;
char *str2     = 
Hello, world!\n
;
H
e
l
l
o
,
w
l
o
r
d
!
\n
length
H
e
l
l
o
,
w
l
o
r
d
!
\n
terminator
 
Java, …
 
C, …
 
C terminator:
 
\0
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
23
23
String length
Must calculate length:
Provided by standard C library: 
#include <string.h>
int
strlen(char str[])
{
  int len = 0;
  while (str[len] != 
\0
)
    len++;
  return (len);
}    
can pass an
array or pointer
Check for 
terminator
array access
to pointer!
What is the size
of the array???
Pointer to Pointer (char **argv)
C
o
x
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
24
24
Passing arguments to main:
int
main(int argc, char **argv)
{
  ...
}    
Suppose you run the program this way
UNIX% ./program hello 1 2 3
argc == 5 
(five strings on the
                   command line
) 
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
25
25
 
char **argv
argv[0]
argv[1]
argv[2]
 
0x1000
 
0x1008
 
0x1010
argv[3]
argv[4]
 
0x1018
 
0x1020
 
./program
 
hello
 
1
 
2
 
3
 
These are strings!!
Not integers!
 
C
o
x
 
A
r
r
a
y
s
 
a
n
d
 
P
o
i
n
t
e
r
s
 
26
26
 
Next Time
 
Structures and Unions
Slide Note
Embed
Share

Explore the fundamentals of arrays, pointers, and strings in C programs, along with their representation at the machine level. Learn the similarities and differences between these data types and how to effectively use them in C programming. Dive into array indexing, representation, sizes, multi-dimensional arrays, and more with practical examples and insights.

  • C programming
  • Arrays
  • Pointers
  • Strings
  • Machine level

Uploaded on Oct 04, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Arrays and Pointers in C Alan L. Cox alc@rice.edu

  2. Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including their similarities and differences Cox Arrays and Pointers 2

  3. Arrays in C All elements of same type homogenous Unlike Java, array size in definition int array[10]; int b; Compare: C: Java: int array[10]; int[] array = new int[10]; First element (index 0) Last element (index size - 1) array[0] = 3; array[9] = 4; array[10] = 5; array[-1] = 6; No bounds checking! Allowed usually causes no obvious error array[10] may overwrite b Cox Arrays and Pointers 3

  4. Array Representation Homogeneous An array of m data values is a sequence of m s bytes Indexing: 0th value at byte s 0, 1st value at byte s 1, Each element same size s bytes m and s are not part of representation Unlike in some other languages s known by compiler usually irrelevant to programmer m often known by compiler if not, must be saved by programmer a[2] 0x1008 int a[3]; a[1] 0x1004 a[0] 0x1000 Cox Arrays and Pointers 4

  5. Array Representation char c1; int a[3]; char c2; int i; i 0x1014 c2 0x1010 a[2] 0x100C Could be optimized by making these adjacent, and reducing padding (by default, not) a[1] 0x1008 a[0] 0x1004 c1 0x1000 Array aligned by size of elements Cox Arrays and Pointers 5

  6. Array Sizes int array[10]; What is sizeof(array[3])? 4 returns the size of an object in bytes sizeof(array)? 40 Cox Arrays and Pointers 6

  7. Multi-Dimensional Arrays matrix[1][2] 0x1014 matrix[1][1] 0x1010 int matrix[2][3]; matrix[1][0] 0x100C matrix[0][2] 0x1008 matrix[1][0] = 17; matrix[0][1] 0x1004 matrix[0][0] 0x1000 Recall: no bounds checking Row Major Organization What happens when you write: matrix[0][3] = 42; Cox Arrays and Pointers 7

  8. Variable-Length Arrays int function(int n) { int array[n]; New C99 feature: Variable-length arrays defined within functions Global arrays must still have fixed (constant) length Cox Arrays and Pointers 8

  9. Memory Addresses Storage cells are typically viewed as being byte-sized Usually the smallest addressable unit of memory Few machines can directly address bits individually Such addresses are sometimes called byte- addresses Memory is often accessed as words Usually a word is the largest unit of memory access by a single machine instruction CLEAR s word size is 8 bytes (= sizeof(long)) A word-address is simply the byte-address of the word s first byte Cox Arrays and Pointers 9

  10. Pointers Special case of bounded-size natural numbers Maximum memory limited by processor word-size 232 bytes = 4GB, 264 bytes = 16 exabytes A pointer is just another kind of value A basic type in C int *ptr; The variable ptr stores a pointer to an int . Cox Arrays and Pointers 10

  11. Pointer Operations in C Creation &variable Dereference *pointer Indirect assignment *pointer=val Returns variable s memory address Returns contents stored at address Stores value at address Of course, still have... Assignment pointer=ptr Stores pointer in another variable Cox Arrays and Pointers 11

  12. Using Pointers int i1; int i2; int *ptr1; int *ptr2; 0x1014 0x1000 ptr2: 0x1010 0x100C i1 = 1; i2 = 2; 0x1000 ptr1: 0x1008 i2: 0x1004 2 3 ptr1 = &i1; ptr2 = ptr1; i1: 0x1000 1 3 *ptr1 = 3; i2 = *ptr2; Cox Arrays and Pointers 12

  13. Using Pointers (cont.) int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; *int_ptr1 = int_ptr2; *int_ptr1 = int2; What happens? Type check warning: int_ptr2 is not an int int1 becomes 8 Cox Arrays and Pointers 13

  14. Using Pointers (cont.) int int1 = 1036; /* some data to point to */ int int2 = 8; int *int_ptr1 = &int1; /* get addresses of data */ int *int_ptr2 = &int2; int_ptr1 = *int_ptr2; int_ptr1 = int_ptr2; What happens? Type check warning: *int_ptr2 is not an int * Changes int_ptr1 doesn t change int1 Cox Arrays and Pointers 14

  15. Pointer Arithmetic pointer + number pointer number E.g., pointer+ 1 adds 1 something to a pointer char *p; char a; char b; int *p; int a; int b; p = &a; p += 1; p = &a; p += 1; In each, p now points to b (Assuming compiler doesn t reorder variables in memory) Adds 1*sizeof(char) to the memory address Adds 1*sizeof(int) to the memory address Pointer arithmetic should be used cautiously Cox Arrays and Pointers 15

  16. A Special Pointer in C Special constant pointer NULL Points to no data Dereferencing illegal causes segmentation fault To define, include <stdlib.h> or <stdio.h> C23 introduces nullptr as a better alternative Cox Arrays and Pointers 16

  17. Generic Pointers void *: a pointer to anything type cast: tells the compiler to change an object s type (for type checking purposes does not modify the object in any way) void *p; int i; char c; p = &i; p = &c; putchar(*(char *)p); Dangerous! Sometimes necessary Lose all information about what type of thing is pointed to Reduces effectiveness of compiler s type-checking Can t use pointer arithmetic Cox Arrays and Pointers 17

  18. Pass-by-Reference void set_x_and_y(int *x, int *y) { *x = 1001; *y = 1002; } 1001 1 a 1002 2 b void f(void) { int a = 1; int b = 2; x y set_x_and_y(&a, &b); } Cox Arrays and Pointers 18

  19. Arrays and Pointers Passing arrays: Dirty secret : Array name a pointer to the initial (0th) array element Must explicitly pass the size Really int *array int foo(int array[], unsigned int size) { array[size - 1] } a[i] *(a + i) An array is passed to a function as a pointer The array size is lost! int main(void) { int a[10], b[5]; foo(a, 10) foo(b, 5) } Usually bad style to interchange arrays and pointers Avoid pointer arithmetic! Cox Arrays and Pointers 19

  20. Arrays and Pointers int foo(int array[], unsigned int size) { printf( %d\n , sizeof(array)); } What does this print? 8 ... because array is really a pointer int main(void) { int a[10], b[5]; foo(a, 10) foo(b, 5) printf( %d\n , sizeof(a)); } What does this print? 40 Cox Arrays and Pointers 20

  21. Arrays and Pointers int i; int array[10]; int *p; int array[10]; for (i = 0; i < 10; i++) { array[i] = ; } for (p = array; p < &array[10]; p++) { *p = ; } These two blocks of code are functionally equivalent Cox Arrays and Pointers 21

  22. Strings In C, a string is just an array of characters Terminated with \0 character Arrays for bounded-length strings Pointer for constant strings (or unknown length) char str1[15] = Hello, world!\n ; char *str2 = Hello, world!\n ; C, H e l l o , w o r l d !\nterminator C terminator: \0 Java, H e l l o , w o r l d !\n length Cox Arrays and Pointers 22

  23. String length Must calculate length: can pass an array or pointer int strlen(char str[]) { int len = 0; Check for terminator array access to pointer! while (str[len] != \0 ) len++; What is the size of the array??? return (len); } Provided by standard C library: #include <string.h> Cox Arrays and Pointers 23

  24. Pointer to Pointer (char **argv) Passing arguments to main: size of the argv array/vector int main(int argc, char **argv) { ... } an array/vector of char * Recall when passing an array, a pointer to the first element is passed Suppose you run the program this way UNIX% ./program hello 1 2 3 argc == 5 (five strings on the command line) Cox Arrays and Pointers 24

  25. char **argv 3 argv[4] 0x1020 These are strings!! Not integers! 2 argv[3] 0x1018 1 argv[2] 0x1010 argv[1] 0x1008 hello argv[0] 0x1000 ./program Cox Arrays and Pointers 25

  26. Next Time Structures and Unions Cox Arrays and Pointers 26

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#