Pointers

¡Supera tus tareas y exámenes ahora con Quizwiz!

True/False: Every byte has a unique address, and int arrays store these addresses.

False: Every byte has a unique address, *pointers* store these addresses.

True/False: given: int scores[3]; scores = &scores[0]?

True: In C, the name of the array by itself is a constant pointer to the first element of the array

True/false: A pointer declared to point to a certain type should not be assigned the address of an object of a different type (without casting)

True: The exception is pointer to void (void *), which is assignment compatible with pointers to other data types

True/False: If you want to copy an array in C, you must copy the elements one by one.

True: Use for-each or while loop

True/False: If your program uses storage which has been allocated dynamically, then you should free it (return it to the operating system) once it is no longer being used.

True: Use free()

True/False: A location in memory is identified and referenced with an 8-byte address

True: (when on a 64-bit machine like stdlinux). This address is analogous to identifying a house's location via an address

True/False: In C, the name of the array by itself is a constant pointer to the last element of the array

False: In C, the name of the array by itself is a constant pointer to the *first* element of the array that is, scores is the same as &scores[0] (don't use &scores, though!)

The dereference operator is always before the type name

False: In casts, the dereference operator follows the type name: (int *) OR (float *) OR (char *) etc.

True/False: The unary operators * and & have lower precedence than arithmetic operators

False: The unary operators * and & have higher precedence than arithmetic operators

True/False: To get the size of an array, use: int scores[3] = {89, 92, 97}; int size = sizeof(scores);

False: There is no library function in C that will tell you the size of an array (for statically or dynamically allocated arrays). This is because no array termination marker is stored in the array (except for strings, or char arrays - more later).

True/False: If ip points to the integer x, (ip holds &x) then *ip can occur in any context where x could

True: Example: *ip = *ip + 10 is equivalent to x=x+10; This increments the value stored at the address in ip by 10

True/False: pointer arithmetic involves scaling using sizeof(type)

True: IMPORTANT: When we do arithmetic with pointers, the value added or subtracted is scaled by the compiler using sizeof(type). In other words, if we add or subtract n from the address in a pointer variable ptr, the compiler will generate an instruction which adds or subtracts n * sizeof(*ptr)

True/False: before using the pointer to access any of the allocated memory, you should check to make sure that the pointer returned was not null.

True: int *p; p = calloc (10, sizeof(int) ); if (p != 0) { /*Also (if p != NULL) */ . . . . . . . . /* OK to access values */ } else { . . . . /*allocation failure, error*/ }

*(array + i) = ?

array[i] with pointer arithmetic

what is data at lowest level?

bit pattern

A pointer to void cannot be dereferenced without _______

casting Since void can point to any type, we need a cast to tell us what type of operations we are using to generate accurate instructions for CPU.

Any time a pointer is passed as a parameter, if the function will not write to variables pointed to by the pointer, the _____ keyword should be used.

const Unless the function needs to change values using the pointer, we should declare the parameter with const, to indicate that the value(s) pointed to by the parameter will not be changed, and also to restrict the interaction between the function and the calling environment. This also aids debugging.

These functions must be used when you do not know while coding how much storage will be needed.

dynamic memory allocation functions malloc() calloc()

Some data in C programs can only be accessed with pointers, like?

elements of arrays, or characters in strings

* (on the right side of an assignment) means ?

get/read the value at that address

int **x; Read as? Interpretation?

int **x; Read as: declare x as a pointer to a pointer to an integer (or a pointer to an integer pointer) Interpretation: Declare x as an 8-byte variable that holds the numeric address at which is another 8-byte numeric address at which are 32 bits (4-bytes) that we intend to manipulate as a signed integer

How can we use pointer arithmetic and the dereference operator to access elements of our dynamically allocated storage?

int *p; p = malloc (10 * sizeof(int)); *p = 100; /* assigns 100 to the first (sizeof) int bytes */ To assign int values to the next two elements: *(p + 1) = 200; /*Remember, the compiler scales the value added*/ *(p + 2) = 300; More generally, for any statically or dynamically allocated array: array[i] accesses the same element as *(array + i)

When functions are called in C, the parameters to the function are ?

passed by value function will not have access to the memory where parameters are stored, so it cannot alter their values. The values of the parameters are placed on the stack (the values are copied from the variables in the calling function, and written to the stack), before the function begins execution.

The only way to access element of array is with a ______

pointer

What is the return type of malloc() or calloc()?

pointer to void (void *)

The only way that C function can change value in calling function is by using ?

pointers

Why should sizeof be used for the parameters in calloc/malloc?

portability

What happens when you attempt to use a pointer value to access space outside the dynamically allocated storage?

seg fault

malloc() and calloc() are declared in ______.h

stdlib.h

When would you get a segmentation fault when using arrays?

trying to access element beyond last element

* VS &

unary operators * says ' go to memory' (unary dereference) & says ' go to address' (unary address)

* (on the left side of an assignment) means ?

set/write the value at that address

why do we explicitly declare the type of a variable?

so compiler can know correct kind of instructions to generate for CPU ie) int addition different than float addition

unary address operator

& (the unary) address operator gives the "address of" a piece of data; this is always a constant. The constant that represents the address is determined by the compiler. int *p; int c = 10; p = &c; /* This statement assigns to the variable p the address of c. So, p points to c */

unary dereference operator

- * - used in declaration of pointer - int *p means variable p is a pointer that points to an integer - When applied to a pointer, it accesses the data (i.e., the bits in memory) the pointer points to

pointer arithmetic

- We can use pointer arithmetic to access the elements beyond the first element - If p points to the first element, p + 1 points to the second, p + 2 points to the third, and p + n points to the (n + 1)th element -

