C Programming Basics and Pointers Exploration

lecture 2 programming in c n.w
1 / 45
Embed
Share

Dive into the fundamentals of C programming, including pointers and arrays. Learn how to manipulate memory addresses, declare pointers, access array elements, and perform pointer arithmetic. Discover the differences between arrays in C and Java, understand how pointers work, and explore common programming errors to avoid.

  • C Programming
  • Pointers
  • Arrays
  • Memory Manipulation
  • Pointer Arithmetic

Uploaded on | 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. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

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.

E N D

Presentation Transcript


  1. Lecture 2: Programming in C 1

  2. Q: What happens when we run the following code? int *p; *p = 5; A. B. 5 5 p p C. Compile time error D. Segmentation fault 2

  3. Q: What is the output of this code? int *p, x = 5; p = &x; printf( %d ,(*p)++); A. The value pointed to by p, which is 5 B. The value pointed to by p plus one, which is 6 C. Undefined 3

  4. Two important facts about Pointers 1) A pointer can only point to one type (basic or derived ) such as int, char, a struct, another pointer, etc 2) After declaring a pointer: int *ptr; ptrdoesn t actually point to anything yet. We can either: make it point to something that already exists, or allocate room in memory for something new that it will point to 4

  5. Array Basics 100 104 108 112 116 ar int ar[5]; // declares a 5-element integer array 5

  6. Array Basics 100 104 108 112 116 ar int ar[5]; int ar[] = {795, 635};//declares and fills a 2- element integer array. // declares a 5-element integer array 6

  7. Array Basics 100 104 108 112 116 ar 20 Accessing elements: ar[i];// returns the ith element How are arrays in C different from Java? 7

  8. Arrays and Pointers 100 104 108 112 116 ar 20 ar is a pointer to the first element ar[0] is the same as *ar ar[2] is the same as *(ar+2) Use pointers to pass arrays to functions Use pointer arithmetic to access arrays more conveniently

  9. Pointer Arithmetic Since a pointer is just a memory address, we can add to it to traverse an array. ptr+1 will return a pointer to the next array element. 100 104 108 112 116 ptr ar 60 20 40

  10. Pointer Arithmetic 100 104 108 112 116 ptr 60 20 40 Perform these operations in sequential order and select the right sequence (1, 2, 3) below A. 21, 20, 40 B. 21, 21, 40 C. 21, 40, 40 1. *ptr+1 = ? 2. *ptr++ = ? 3. *(ptr+1)=?

  11. Arrays: Fast data access Using pointer arithmetic, easy to compute the address of any array element in memory How are array elements accessed on an ARM? 100 104 108 112 116 ptr 60 20 40 Base address (100) Address Memory register Processor Data

  12. Restrictions on memory access Not all of memory is accessible by your program 100 104 108 112 116 ptr 60 20 40 Base address (100) Address Memory register Processor Data

  13. Q: Which of the assignment statements produces an error at compilation. Why? int *p, ar[5]; //Declaration ar 100 104 108 112 116 i) p=ar+5; ii)ar=p+1; 20 p A. p=ar+5; B. ar=p+1; C. Both statements result in error at compile time D. Neither results in a compilation error

  14. Q: What happens when the following code is executed? int *p, ar[5]; //Declaration p=ar-5; *p=0; A. Always results in a segmentation fault because a pointer cannot be used to change the value of an array element B. Always results in a segmentation fault because the array element being accessed is out of bounds C. Likely to result in a segmentation fault because the memory location being accessed may not be a valid address D. It results in a compilation error

  15. Arrays Pitfall: An array in C does not know its own length, & bounds not checked! Consequence: We can accidentally access off the end of an array. Consequence: We must pass the array and its size to a procedure which is going to traverse it. Segmentation faults and bus errors: These are VERY difficult to find, so be careful.

  16. Pointer Arithmetic What if we have an array of large structs (objects)? C takes care of it: In reality, ptr+1doesn t add 1 to the memory address, but rather adds the size of the array element. C knows the size of the thing a pointer points to every addition or subtraction moves that many bytes: 1 byte for a char, 4 bytes for an int, etc.

  17. Pointer Arithmetic Question How many of the following are invalid? I. pointer + integer (ptr+1) II. integer + pointer (1+ptr) III. pointer + pointer (ptr + ptr) IV. pointer integer (ptr 1) V. integer pointer (1 ptr) VI. pointer pointer (ptr ptr) VII. compare pointer to pointer (ptr == ptr) VIII. compare pointer to integer (1 == ptr) IX. compare pointer to 0 (ptr == NULL) X. compare pointer to NULL (ptr == NULL) #invalid A: 1 B: 2 C: 3 D: 4 E: 5

  18. Pointer Arithmetic Question How many of the following are invalid? I. pointer + integer (ptr+1) II. integer + pointer (1+ptr) III. pointer + pointer (ptr + ptr) IV. pointer integer (ptr 1) V. integer pointer (1 ptr) VI. pointer pointer (ptr ptr) VII. compare pointer to pointer (ptr == ptr) VIII. compare pointer to integer (1 == ptr) IX. compare pointer to 0 (ptr == NULL) X. compare pointer to NULL (ptr == NULL) #invalid A: 1 B: 2 C: 3 D: 4 E: 5

  19. Overview of Functions Functions make code easy to Maintain Debug Reuse 19

  20. Functions Overview void foo(int x, int y); //Declaration 20

  21. Functions Overview //Definition void foo(int x, int y) { int tmp; tmp= x; x= y; y= tmp; } y x foo tmp What does foo do? 21

  22. Stack Allocation When program execution starts Local variables of func() Other information about func() Stack Pointer Local variables of main() What if main calls the function func()? 22

  23. Stack Allocation Variables whose lifetime is the execution time of function are managed using the stack structure Stack Pointer Local variables of main() 23

  24. Variables declared within a function A. can be used by other functions A. can only be used within the function B. continue to exist in memory as long as the program executes 24

  25. Consider the following function //Declaration void swap(int x, int y); void swap(int x, int y) { int tmp; tmp= x; x= y; y= tmp; } y x swap The swap function intends to swap the value of its inputs. Is the logic correct? A. Yes B. No C. Depends x y 25

  26. Q: Which of the following changes are required to interchange the values in a and b when swap is called? { . . . . swap(a, b); } y x 6 5 b a swap A. In swap, return the values of x and y to the main function after swapping them B. Declare a and b as global variables, so that they become accessible to the swap routine C. Pass the address of a and b to swap instead of their value D. Move the implementation in swap to the main function 26

  27. Q: Which of the following changes are required to interchange the values in a and b when swap is called? { . . . . swap(a, b); } y x 6 5 b a swap A. In swap, return the values of x and y to the main function after swapping them B. Declare a and b as global variables, so that they become accessible to the swap routine C. Pass the address of a and b to swap instead of their value D. Move the implementation in swap to the main function 27

  28. Functions: Call by reference void swap(int *x, int *y) { . . . } Q: What should the modified swap function do? A. Swap the addresses in x and y B. Swap the values pointed to by x and y C. Both the above operations are equivalent 28

  29. Functions: Call by reference void swap(int *x, int *y) { } Q: What should the modified swap function do? A. Swap the addresses in x and y B. Swap the values pointed to by x and y C. Both the above operations are equivalent 29

  30. void IncrementPtr(int *p){ p = p + 1; } Q: What happens when IncrementPtr(q)is called in the following code: Aq int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); 50 60 70 A. q points to the next element in the array with value 60 B. q points to the first element in the array with value 50

  31. void IncrementPtr(int *p){ p = p + 1; } Q: What happens when IncrementPtr(q)is called in the following code: Aq int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(q); 50 60 70 A. q points to the next element in the array with value 60 B. q points to the first element in the array with value 50

  32. void IncrementPtr(int **p){ p = p + 1; } Q: How should we implement IncrementPtr(),so that q moves by one element when the following code executes? Aq int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); 50 60 70 A. p = p + 1; B. &p = &p + 1; C. *p= *p + 1; D. *p++; E. p= &p+1;

  33. void IncrementPtr(int **p){ p = p + 1; } Q: How should we implement IncrementPtr(),so that q moves by one element when the following code executes? Aq int A[3] = {50, 60, 70}; int *q = A; IncrementPtr(&q); 50 60 70 A. p = p + 1; //The current one is correct B. &p = &p + 1; C. *p= *p + 1; D. *p++; E. p= &p+1;

  34. Derived data types: Structures

  35. C structures : Overview A struct is a data structure composed of simpler data types. Like a class in Java/C++ but without methods or inheritance. struct point { int x; int y; } void PrintPoint(struct point p) { printf( (%d,%d) } , p.x, p.y);

  36. Pointers to structures The C arrow operator (->) dereferences and extracts a structure field with a single operator. The following are equivalent: struct point *p; printf( printf( x is %d\n x is %d\n , (*p).x); , p->x);

  37. Representation in memory struct p { int y; char x; }; struct p sp; sp y (4 bytes) x (1byte) 0x105 0x100 0x104

  38. Q: How are the structs below stored in memory? struct p { int y; char x; }; struct p sp; sp y (4 bytes) x (1byte) 0x100 0x104 struct p { char x; int y; }; Struct p sp;

  39. Data Alignment Processors do not always access memory in byte sized chunks, instead in 2, 4, 8, even 16 or 32 byte chunks Boundaries at which data objects are stored affects the behavior of read/write operations into memory 0x00 0x00 0x01 0x02 0x02 0x03 0x04 0x04 0x05 Programmer's view of memory Processor s view of memory

  40. Data Alignment Consider the task of reading 4 bytes from memory starting at 0x00 for processors that read 1, 2, 4 bytes at a time. How many memory accesses are needed in each case? 0x00 0x00 0x00 0x01 0x02 0x02 0x03 0x04 0x04 0x04 0x05 2 byte reads 4 byte reads 1 byte reads

  41. Why data alignment? Now consider the task of reading 4 bytes from memory starting at 0x01 for processors that read 1, 2, 4 bytes at a time. How many memory accesses are needed in each case? Some processors just would not allow this scenario because it is extra work for the h/w and it affects the performance 0x00 0x00 0x00 0x01 0x02 0x02 0x03 0x04 0x04 0x04 0x05 2 byte reads 4 byte reads 1 byte reads

  42. Alignment requirements Data objects should start at memory addresses that are divisible by the size of the data object short (2 byte) at address divisible by 2 0b_ _ _ _ _ 0 int (4 byte) at address divisible by 4 0b_ _ _ _ 00 double (8 byte) at address divisible by 8 0b_ _ _ _ 000

  43. Alignment requirements Q: How is sp stored in memory? struct p { char x; int y; }; struct p sp;

  44. Alignment requirements Q: How is sp laid out in memory? Compiler takes care of zero padding struct p { char x; int y; }; struct p sp; sp x 0 0 0 y 0x100 0x104 0x108

  45. How big are structs? Recall C operator sizeof() which gives size in bytes (of type or variable) Q: How big is sizeof(struct p)? struct p { char x; int y; }; A. 5 bytes B. 8 bytes C. 12 bytes

Related


More Related Content