C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Pointers Pointer is a variable that contains the address of a variable Here P is sahd to point to the variable C C 7 34……
Array_strcpy void array_strcpy(char dest[], char src[]) { int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; }
Pointers in C Rohit Khokher
BBS514 Structured Programming (Yapısal Programlama)1 Pointers.
Kernighan/Ritchie: Kelley/Pohl:
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
1 CSE1301 Computer Programming Lecture 16 Pointers.
Pointers Pointer - A pointer is a derived data type; that is it is a data type built from one of the standard types. Its value is any of the addresses.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Pointers ( מצביעים ). 2 Variables in memory Primitives Arrays.
1 More on Pointers. 2 Reminder 3 Pointers Pointer is a variable that contains the address of a variable Here P is said to point to the variable C C 7.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
Even More C Programming Pointers. Names and Addresses every variable has a location in memory. This memory location is uniquely determined by a memory.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
1 CSE1301 Computer Programming Lecture 16 Pointers.
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Computer Skills2 for Scientific Colleges 1 Pointers in C++ Topics to cover: Overview of Pointers Pointer Declaration Pointer Assignment Pointer Arithmetic.
Pointers CSE 2451 Rong Shi.
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Chapter 11: Pointers Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 11 Pointers.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Pointers Programming Applications. Pointer A pointer is a variable whose value is a memory address representing the location of the chunk of memory on.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Pointers and Arrays An array's name is a constant whose value is the address of the array's first element. For this reason, the value of an array's name.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
142 L -1 Pointers Chapter 6 C uses a call BY VALUE for functions for example: void add_one(int x, int y) { x=x+1; y=y+1; } int main(void) { int a,b; a=4;
Introduction to Computing Lecture 12 Pointers Dr. Bekir KARLIK Yasar University Department of Computer Engineering
2/23/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 9 (C-3)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Pointers. Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example.
Pointers. Addresses in Memory Everything in memory has an address. C allows us to obtain the address that a variable is stored at. scanf() is an example.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
 Recursion  Pointers and Arrays #include void print3(int n){ if (n==0)return; printf ("%d\n",n); print3(n-1); printf ("%d\n",n); } void main(){ print3(5);
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
Basic Concepts:- Invalid use of Address Operator &75 &(‘a’) &(a+b)
Pointers. Pointer Arithmetic Since arrays consist of contiguous memory locations, we can increment (or decrement) the addresses to move through the array.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
CSE 220 – C Programming Pointers.
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
Pointers and Pointer-Based Strings
Pointers.
INC 161 , CPE 100 Computer Programming
Programmazione I a.a. 2017/2018.
CSI-121 Structured Programming Language Lecture 16 Pointers
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
Outline Defining and using Pointers Operations on pointers
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
C++ Pointers and Strings
Pointers and Pointer-Based Strings
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Exercise Arrays.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
C++ Pointers and Strings
FUNCTION ||.
Pointers.
Presentation transcript:

C Programming - Structures

Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure that contains a member which is an array, the array is copied element by element  Not just the address gets copied  For example - array_member.c Reminder – ordinary arrays can’t be copied simply by using the ‘=‘ operator  They must be copied using a loop

Structures containing arrays When passing the structure to a function by value  Changing the array field inside the function won’t change it in the calling function Reminder – when passing an ordinary array to a function, all that gets passed is the address of its first element  Hence every change to the array within the function, changes the array in the calling function

C Programming Pointers

A new type of variable Its value is the address of another variable We declare a pointer variable by adding a ‘*’ before the variable name: type *variable_name;

Understanding Pointers int i = 5; TypeNameaddressvalueinti20005 int j = 10; intj200410int*p int* p = &i; int*q int* q = p; j = *p; address of i The value of q equals the value of p Evaluate the right hand side of the assignment: Go to the variable pointed by p and take its value

Referencing The unary operator & gives the address of a variable The statement: ptr = &c; assigns the address of c to the pointer variable ptr, and now ptr points to c

Referencing - Example int n; int *iptr; /* Declare iptr as a pointer to int */ n = 7; iptr = &n; n 34…… …… iptr

Dereferencing The unary operator * is the dereferencing operator Applied ONLY on pointers Access the object the pointer points to The statement: *iptr = 5; puts 5 in the variable pointed by iptr

Dereferencing printf(“%d”, *iptr); /* Prints out ‘7’ */ *iptr = 181; printf(“%d”, n); /* Prints out ‘181’ */ iptr = 181; /* This is unadvisable!! */ n 34…… …… iptr

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2] …

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2]

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2]

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2]

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2]

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2]

Pointers Example int x=1, y=2, z[3]={5,6,7}; int *ip; ip = &x; y = *ip; *ip = 0; ip = z; ip = &z[2]; *ip = 1; xy zip Z[0]Z[1]Z[2]

