Quick Note on Memory 198:211 Computer Architecture

Size: px
Start display at page:

Download "Quick Note on Memory 198:211 Computer Architecture"

Transcription

1 Quick Note on Memory 198:211 Computer Architecture Topics: Pointers Advanced Types I/O Week 3 Fall 2012 We ll get into much more detail on this later in the course Remember Von Neuman Architecture All data is stored in memory Memory is addressable Think of lockers!! Locker number, contents of locker Amount of memory required per data type varies Input Unit! Memory! Unit! Arithmetic and Logic (ALU)! Control! Unit! Output! Unit! Memory Think of memory as a long continuous array Memory allocated based on bytes Has an address and contents associated with that address Memory Memory allocated to variables in bytes int x; double y; char z; short int w; This memory stays allocated for the lifetime of the variable

2 Pointers - Introduction Any variable that is declared within a program is assigned to a portion of memory to store it s assigned value. Run time systems maintains a mapping (called a symbol table) that store, for each variable, its assigned location in memory. In C, address of a variable can be access by & operator char char1 = a char char2 = b ; printf ( char1,&char1); VarName! char1! MemLoc! x3100! char2! x3101! value a b c address x3100 x3101 x3102 Pointers - Intro (continued) Since we can talk about memory address, we should be able to assign it to a variable as well! A Pointer is a type of variable that stores the address of another variable in memory Allows us to indirectly access variables in other words, we can talk about its address (or where its stored) rather than its value Pointers in C Pointers in C C lets us talk about and manipulate pointers as variables and in expressions. Declaration int *p; /* p is a pointer to an int */ A pointer in C is usually a pointer to a particular data type: int*, double*, char*, float*, etc. Pointer Operators *p -- returns the value pointed to by p &z -- returns the address of variable z Declaration int date; date=5; /* date is integer with value 5 */ int *p; /* p is a pointer to an integer variable */ p=&date /* value of p is address of date */ Remember p is of type pointer (think address) Remember *p is of type integer (think value) Initialize pointer print (,*p); /*STMT2 prints what? */ *p = date + 1 /* STMT 2 make contents of p same as integer date + 1 */ Address=10 Address=6 Address= a p printf ( format, a, &a, *p, p, &p) 2

3 Pointer Example Pointer Example int i; int *ptr; int i; int *ptr; store the value 4 into the memory location associated with i i = 4; ptr = &i; *ptr = *ptr + 1; i = 4; ptr = &i; *ptr = *ptr + 1; i! ptr!?!?!?! 4300! 4304! random address! i! ptr! 4!?!?! 4300! 4304! random address! Pointer Example Pointer Example int i; int *ptr; int i; int *ptr; store the result into memory at the address stored in ptr i = 4; ptr = &i; *ptr = *ptr + 1; store the address of i into the memory location associated with ptr i = 4; ptr = &i; *ptr = *ptr + 1; read the contents of memory at the address stored in ptr i! ptr! 4! 4300!?! 4300! 4304! random address! i! ptr! 5! 4300!?! 4300! 4304! random address! 3

4 Pointer Example #include <stdio.h> main() { int value=5; int * value_ptr; printf ("value %d, memory location %d\n", value, &value); value_ptr= &value; printf (" content of value_ptr %d\n", value_ptr); printf (" value pointed to by value_ptr %d\n", *value_ptr); printf (" address of value_ptr %d\n", &value_ptr); printf (" \n \n"); Pointer Example int i; int *ptr; i = 4; ptr = &i; *ptr = *ptr + 1; i! ptr! What would happen if the last statement was:! ptr = *ptr + 1; *ptr = ptr + 1; ptr = ptr + 1;?! 4300!?! 4300! 4304! random address! Useful Examples for Pointers Consider the following function that's supposed to swap the values of its arguments. void Swap(int firstval, int secondval) { int tempval = firstval; firstval = secondval; secondval = tempval; int fv = 6, sv = 10; Swap(fv, sv); printf( Values: (%d, %d)\n, fv, sv); Recall that functions are pass-by-value Pointers as Arguments Passing a pointer into a function allows the function to read/change memory. void NewSwap(int *firstval, int *secondval) {int tempval; tempval = *firstval; *firstval = *secondval; *secondval = tempval; int fv = 6, sv = 10; NewSwap(&fv, &sv); printf( Values: (%d, %d)\n, fv, sv); 4

