The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

Similar documents
Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

CS 11 C track: lecture 5

Understanding Pointers

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

PRINCIPLES OF OPERATING SYSTEMS

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Kurt Schmidt. October 30, 2018

Arrays and Memory Management

CS C Primer. Tyler Szepesi. January 16, 2013

High Performance Programming Programming in C part 1

ECE264 Fall 2013 Exam 3, November 20, 2013

Arrays and Pointers (part 2) Be extra careful with pointers!

CS 61c: Great Ideas in Computer Architecture

Systems Programming and Computer Architecture ( )

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Data Representation and Storage. Some definitions (in C)

CS 322 Operating Systems Practice Midterm Questions

CSE 303: Concepts and Tools for Software Development

Dynamic memory allocation (malloc)

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Quick review pointer basics (KR ch )

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet

Programming. Pointers, Multi-dimensional Arrays and Memory Management

CS24 Week 2 Lecture 1

Arrays and Pointers (part 2) Be extra careful with pointers!

EL2310 Scientific Programming

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

First of all, it is a variable, just like other variables you studied

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Array Initialization

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

A Quick Look at C for C++ Programmers

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

CS61, Fall 2012 Section 2 Notes

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Welcome! COMP s1. Programming Fundamentals

Intermediate Programming, Spring 2017*

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

Pointers and File Handling

Arrays in C. Data and File Structures Laboratory. DFS Lab (ISI) Arrays in C 1 / 1

TI2725-C, C programming lab, course

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

CS 11 C track: lecture 6

Week 6 Part 1. Kyle Dewey. Monday, July 30, 12

Welcome! COMP s1. Programming Fundamentals

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

CMPSC 311- Introduction to Systems Programming Module: Arrays and Pointers

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

ESC101N: Fundamentals of Computing End-sem st semester

Memory Allocation in C

Chapter IV Introduction to C for Java programmers

Fundamental of Programming (C)

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

POINTER AND ARRAY SUNU WIBIRAMA

Variables and literals

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

EL2310 Scientific Programming

CSE 333 Lecture 2 - arrays, memory, pointers

CSE 333 Lecture 4 - malloc, free, struct, typedef

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

Pointers, Arrays, Memory: AKA the cause of those Segfaults

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Lectures 5-6: Introduction to C

CS 222: Pointers and Manual Memory Management

Work relative to other classes

Dynamic Memory Allocation and Command-line Arguments

FUNCTIONS POINTERS. Pointers. Functions

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

COMP 2355 Introduction to Systems Programming

Arrays and Pointers (part 1)

Character Strings. String-copy Example

Pointers. Pointer References

Lecture Notes on Memory Layout

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

CS Software Engineering for Scientific Computing. Lecture 2: Our first C++ programs: Hello World, and others; pointers and memory management

CS 241 Data Organization Pointers and Arrays

CSE 333 Lecture 3 - arrays, memory, pointers

Final CSE 131B Spring 2005

Lecture 14. Dynamic Memory Allocation

Programming in C Lecture Tiina Niklander

CSC 1600 Memory Layout for Unix Processes"

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Fall Programming Assignment 1 (updated 9/16/2017)

CS 261 Data Structures. Introduction to C Programming

Introduction Slide 1/20. Introduction. Fall Semester. Parallel Computing

Transcription:

Memory A bit is a binary digit, either 0 or 1. A byte is eight bits, and can thus represent 256 unique values, such as 00000000 and 10010110. Computer scientists often think in terms of hexadecimal, rather than binary, because each hex digit maps to four bits, and thus a byte is more compactly represented in only two hex digits. The mapping is: 0 0000 1 0001 2 0010 3 0011 4 0100 5 0101 6 0110 7 0111 8 1000 9 1001 a 1010 b 1011 c 1100 d 1101 e 1110 f 1111 Thus, the two example values above would be 0x00 and 0x96. Think of your computer as a huge array of bytes; say, 2 32 or 2 64 of them, depending on the system. Everything, absolutely everything about your program must ultimately be represented in bytes and stored somewhere in memory. That applies even to code; your C source code compiles down to machine code, which has a very precise mapping into bytes, and is stored somewhere in memory for the CPU to read, one instruction at a time, and execute. Each of your variables also resides somewhere. The computer (more specifically, the C compiler and runtime) decides where everything goes, and unless you care to find out, this organization usually doesn t matter to you. This massive array, your memory, naturally has indices. As good computer scientists, we number from zero, so the lowest index of a byte in memory is 0x00000000, and the highest possible location in memory (on a 32-bit system) is 0xffffffff. The index of a particular chunk of memory is called its address; the & operator lets you determine the address of any variable, and the %p format to printf is specially tailored for printing them out (they are also just numbers, so you can print them out however you like). addresses.c 1

5 int i; 7 printf("the address of i is %p.\n", &i); 8 printf("the address of main is %p.\n", &main); 10 return 0; 11 } This program prints out the address of a local function variable and also the address of a function itself (remember that your code is sitting in memory too, encoded as machine instructions). It produces something like this: The address of i is 0xbf85416c. The address of main is 0x80483e4. As discussed, each primitive type has a particular fixed width. C also has arrays; an array has a particular size and a particular type, and is space set aside for that many of those values. For example, if each int takes up four bytes somewhere in memory, an array of five ints takes up twenty contiguous bytes somewhere in memory. The address of the array is synonymous with the address of the first element; the address of the second element is four greater (because it falls right after the first, which consumes those four indices of memory). This program demonstrates both the concepts above, and the syntax for working with arrays. arrays.c 5 int arr[5]; 7 printf("the address of arr is %p.\n", &arr); 8 printf("the address of the first element is %p.\n", &arr[0]); 9 printf("the address of the second element is %p.\n", &arr[1]); 10 printf("each element occupies %zd bytes.\n", sizeof arr[0]); 11 printf("the whole 5-element array occupies %zd bytes.\n", sizeof arr); 13 return 0; 14 } The output: 2