Common errors It is an error to define pointers to constants or expressions.  i = &3  j = &(k + 5) It is an error to change a variable’s address (because it is not for us to determine!).  &a = 150  &a = &b Dereferencing un-initialized pointers int* a;... *a = 5;

What will be printed? int main() { int a=3,b=6,c; int *x=&a; printf(“c=%d\n”,c); } c=b*(*x);c=b**x;

Function Arguments Functions receive their arguments “by value” Cannot change the value in the caller void increment_counter(int counter) { counter++; }

Pointers as Function Arguments If we want to change a variable in the function we can pass its address – a pointer! Call “by reference” void increment_counter(int* counter) { (*counter)++; }

CallerCallee main incerement_counter(X) X by value increment_counter(int counter) by reference increment_counter(int* counter) copy of X counter main incerement_counter(&X)

Wrong Swap A swap that gets integers as variables does not change the value in the original variables. void swap(int x, int y) { int tmp = x; x = y; y = tmp; }

How can we fix it? We can define swap so it gets pointers to integers instead of integers void swap(int *x, int *y) { …swap *x and *y… } We then call swap by swap(&x, &y); This is passing values by address

Right Swap – add_swap.c void swap(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; }

Back to scanf We can now understand the & in scanf("%d", &a); The argument list in scanf is simply passed by address, so scanf can change its content

Exercise Implement the function: void split(double d, int* int_part, double* frac_part) The function accepts a double parameter and returns its integer and fraction parts. Write a program that accepts a number from the user and prints out its integer and fraction parts.

Solution void split(double num, int *int_part, double *frac_part) { *int_part = (int)num; *frac_part = num - *int_part; } int main(void) { double num, fraction; int integer; printf("Please enter a real number: "); scanf("%lf", &num); split(num, &integer, &fraction); printf("The integer part is %d\n", integer); printf("The remaining fraction is %g\n", fraction); return 0; }

Pointers and Arrays An array is consecutive bytes in memory The name of the array is the address of the first element. arr is the address of arr[0] Unlike pointers this address cannot be changed

Pointers Vs. Arrays Characteristics: Assignment: change content can changeaddress xxx pointer xx array xx const pointer arraypointer xx array xxx const pointer

Pointers Vs. Arrays - Example int arr[3] = {1, 2, 3}; int *ptr; const int* cptr; arr = ptr; ptr = arr; *ptr = 3; cptr = arr; *cptr = 5; ptr = cptr; *arr = 6; same as arr[0] = 6

Pointer arithmetic Pointers can be incremented and decremented If p is a pointer to a particular type, p+1 yields the correct address of the next variable of the same type p++, p+i, and p += i also make sense

Pointer arithmetic If p and q point to elements in an array, q-p yields the number of elements between p and q. You can’t add two pointers There is a difference between pointer arithmetic and “regular” arithmetic.

Pointer arithmetic - example int main(void) { int a[3] = {17,289,4913}, *p, *q; p = a; /* p points to the beginning of a, that is &a[0] */ q = p+2; /* q points to a[2]. Equivalent to q = &a[2] */ printf(“a is %p\n", a); printf("p is %p, q is %p\n", p, q); printf("p points to %d and q points to %d\n", *p, *q); printf("The pointer distance between p and q is %d\n", q-p); printf("The integer distance between p and q is %d\n", (int)q-(int)p); return 0; } a is 0012FECC p is 0012FECC, q is 0012FED4 p points to 17 and q points to 4913 The pointer distance between p and q is 2 The integer distance between p and q is 8

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘!’

void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘!’

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘!’

void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘!’

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘s’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘s’‘!’

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘s’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘s’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Strcpy – step by step ‘y’‘e’‘s’‘\0’‘%’ src dest ‘y’‘e’‘s’‘\0’‘!’ void my_strcpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; }

Pointers, Arrays and Function Arguments Consider the following function prototypes These are all identical void foo(char str[10]); void foo(char str[]); void foo(char* str);

Exercise Write a function with the prototype: void replace_char(char *str, char c1, char c2); It replaces each appearance of c1 by c2 in the string str. Do not use the [] operator! Demonstrate your function with a program that uses it

Solution void replace_char(char *str, char c1, char c2) { while (*str != '\0') { if (*str == c1) *str = c2; ++str; }

Exercise Write a function with the prototype: int *find_max (int *array, size); that returns a pointer to the largest element of the array Do not use the [] operator! Use pointer arithmetics

Solution int* find_max(int *array, int size) { int *ptr = array, *max = array; for (ptr=array;ptr<array+size; ptr++) { if (*ptr > *max) max = ptr; } return max; }