5 Null Pointer Sometimes we want a pointer that points to nothing. In other words, we declare a pointer, but we re not ready to actually point to something yet. int *p; p = NULL; /* p is a null pointer */ NULL is a predefined macro that contains a value that a non-null pointer should never hold. Often, NULL = 0, because Address 0 is not a legal address for most programs on most platforms. Using Arguments for Results Pass address of variable where you want result stored Useful for multiple results Example: return value via pointer return status code as function result This solves the mystery of why & with argument to scanf: scanf("%d ", &datain); read a decimal integer and store in datain Structured data objects Arrays Structured data objects are available as object array [] struct union property enumerated, numbered from 0 names and types of fields names and types of fields but only 1 field can be used at any one time 19 Arrays are defined by specifying an element type and number of elements int vec[100]; char str[30]; float m[10][10]; For array containing N elements, indexes are 0..N-1 Stored as linear arrangement of elements Note: Index starts at 0 and the number in the declaration gives the number of elements. 20 5

6 Arrays Array elements are accessed using the same syntax as in Java: array[index] Example (iteration over array): int i, sum = 0;... for (i = 0; i < VECSIZE; i++) sum += vec[i]; C does not check whether array index values are sensible (i.e., no bounds checking) vec[-1] or vec[10000] will not generate a compiler warning! if you re lucky, the program crashes with Segmentation fault (core dumped) Arrays C references arrays by the address of their first element array is equivalent to &array[0] can iterate through arrays using pointers as well as indexes: int *v, *last; int sum = 0; last = &vec[vecsize-1]; for (v = vec; v <= last; v++) sum += *v; D arrays 2-dimensional array int weekends[52][2]; [0][0] [0][1] [1][0] [1][1] [2][0] [2][1] [3][0].... weekends Arrays - example #include <stdio.h> void main(void) { int number[12]; /* 12 cells, one cell per student */ int index, sum = 0; /* Always initialize array before use */ for (index = 0; index < 12; index++) { number[index] = index; /* now, number[index]=index; will cause error:why?*/ for (index = 0; index < 12; index = index + 1) { sum += number[index]; /* sum array elements */ return; weekends[2][1] is same as *(weekends+2*2+1) NOT *weekends+2*2+1 :this is an int! Sep-12 Advanced Programming Spring

7 Arrays SizeOf C does not remember how large arrays are (i.e., no length attribute) int x[10]; x[10] = 5; may work (for a while) In the block where array A is defined: sizeof A gives the number of bytes in array can compute length via sizeof A /sizeof A[0] When an array is passed as a parameter to a function the size information is not available inside the function array size is typically passed as an additional parameter PrintArray(A, VECSIZE); or as part of a struct (best, object-like) or globally #define VECSIZE Sep-12 Advanced Programming Spring sizeof(x) - is a function to determine the amount of storage (in bytes) required to store an object of the type of its operand char char_array[20]; int int_array[20]; sizeof(int) is 4 sizeof(char) is 1 sizeof(char_array) is 20 sizeof(int_array) is 80 Number of elements in int_array sizeof(int_array)/sizeof(int) is 20 Arrays Arrays are declared with a type and a size. Size must be known at compile time. char foo1[20]; // an array of 20 characters Arrays are accessed by referring to their elements using index numbers: foo1[10]; // value stored at the 11th element All arrays indexes start at 0; There is NO checking on array bounds int array[10], i =0; for(i=0; i< 10; i++) array[i] = i for(i=0; i< 15; i++){ printf("%d\t%d\n", i, array[i]); Array Storage Elements of an array are stored sequentially in memory!! char grid[10]; First element (grid[0]) is at lowest address of allocated space.! Knowing the first element is enough to access any element! grid[0] grid[1] grid[2] grid[3] grid[4] grid[5] grid[6] grid[7] grid[8] grid[9] 7