The address of arr is 0xbf95d9cc. The address of the first element is 0xbf95d9cc. The address of the second element is 0xbf95d9d0. Each element occupies 4 bytes. The whole 5-element array occupies 20 bytes. Note that &arr, the address of arr, is the same as &arr[0], the address of arr[0] (which is the first element, remember counting from zero!). Also note that the second element, arr[1], falls immediately after arr[0], and the size of the whole array is the number of elements times the size of each. Arrays in C are fixed size and always homogeneous; you can not grow or shrink an array, and you can not have an array of values some of which are ints and some of which are doubles. This is a handy time to introduce pointers. A pointer type is an integer type big enough to store indexes into memory, that is, addresses. Thus, the type int * is for values that are addresses, specifically the addresses of ints. In addition to simply storing the results of the address-of & operator, you can also go the other way, and turn the address back into a value, with the dereference * operator. If you have an int pointer p, the expression *p evaluates to the value of the memory at the address stored in p, as an int. You can also assign to *p to change that part of memory. pointers.c 5 int i = 0; 6 int *p = &i; 8 printf("i = %d\n", i); 9 printf("*p = %d\n", *p); 11 i = 1; 13 printf("i = %d\n", i); 14 printf("*p = %d\n", *p); 16 *p = 2; 18 printf("i = %d\n", i); 19 printf("*p = %d\n", *p); 21 return 0; 22 } As you might imagine, this produces: 3

i = 0 *p = 0 i = 1 *p = 1 i = 2 *p = 2 In addition to assigning a pointer from the address of another variable, you can also allocate anonymous portions of memory of arbitrary size with malloc, a standard function found in stdlib.h. Thus: 2 #include <stdlib.h> pointers2.c 4 int main(int argc, char **argv) 5 { 6 int *p; 8 p = malloc(sizeof *p); 9 if (!p) { 10 fprintf(stderr, "Could not allocate memory!\n"); 11 return 1; 12 } 14 *p = 2; 16 printf("*p = %d\n", *p); 18 free(p); 19 return 0; 20 } It is possible for you to run out of memory, in which case malloc returns a so-called null pointer; null pointers are guaranteed to be false, so we can check for failure. Note that at the end, we free the memory we allocate. Every single time you call malloc, it returns a new chunk of memory of the size you request, and every single one of them must be freed. This is crucial, and failure to do so results in memory leaks. Now for a little secret: Pointers and arrays are the same thing. Some simple arithmetic is allowed on pointers. For example, with an int pointer p, p + 1 evaluates to the address of the next int in memory after p s target (thus, the actual address increases by 4, not 1; it is 1 value, not one address). Naturally, p + 2 evaluates to the one after that, and, obviously, p + 0 is p itself. The syntax a[i], used for array indices, is in fact syntactic sugar for *(a + i). Thus, here is the array-of-five-ints example, with malloc. 4

2 #include <stdlib.h> arrays2.c 4 int main(int argc, char **argv) 5 { 6 int *arr; 8 arr = malloc(5 * sizeof arr[0]); 9 if (!arr) { 10 fprintf(stderr, "Could not allocate memory!\n"); 11 return 1; 12 } 14 printf("the address of arr is %p.\n", arr); 15 printf("the address of the first element is %p.\n", &arr[0]); 16 printf("the address of the second element is %p.\n", arr + 1); 17 printf("each element occupies %zd bytes.\n", sizeof *arr); 19 free(arr); 20 return 0; 21 } Finally, a second little secret: Strings are not a fundamental type in C, but rather are simply arrays of characters. Each character takes up one byte (the size of a char), and there is always an implicit null character \0 at the end, so that you know how long the string is. Here, for example, is a simple re-implementation of the standard strlen function (the real one is found in string.h). It simply counts the number of actual characters in the string, not including the terminal null. strlen.c 5

3 unsigned int strlen(char *str) 5 unsigned int i = 0; 6 while (str[i]!= \0 ) 7 ++i; 8 return i; 9 } 11 int main(int argc, char **argv) 12 { 13 char greeting[] = "Hello, world!\n"; 15 printf("the greeting occupies %zd bytes.\n", sizeof greeting); 16 printf("it has %u characters.\n", strlen(greeting)); 18 return 0; 19 } Another real-life example of arrays and strings is one we have been ignoring so far: the arguments to main. The argv argument is a char pointer pointer; in fact, it is an array of strings (an array of arrays of characters). How big is the array? Naturally, sizeof would only tell us the size of a pointer. Thus, we also get argc, the count of the arguments. Here is a very simple program similar to the standard echo utility, which just prints its arguments. echo.c 5 int i; 7 for (i = 0; i < argc; ++i) 8 printf("%s\n", argv[i]); 10 return 0; 11 } The first argument, argv[0], is the name of the program as you typed it; the real echo utility doesn t print it, but this one does, for demonstration purposes. $./echo./echo $./echo blah./echo 6

blah $./echo foo bar./echo foo bar 7