malloc()

- dynamic allocation function - return type: void pointer (void *) - return points to first byte of allocated space on heap - one parameter (sizeof()), # bytes requested - returns uninitialized garbage values To request enough bytes for 4 integer values, we could use: int *p; p = malloc ( 4 * sizeof(int) ); /* malloc (4 * 4) is not portable! */

calloc()

- dynamic allocation function - return type: void pointer (void *) - return points to first byte of allocated space on heap - two parameters (sizeof()), # bytes & # elements - returns initialized values, of 0 To request enough bytes for 4 integer values, we could use: int *p; p = calloc ( 4, sizeof(int) ); /* calloc (4. 4) is not portable! */

passed by value

- function parameters - no access to memory, so cannot alter values - copies of values placed on stack for function execution

Most common malloc() errors (3)

- not checking for allocation failure (NULL) - memory leaks (ie forget to free) - logical error (ie try to access value after call to free)

If the address of the first integer is 0x1000 (hex 1000), then the address of the second is:

0x1004. (0x1000 + 1 * sizeof(int)) So, if sizeof(int) is 4 bytes on the system, then the address of the second integer is 0x1004.

dynamic allocation functions

1) malloc() 2) calloc() return pointer to void use 'sizeof' as parameter

int is __ bits

32 (4 bytes)

int is __ bytes

4 (32 bits)

A pointer is a variable that ... ?

A pointer is a variable (or a constant) that contains the address of another variable The type of a pointer is: pointer to the type of data to which it points. * (the unary dereference operator) is used in the declaration of a pointer type

How are elements of array stored in memory?

All of the elements of the array are stored in contiguous memory locations.

int* ptr_a; int *ptr_a; Which is the correct way to declare the int pointer?

Both are valid, but the first style leads to mistakes, so use: int *ptr_a;

Dynamically allocated arrays

Dynamically allocated arrays: A C library function is called to request space for the array elements at runtime

Why do malloc and calloc return void pointers?

If not, we'd need versions for each function in each type i.e.) float, int, char There are 8 primitive types in C. Each can extend to an unlimited number of derived types. So, we would need infinite versions of a given function if void pointers were not returned!

What happens when malloc/calloc work correctly? fail?

If the allocation succeeds, these functions return a pointer to the first bye address of the allocated memory space on the heap. If the allocation fails (out of memory error), returns null pointer (0).

++*int_ptr; Is this increasing pointer or what it is pointing to?

It's increasing the address int_ptr is pointing to, not the value at that address

Statically allocated arrays

Statically allocated arrays: The compiler generates code to allocate the space for the array elements at compile time. The space is allocated on the stack or the heap depending upon the declaration statement. - fixed size - elements initialized to 0

Statically vs Dynamically allocated arrays

Statically allocated arrays: The compiler generates code to allocate the space for the array elements at compile time. The space is allocated on the stack or the heap depending upon the declaration statement. Dynamically allocated arrays: A C library function is called to request space for the array elements at runtime

The dereference operator can be used to access data by __________.

The dereference operator can be used to access data by *indirection*. When we use a pointer to access a value rather than accessing the value directly through a variable which holds that value, we access it indirectly through the pointer variable which holds the address of the value

True/False A pointer stores a reference to (address of) its pointee, which stores something useful.

True

True/False: All pointers are 8 bytes in 64bit environment

True

True/False: Pointers are variables so they can be used without dereferencing.

True

True/False: Pointers give direct memory access

True

True/False: Without void pointers, dynamic allocation would not work

True

True/False: Arrays and pointers are closely related

True

int x = 3; int* ip = &x; Is *ip = *ip + 10 equivalent to x = x + 10?

Yes: If ip points to the integer x, (ip holds &x) then *ip can occur in any context where x could Example: *ip = *ip + 10 is equivalent to x=x+10; This increments the value stored at the address in ip by 10

what type does a void pointer hold the address of?

a pointer to void holds the address of a value of *any* type, but can't be dereferenced (i.e. cannot be used to get the "contents of" another memory location through indirection) without casting.

pointee

a variable whose address is assigned to be the value of a pointer. - A pointer stores a reference to (address of) its pointee, which stores something useful. - The dereference operation on a pointer accesses its pointee. - Allocating space for a pointer ≠ assigning a pointer its pointee

If we add 1 to a pointer, it ?

add 1 to a pointer, it adds 1 times the size of the data that it points to (scales value using sizeof(type))

Which executes faster, malloc() or calloc()?

malloc(), as it doesn't have initialized values

What does p point to at the end? int *p; int c = 10; p = &c;

p = &c; /* This statement assigns to the variable p the address of c. So, p points to c. */ *p = int p = int pointer

unsigned int *x Read as? Interpretation?

unsigned int *x; Read as: "declare x as a pointer to an unsigned integer" Interpretation: declare x as a variable that holds the numeric (8-byte) address of a location in memory at which bits are stored that we intend to manipulate as an unsigned (4-byte) integer


Conjuntos de estudio relacionados

VPN Connection and Authentication Protocols

View Set

True and False Questions Exams 1-3

View Set

Differences between Groups and Teams, Strategies to enhance team cohesion, Rigelmann effect and social loafing, What is team cohesion, Correlation between cohesion and performance, Interactive teams Vs Coactive teams, What is a sociogram, What is...

View Set

Property & Casualty Exam Study Questions

View Set

Lesson 4 - Understanding Network Security

View Set

Quiz health assessment chapters 12, 24, and 25

View Set

Political Science 2 - Michael Soupios LIU Post

View Set

Chapter 13 Fluid and Electrolytes: Balance and Disturbance (Week 1)

View Set

ATI Pharmacological and Parenteral Therapies Practice Test

View Set