8 Relationship between Arrays and Pointers An array name is essentially a pointer to the first element in the array. [0] char word[10]; char *cptr; cptr = word; /* points to word[0] */ Difference: Can change the contents of cptr, as in cptr = cptr + 1; (The identifier "word" is not a variable.) be careful Correspondence between Ptr and Array Notation Given the declarations on the previous slide, each line below gives three equivalent expressions: char word[10]; char *cptr; cptr = word; cptr word &word[0] (cptr + n) word + n &word[n] *cptr *word word[0] *(cptr + n) *(word + n) word[n] Passing Arrays as Arguments C passes arrays by reference (actually it s by value) the address of the array (i.e., of the first element) is copied. otherwise, would have to copy each element. main() { int numbers[max_nums]; mean = Average(numbers); This must be a constant, e.g., #define MAX_NUMS 10 int Average(int * inputvalues ) { for (index = 0; index < MAX_NUMS; index++) sum = sum + inputvalues[index]; return (sum / MAX_NUMS); int Average(int inputvalues[], );/* Alternative Prototype */ Common Pitfalls with Arrays in C Overrun array limits There is no checking at run-time or compile-time to see whether reference is within array bounds. int array[10]; int i; for (i = 0; i <= 10; i++) array[i] = 0; Declaration with variable size Size of array must be known at compile time. void SomeFunction(int num_elements) { int temp[num_elements]; 8

9 Pointer Arithmetic Address calculations depend on size of elements C does size calculations under the covers, depending on the size of item being pointed to: double x[10]; double *y = x; *(y + 3) = 13; allocates 10 doubles, size of 80 bytes char s[10]; char *t = s; *(t + 3) = A ; same as x[3] Aside: void, void * Function that doesn t return anything declared as void No argument is also declared as void Special pointer *void can point to anything #include <stdio.h> extern void *f(void); void *f(void) { printf("the big void\n"); return NULL; int main(void) { f(); How far does each pointer move? 17-Sep-12 Advanced Programming Spring Structures in C A struct is a mechanism for grouping together related data items of different types. Recall that an array groups items of a single type. Example: We want to represent an airborne aircraft: int altitude; int longitude; int latitude; int heading; double airspeed; We can use a struct to group these data together for each plane. Defining a Struct We first need to define a new type for the compiler and tell it what our struct looks like. struct flighttype { int altitude; /* in meters */ int longitude; /* in tenths of degrees */ int latitude; /* in tenths of degrees */ int heading; /* in tenths of degrees */ double airspeed; /* in km/hr */ ; This tells the compiler how big our struct is and how the different data items ( members ) are laid out in memory. But it does not allocate any memory. 9

10 Declaring and Using a Struct To allocate memory for a struct, we declare a variable using our new data type. struct flighttype plane; Memory is allocated, and we can access individual members of this variable: plane.airspeed = 800.0; plane.altitude = 10000; A struct s members are laid out in the order specified by the definition. plane.altitude plane.longitude plane.latitude plane.heading plane.airspeed Defining and Declaring at Once You can both define and declare a struct at the same time. struct whackjob { int height; /* in meters */ int weight; /* in ounces */ char haircolor; /* B, G, etc*/ double wealth; /* in MillionDollars and cents */ snooki; And you can use the celebrity name to declare other structs. struct whackjob ladygaga; typedef C provides a way to define a data type by giving a new name or alias to a predefined type. Can use any readable name for pre defined type Syntax: typedef <type> <name>; Examples: typedef int Color; typedef struct celebrity; Using typedef This gives us a way to make code more readable by giving application-specific names to types. Color x, y; Celebrity beyonce, madonna; Typical practice: Declare typedef s into a header file, and use type names in the main program. If the definition of Flight changes, you might not need to change the code in your main program file. 10

11 Array of Structs Can declare an array of structs: Flight planes[100]; Each array element is a struct. To access member of a particular element: planes[34].altitude = 10000; Because the [] and. operators are at the same precedence, and both associate left-to-right, this is the same as: (planes[34]).altitude = 10000; Pointer to Struct We can declare and create a pointer to a struct: Flight *planeptr; planeptr = &planes[34]; To access a member of the struct addressed by a Ptr: (*planeptr).altitude = 10000; Because the. operator has higher precedence than *, this is NOT the same as: *planeptr.altitude = 10000; C provides special syntax for accessing a struct member through a pointer: planeptr->altitude = 10000; Passing Structs as Arguments Unlike an array, a struct is always passed by value into a function. This means the struct members are copied to the function s state and changes inside the function are not reflected in the calling routine s copy. Most of the time, you ll want to pass a pointer to a struct. int Collide(Flight *planea, Flight *planeb) { if (planea->altitude == planeb->altitude) {... else return 0; union Like struct (collection of variables of different types) But only one field can store a value at any given time Memory allocated to the maximum required for any field Once a field is allocated, any previous field if any is erased union exptdata {int approxdata; double precisedata;mydata; 11

12 Dynamic Allocation Memory partition When a variable is declared, memory is allocated for that variable int i, j; What if we don t a priori how may instances of a variable are needed? E.g., a variable number of integers as many as the user wants to enter. We can t allocate an array of integers, because we don t know the maximum number of that might be required. Even if we do know the maximum number, it might be wasteful to allocate that much memory because most of the time only a few integers may be needed. Solution: Allocate storage for data dynamically, as needed. Stack Local variables on stack; grows and shrinks based on calls dynamic Heap Global variables, static constants Dynamic (malloc) Stack Heap Text Enter Dynamic Memory Memory allocated from the stack has a limited life-time.! What do we do if we want memory that exists outside the life-time of functions! Two ways to get memory! Declare a variable - gets placed on the stack! Ask the run-time system for a chunk of memory! Requests for dynamic chunks of memory performed using a call to the underlying runtime system (a system call).! Command: malloc and free! Dynamic Memory or heap Dynamic request for memory are honored from heap. Memory Management taken care of by the run-time system. Complicated While functions are being called and returning, activations records are being added and removed from the heap. This does NOT effect the heap. Once allocated it will stay there until freed Question to ask: why do they grow from different directions? 0x0000 instructions global data Stack run-time heap 47 0xFFFF 48 12

13 malloc The Standard C Library provides a function for allocating memory at run-time: malloc. void *malloc(int numbytes); It returns a generic pointer (void*) to a contiguous region of memory of the requested size (in bytes). The bytes are allocated from a region in memory called the heap. The run-time system keeps track of chunks of memory from the heap that have been allocated. Example 1 #include <stdio.h> #include <malloc.h> main(){ int *base; int i,j; int cnt=0; int sum=0; printf("how many integers you have to store \n"); scanf("%d",&cnt); /* how many integers? */ base = (int *)malloc(cnt * sizeof(int)); if(!base) printf("unable to allocate size \n"); else { for(j=0;j<cnt;j++) *(base+j)=5; Using malloc To use malloc, we need to know how many bytes to allocate. The sizeof operator is used to calculate the size of a particular type. planes = malloc(n * sizeof(flight)); We also need to change the type of the return value to the proper kind of pointer this is called casting. planes = (Flight *) malloc(n* sizeof(flight)); 51 Example 2 int airborneplanes; Flight *planes; printf( How many planes are in the air? ); scanf( %d, &airborneplanes); planes = (Flight*) malloc(sizeof(flight) * airborneplanes); if (planes == NULL) { fprintf(stderr, Error in allocating the data array.\n );... planes[0].altitude =... If allocation fails, malloc returns NULL. Note: Can use array notation or pointer notation

14 free Once the data is no longer needed, it should be released back into the heap for later use. Command Line Arguments You can use the command line to provide input to your programs. This is done using the free function, passing it the same address that was returned by malloc. void free(void*); free(base); /* in example 1 */ If allocated data is not freed, the program might run out of heap memory and will be unable to continue. 53 int main( int argc, char * argv [] ){ argc - the number of arguments (including program name) argv pointer to array of char arrays (strings) 54 Command Line (example) Array of strings and double pointers int main(int argc, char * argv []){ int i; printf( %d arguments\n, argc); for(i=0; i<argc; i++) printf( \t%d: %s\n, i, argv[i]); return 0; **argv is a double pointer argv (array name) is a pointer to first element of the array Which in turn is a pointer to char argv[0], argv[1],. argv

15 File I/O example For our purposes, a file is a sequence of ASCII characters stored on some device. Allows us to process large amounts of data without having to type it in each time or read it all on the screen as it scrolls by. Each file is associated with a stream. May be input stream or output stream (or both!). The type of a stream is a "file pointer", declared as: FILE *infile; #include<stdio.h> void main(){ FILE *fp; fp = fopen( PA1.ANS", w"); fprintf(fp,"%s %d\n", OBAMA",44); fclose(fp) ; The FILE type is defined in <stdio.h> fopen The fopen (pronounced "eff-open") function associates a physical file with a stream. FILE *fopen(char* name, char* mode); First argument: name The name of the physical file, or how to locate it on the storage device. This may be dependent on the underlying operating system. Second argument: mode How the file will be used: "r" -- read from the file "w" -- write, starting at the beginning of the file "a" -- write, starting at the end of the file (append) fprintf and fscanf Once a file is opened, it can be read or written using fscanf() and fprintf(), respectively. These are just like scanf() and printf(), except an additional argument specifies a file pointer. FILE * fpout; fpin; fpout = fopen( PA1.out, w ); fprintf(fpout, "The answer is %d\n", x); fpin = fopen( PA1.in, r ); fscanf(fpin, "%s %d/%d/%d %lf\n", name, &bmonth, &bday, &byear, &gpa);

16 A String is an Array of Characters I/O with Strings Allocate space for a string just like any other array: char outputstring[16]; Space for string must contain room for terminating zero (i.e. \0 ) Special syntax for initializing a string: char outputstring[16] = "Result = "; which is the same as: outputstring[0] = 'R'; outputstring[1] = 'e'; outputstring[2] = 's'; printf and scanf use "%s" format character for string printf -- print characters up to terminating zero printf("%s", outputstring); scanf -- read characters until whitespace, store result in string, and terminate with zero scanf("%s", inputstring); char outputstring[16] = "Result ="; printf("length: %d\n", strlen(outputstring)); printf("length: %d\n", sizeof(outputstring)); 62 Useful functions for Strings Standard C Library Useful string related functions in string.h char * strcpy(ct, cs) Copy string cs to ct char * ct, cs int strcmp(str1, str2)compare string str1 to str2 char * str1, str2 A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite. size_t strlen(ls) Returns length of ls char * ls 63 I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented by any ANSI standard implementation. Automatically linked with every executable. Implementation depends on processor, operating system, etc., but interface is standard. Since they are not part of the language, compiler must be told about function interfaces. Standard header files are provided, which contain declarations of functions, variables, etc

17 Basic I/O Functions The standard I/O functions are declared in the <stdio.h> header file. Function Description putchar Displays an ASCII character to the screen. getchar Reads an ASCII character from the keyboard. printf Displays a formatted string, scanf Reads a formatted string. fopen Open/create a file for I/O. fprintf Writes a formatted string to a file. fscanf Reads a formatted string from a file. 65 Formatted I/O printf and scanf allow conversion between ASCII representations and internal data types. Format string contains text to be read/written, and formatting characters that describe how data is to be read/ written. %d signed decimal integer %f signed decimal floating-point number %x unsigned hexadecimal number %c ASCII character %s ASCII string 66 Special Character Literals Certain characters cannot be easily represented by a single keystroke, because they correspond to whitespace (newline, tab, backspace,...) are used as delimiters for other literals (quote, double quote,...) These are represented by the following sequences: \n newline \t tab \b backspace \\ backslash \' single quote \" double quote \0nnn ASCII code nnn (in octal) \xnnn ASCII code nnn (in hex) 67 printf Prints its first argument (format string) to stdout with all formatting characters replaced by the ASCII representation of the corresponding data argument. int a = 100; int b = 65; char c = 'z'; char banner[10] = "Hola!"; double pi = ; printf("the variable 'a' decimal: %d\n", a); printf("the variable 'a' hex: %x\n", a); printf("'a' plus 'b' as character: %c\n", a+b); printf("a char %c.\t A string %s\n A float %f\n", c, banner, pi); 68 17

18 scanf Reads ASCII characters from stdin, matching characters to its first argument (format string), converting character sequences according to any formatting characters, and storing the converted values to the addresses specified by its data pointer arguments. char name[100]; int bmonth, bday, byear; double gpa; scanf("%s %d/%d/%d %lf", name, &bmonth, &bday, &byear, &gpa); scanf Conversion For each data conversion, scanf will skip whitespace characters and then read ASCII characters until it encounters the first character that should NOT be included in the converted value. %d Reads until first non-digit. %x Reads until first non-digit (in hex). %s Reads until first whitespace character. Literals in format string must match literals in the input stream. Data arguments must be pointers, because scanf stores the converted value to that memory address scanf Return Value Bad scanf Arguments The scanf function returns an integer, which indicates the number of successful conversions performed. This lets the program check whether the input stream was in the proper format. Example: int rv = scanf("%s %d/%d/%d %lf", &name, &bmonth, &bday, &byear, &gpa); Input Stream Return Value Mudd 02/16/ Muss Doesn't match literal '/', so scanf quits Two problems with scanf data arguments 1. Not a pointer int n = 0; scanf("%d", n); Will use the value of the argument as an address. 2. Missing data argument scanf("%d"); Will get address from stack, where it expects to find first data argument. If you're lucky, program will crash because of trying to modify a restricted memory location (e.g., location 0). Otherwise, your program will just modify an arbitrary memory location, which can cause very unpredictable behavior. after second conversion

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

More information

Chapter 19 Data Structures -struct -dynamic memory allocation

Chapter 19 Data Structures -struct -dynamic memory allocation Chapter 19 Data Structures -struct -dynamic memory allocation Data Structures A data structure is a particular organization of data in memory. We want to group related items together. We want to organize

More information

COMPSCI 210 Part II Data Structure

COMPSCI 210 Part II Data Structure Agenda & Reading COMPSCI 210 Part II Data Structure Based on slides @ McGraw-Hill Agenda: Enum structs Nested structs Array of structs structs Parameters & Returning structs structs Pointers Exercises:

More information

Chapter 19 Data Structures

Chapter 19 Data Structures Chapter 19 Data Structures Img src: reddit.com/r/programmerhumor 19-2 Data Structures A data structure is a particular organization of data in memory. We want to group related items together. We want to

More information

Midterm 1 Review. Introduction to Programming in C. General. Turing Machine. Universal Turing Machine

Midterm 1 Review. Introduction to Programming in C. General. Turing Machine. Universal Turing Machine Midterm 1 Review General Bring student ID card Must have it to check into lab Seating Randomized seating chart Front rows Check when you enter the room Exam No time limit, 100 points NO notes, calculators,

More information

Chapter 16 Pointers and Arrays

Chapter 16 Pointers and Arrays Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address of a variable in memory Allows us to indirectly access

More information

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Pointers and Arrays

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Pointers and Arrays Chapter 16 Pointers and Arrays Original slides from Gregory Byrd, North Carolina State University Modified slides by C. Wilcox, S. Rajopadhye Colorado State University Pointers and Arrays! We ve seen examples

More information

Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi

Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 Cyrus Bazeghi POINTERS AND ARRAYS We have briefly seen these before, here are the details Pointer Array Address of a variable in memory Allows

More information

Chapter 16 Pointers and Arrays

Chapter 16 Pointers and Arrays Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address of a variable in memory Allows us to indirectly access

More information

n Address of a variable in memory n Allows us to indirectly access variables ! Array n A list of values arranged sequentially in memory

n Address of a variable in memory n Allows us to indirectly access variables ! Array n A list of values arranged sequentially in memory Chapter 16 Pointers and Arrays Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox, Colorado State University Pointers and Arrays! We've seen examples of

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses Chapter 16 Pointers and Arrays Based on slides McGraw-Hill Additional material 200/2005 Lewis/Martin Pointers and Arrays We've seen examples of both of these in our LC- programs; now we'll see them in

More information

CS 2461: Computer Architecture I

CS 2461: Computer Architecture I Next: Pointers, Arrays, Structs... : Computer Architecture I The real fun stuff in C.. Pointers and Arrays Read Chapters 16, 18 of text Functions, Arrays, Pointers Dynamic data structures Allocating space

More information

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation

More information

Why do we need Pointers? Call by Value vs. Call by Reference in detail Implementing Arrays Buffer Overflow / The Stack Hack

Why do we need Pointers? Call by Value vs. Call by Reference in detail Implementing Arrays Buffer Overflow / The Stack Hack Chapter 16 Why do we need Pointers? Call by Value vs. Call by Reference in detail Implementing Arrays Buffer Overflow / The Stack Hack A problem with parameter passing via stack Consider the following

More information

High Performance Computing in C and C++

High Performance Computing in C and C++ High Performance Computing in C and C++ Rita Borgo Computer Science Department, Swansea University Summary Introduction to C Writing a simple C program Compiling a simple C program Running a simple C program

More information

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.

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. Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

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

ch = argv[i][++j]; /* why does ++j but j++ does not? */ CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and

More information

Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers in C. Alan L. Cox 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

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

Pointers and File Handling

Pointers and File Handling 1 Pointers and File Handling From variables to their addresses Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 2 Basics of Pointers INDIAN INSTITUTE OF TECHNOLOGY

More information

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

High-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet High-performance computing and programming Intro to C on Unix/Linux IT Uppsala universitet What is C? An old imperative language that remains rooted close to the hardware C is relatively small and easy

More information

CS 11 C track: lecture 5

CS 11 C track: lecture 5 CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

Heap Arrays. Steven R. Bagley

Heap Arrays. Steven R. Bagley Heap Arrays Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index a[42] = 35; Variables and arrays have a type int, char, double,

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

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

First of all, it is a variable, just like other variables you studied Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)

More information

01:198:211 Computer Architecture Lecture 1

01:198:211 Computer Architecture Lecture 1 01:198:211 Computer Architecture Lecture 1 Liu Liu Rutgers University jack.liuliu@cs.rutgers.edu Summer 2016 Instructors Me: TA: TA: Liu Liu jack.liuliu@cs.rutgers.edu Office Hours: By appt (will be in

More information

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

Data Representation and Storage. Some definitions (in C)

Data Representation and Storage. Some definitions (in C) Data Representation and Storage Learning Objectives Define the following terms (with respect to C): Object Declaration Definition Alias Fundamental type Derived type Use pointer arithmetic correctly Explain

More information

Contents. A Review of C language. Visual C Visual C++ 6.0

Contents. A Review of C language. Visual C Visual C++ 6.0 A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

Basic Types and Formatted I/O

Basic Types and Formatted I/O Basic Types and Formatted I/O C Variables Names (1) Variable Names Names may contain letters, digits and underscores The first character must be a letter or an underscore. the underscore can be used but

More information

Advanced C Programming Topics

Advanced C Programming Topics Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8

More information

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009 Lecture 5: Multidimensional Arrays CS209 : Algorithms and Scientific Computing Wednesday, 11 February 2009 CS209 Lecture 5: Multidimensional Arrays 1/20 In today lecture... 1 Let s recall... 2 Multidimensional

More information

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 {

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 { 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

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

More information

Heap Arrays and Linked Lists. Steven R. Bagley

Heap Arrays and Linked Lists. Steven R. Bagley Heap Arrays and Linked Lists Steven R. Bagley Recap Data is stored in variables Can be accessed by the variable name Or in an array, accessed by name and index Variables and arrays have a type Create our

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings Lecture 4: Outline I. Pointers A. Accessing data objects using pointers B. Type casting with pointers C. Difference with Java references D. Pointer pitfalls E. Use case II. Arrays A. Representation in

More information

File Handling in C. EECS 2031 Fall October 27, 2014

File Handling in C. EECS 2031 Fall October 27, 2014 File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically

More information

THE FUNDAMENTAL DATA TYPES

THE FUNDAMENTAL DATA TYPES THE FUNDAMENTAL DATA TYPES Declarations, Expressions, and Assignments Variables and constants are the objects that a prog. manipulates. All variables must be declared before they can be used. #include

More information

Data Representation and Storage

Data Representation and Storage Data Representation and Storage Learning Objectives Define the following terms (with respect to C): Object Declaration Definition Alias Fundamental type Derived type Use size_t, ssize_t appropriately Use

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable. CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files

More information

2009 S2 COMP File Operations

2009 S2 COMP File Operations 2009 S2 COMP1921 9. File Operations Oliver Diessel odiessel@cse.unsw.edu.au Last updated: 16:00 22 Sep 2009 9. File Operations Topics to be covered: Streams Text file operations Binary file operations

More information

Arrays, Strings, & Pointers

Arrays, Strings, & Pointers Arrays, Strings, & Pointers Alexander Nelson August 31, 2018 University of Arkansas - Department of Computer Science and Computer Engineering Arrays, Strings, & Pointers Arrays, Strings, & Pointers are

More information

Memory, Arrays & Pointers

Memory, Arrays & Pointers 1 Memory, Arrays & Pointers Memory int main() { char c; int i,j; double x; c i j x 2 Arrays Defines a block of consecutive cells int main() { int i; int a[3]; i a[0] a[1] a[2] Arrays - the [ ] operator

More information

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng Slide Set 2 for ENCM 335 in Fall 2018 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2018 ENCM 335 Fall 2018 Slide Set 2 slide

More information

C for C++ Programmers

C for C++ Programmers C for C++ Programmers CS230/330 - Operating Systems (Winter 2001). The good news is that C syntax is almost identical to that of C++. However, there are many things you're used to that aren't available

More information

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

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia

More information

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

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Bernhard Boser & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

The Design of C: A Rational Reconstruction (cont.)

The Design of C: A Rational Reconstruction (cont.) The Design of C: A Rational Reconstruction (cont.) 1 Goals of this Lecture Recall from last lecture Help you learn about: The decisions that were available to the designers of C The decisions that were

More information

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers Instructor: Justin Hsia 6/20/2012 Summer 2012 Lecture #3 1 Review of Last Lecture C Basics Variables, Functions, Flow Control,

More information

today cs3157-fall2002-sklar-lect05 1

today cs3157-fall2002-sklar-lect05 1 today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical

More information

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

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 Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays Strings and Pointers Announcements Lab 4 Why are you taking this course? Lab 5 #, 8: Reading in data from file using fscanf Quiz Quiz Strings Special character arrays End in null character, \ char hi[6];

More information

Should you know scanf and printf?

Should you know scanf and printf? C-LANGUAGE INPUT & OUTPUT C-Language Output with printf Input with scanf and gets_s and Defensive Programming Copyright 2016 Dan McElroy Should you know scanf and printf? scanf is only useful in the C-language,

More information

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

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

C programming basics T3-1 -

C programming basics T3-1 - C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review CS 2060 Variables Variables are statically typed. Variables must be defined before they are used. You only specify the type name when you define the variable. int a, b, c; float d, e, f; char letter; //

More information

CS C Primer. Tyler Szepesi. January 16, 2013

CS C Primer. Tyler Szepesi. January 16, 2013 January 16, 2013 Topics 1 Why C? 2 Data Types 3 Memory 4 Files 5 Endianness 6 Resources Why C? C is exteremely flexible and gives control to the programmer Allows users to break rigid rules, which are

More information

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012 CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012 TOPICS TODAY Project 5 Pointer Basics Pointers and Arrays Pointers and Strings POINTER BASICS Java Reference In Java,

More information

Procedural programming with C

Procedural programming with C Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical

More information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE I A.A. 2017/2018 PROGRAMMAZIONE I A.A. 2017/2018 INPUT/OUTPUT INPUT AND OUTPUT Programs must be able to write data to files or to physical output devices such as displays or printers, and to read in data from files or

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi CE 43 - Fall 97 Lecture 4 Input and Output Department of Computer Engineering Outline printf

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

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

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Review Topics. Final Exam Review Slides

Review Topics. Final Exam Review Slides Review Topics Final Exam Review Slides!! Transistors and Gates! Combinational Logic! LC-3 Programming!! Original slides from Gregory Byrd, North Carolina State University Modified slides by Chris Wilcox,

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Lectures 5-6: Introduction to C

Lectures 5-6: Introduction to C Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 12: Memory, Files and Bitoperations (pronobis@kth.se) Overview Overview Lecture 12: Memory, Files and Bit operations Wrap Up Main function; reading and writing Bitwise Operations Wrap Up Lecture

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down

Number Review. Lecture #3 More C intro, C Strings, Arrays, & Malloc Variables. Clarification about counting down CS61C L3 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #3 More C intro, C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-25 Number Review Sign and magnitude

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

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

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

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

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 4 Input & Output Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline printf scanf putchar getchar getch getche Input and Output in

More information