C++ Pointers and Addresses

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

In C, what is the primary purpose of the & operator when used with a variable?

  • To dereference a pointer.
  • To declare a pointer variable.
  • To perform a bitwise AND operation.
  • To return the memory address of the variable. (correct)

Regarding lvalues and rvalues in C, which statement is correct?

  • An rvalue can always be placed on the left side of an assignment.
  • An lvalue is any valid expression, while an rvalue is only a variable name.
  • An lvalue must refer to a memory location. (correct)
  • An lvalue is an expression that cannot have a memory space reserved for it.

In C, how is a pointer typically declared?

  • By prefixing a variable name with the `*` symbol during declaration. (correct)
  • Pointers do not need explicit declarations.
  • Using the `ptr` keyword.
  • By using the `address` keyword.

What does dereferencing a pointer in C using the * operator allow you to do?

<p>Access the value stored at the memory address pointed to by the pointer. (D)</p> Signup and view all the answers

If ptr is a pointer to an integer, what does ptr + 1 do?

<p>It increments the memory address stored in <code>ptr</code> by the size of an integer. (B)</p> Signup and view all the answers

What is a 'void pointer' in C?

<p>A pointer that can point to any data type. (B)</p> Signup and view all the answers

Which of the following is a valid use case for function pointers in C?

<p>To pass a function as an argument to another function. (B)</p> Signup and view all the answers

What is the meaning of const int *ptr in C?

<p><code>ptr</code> is a non-constant pointer to a constant integer. (B)</p> Signup and view all the answers

What is the significance of a 'static' variable inside a function in C?

<p>It retains its value between function calls. (B)</p> Signup and view all the answers

When should explicit type conversion (casting) of pointers be avoided in C?

<p>When assigning a more qualified pointer to a less qualified pointer. (D)</p> Signup and view all the answers

What is the purpose of the -> operator in C when used with pointers and structures?

<p>It is used to access a structure member when you have a pointer to the structure. (A)</p> Signup and view all the answers

What is the typical return type of the main function in a C program, and what does its return value signify?

<p><code>int</code>; The return value indicates the program's execution status to the operating system. (C)</p> Signup and view all the answers

How does using pointer arithmetic on array elements differ from using array indexing?

<p>Pointer arithmetic involves manual address calculation, while array indexing is handled by the compiler. (C)</p> Signup and view all the answers

In the context of function arguments, what does it mean to 'pass by reference' using pointers in C?

<p>The function receives the memory address of the variable, allowing it to modify the original variable. (B)</p> Signup and view all the answers

Which of the following standard library functions in C is used to dynamically allocate memory?

<p>All of the above (D)</p> Signup and view all the answers

What is 'memoization' in the context of function optimization?

<p>A technique for storing and reusing the results of expensive function calls to avoid redundant computations. (A)</p> Signup and view all the answers

Regarding function pointers, what does the following declaration mean: int (*func_ptr)(int, int);?

<p>It declares a pointer named <code>func_ptr</code> to a function that takes two integers as arguments and returns an integer. (B)</p> Signup and view all the answers

Consider the given C code snippet. What does it do?

int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
ptr += 2;
int value = *ptr;

<p><code>value</code> will store the value 30. (A)</p> Signup and view all the answers

In C, which function is used to perform a binary search on a sorted array?

<p><code>bsearch()</code> (C)</p> Signup and view all the answers

In the C standard library, what are stdin, stdout, and stderr?

<p>They are predefined stream pointers for standard input, standard output, and standard error, respectively. (D)</p> Signup and view all the answers

Which header file in the C standard library is required for performing input and output operations?

<p><code>stdio.h</code> (D)</p> Signup and view all the answers

Which of the following functions is used to write formatted output to a file in C?

<p><code>fprintf()</code> (C)</p> Signup and view all the answers

If a C program encounters an error during file input/output, which function can be used to print a descriptive error message to stderr?

<p><code>perror()</code> (D)</p> Signup and view all the answers

Which function in C is used to close a file stream?

<p><code>fclose()</code> (D)</p> Signup and view all the answers

What is the purpose of the fflush() function in C when used with file streams?

<p>To force the writing of buffered output to a file. (B)</p> Signup and view all the answers

What is the significance of the end-of-file (EOF) character?

<p>It signals the end of input from a file or stream. (D)</p> Signup and view all the answers

Which of the following functions reads a line from a stream?

<p><code>fgets()</code> (C)</p> Signup and view all the answers

In C, what does the rewind() function do?

<p>It resets the file position indicator to the beginning of the file. (B)</p> Signup and view all the answers

Which of the following functions is used to read unformatted data (raw bytes) from a file in C?

<p><code>fread()</code> (C)</p> Signup and view all the answers

What is the purpose of using binary streams?

<p>Processing data as a sequence of bytes without any formatting. (A)</p> Signup and view all the answers

Which function is used to retrieve a name for a temporary file?

<p><code>tmpnam()</code> (C)</p> Signup and view all the answers

What is the purpose of the qsort function?

<p>To sort an array. (D)</p> Signup and view all the answers

Which correctly describes how the comparison function (compar) should behave when used with qsort?

<p>It returns a negative value if the first element should come before the second, positive if the first should come after the second, and 0 if they are equal. (B)</p> Signup and view all the answers

When creating a static variable inside a function to track the number of times that function has been called, what is the initial value of that variable if it is not explicitly initialized?

<p>Zero. (A)</p> Signup and view all the answers

What is the purpose of a header file in C programming?

<p>To declare functions, variables, and structures that are used in multiple source files. (D)</p> Signup and view all the answers

Which of the following describes the purpose of using a *const char ** argument.

<p>A pointer to a constant character pointer. (D)</p> Signup and view all the answers

Flashcards

Address

A memory location's address

Left-value (lvalue)

A left-value (lvalue) is an expression that can appear on the left side of an assignment.

Right-value (rvalue)

A right-value (rvalue) is any valid expression.

& operator

An operator (&) that returns the address of a left-value.

Signup and view all the flashcards

Pointer

A variable that stores a memory address.

Signup and view all the flashcards

Pointer Declaration

Declaring a pointer requires the * symbol.

Signup and view all the flashcards

Benefit of typed pointers

Detect errors at compilation

Signup and view all the flashcards

Null pointer

Identified by the value NULL.

Signup and view all the flashcards

Constant Pointer

Read-only, writing forbidden.

Signup and view all the flashcards

Generic pointer

A pointer of type void*

Signup and view all the flashcards

Function Pointer

Allows passing functions as arguments.

Signup and view all the flashcards

Dereferencing

Accessing the data to which the pointer points.

Signup and view all the flashcards

-> operator

Access data pointed to by pointer in struct

Signup and view all the flashcards

== (for pointers)

Indicates if two pointers have the same address.

Signup and view all the flashcards

  • operator (pointers)

Move pointer towards the right

Signup and view all the flashcards

  • operator (pointers)

Move pointer towards the left

Signup and view all the flashcards

++ operator (pointers)

Advance pointer to the next block

Signup and view all the flashcards

-- operator (pointers)

Move to the previous block

Signup and view all the flashcards

Implicit pointer conversion

If p is more qualified than q, otherwise explicit conversion is required.

Signup and view all the flashcards

Safe pointer conversions

Conversion to same type is ok, especially adding const. Conversion to void* also OK

Signup and view all the flashcards

Array addresses

Recover a value's address in a table.

Signup and view all the flashcards

Pointer += 1

Pointer Arithmetic

Signup and view all the flashcards

Variables attached to function

Called static variables.

Signup and view all the flashcards

Memoization

Memorize function results

Signup and view all the flashcards

Function arguments

Pass function as argument

Signup and view all the flashcards

Syntax (*f)(int x)

Function pointer usage

Signup and view all the flashcards

qsort compar parameter

Pointer to function that compares two elements.

Signup and view all the flashcards

stdio.h

Standard input/output library in C.

Signup and view all the flashcards

stdin

Standard input

Signup and view all the flashcards

stdout

Standard output

Signup and view all the flashcards

stderr

Standard error

Signup and view all the flashcards

Return value of program

0 means finished normally.

Signup and view all the flashcards

Study Notes

Addresses and Pointers

  • Data items in memory are stored at a specific memory address
  • The ampersand operator (&) retrieves the memory address of a left-value
  • The ampersand only functions with left values

Addresses Within Structures

  • The addresses for the elements of the structure will be different for each element
  • Stored contiguously

Pointers

  • A pointer is a left-value holding a memory address
  • Pointers are declared using the asterisk symbol (*)

Typed Pointers

  • Examples of typed pointers: char*, int*, double*, double**, enum answer*, struct player*, void*.
  • Typed pointers identify errors during compilation
  • Different types of pointers include:
    • Null pointer. Identified by the value NULL.
    • Constant pointer. Permits read-only access with write access denied.
    • Generic pointer of type void*.
    • Function pointer. This allows you to pass functions as arguments

Memory Space

  • All pointers occupy the same amount of memory space
  • Pointers contain addresses

Qualifiers

  • const <type> *p: A read-only pointer
    • The pointed-to value can be read but not written
  • <type> *const p: A constant pointer
    • The pointer's value cannot be modified
  • Arrays often decay into constant pointers

Pointer Dereferencing

  • Dereferencing accesses data at the memory location pointed to by a pointer
  • Achieved through the asterisk operator (*)

Arrow Operator

  • For a pointer p pointing to a structure with field champ, p->champ is equivalent to (*p).champ
  • p->champ is preferred over (*p).champ

Pointer Operations

  • Assignment (=)
  • Conversion: implicit or explicit using (type*)
  • Comparison
    • Equality of addresses (==)
    • Inequality of addresses (!=)
    • Comparison of addresses (<=, >=, <, >)
  • Arithmetic
    • +: Pointer incremented towards the "right"
    • -: Pointer decremented towards the "left"
    • ++: Incrementation
    • --: Decrementation

Pointer Assignment and Conversion

  • Pointers can be assigned to each other
  • If p and q have the same type, the operation occurs without issue
  • If p is more qualified (const) than q, an implicit conversion occurs
  • Otherwise, an explicit conversion is required

Safe Pointer Conversions

  • Converting a pointer should be avoided except in cases where
    • The pointer is of the same type but more qualified (const)
    • Conversion to or from a void pointer (void*)
    • Assigning the NULL value

Arrays and Pointer Arithmetic

  • It's possible to get addresses of values in arrays

Pointer Arithmetic Details

  • Accessing elements in arrays involves pointer arithmetic
  • If 't' points to the start of the array:
    • t + i: points to the i-th value
    • t - 1: points to the value to the 'left'
    • t + 6: points to the value to the 'right'
    • (t + i) == &t[i] and *(t + i) == t[i]

Comparison Operators

  • == specifies if two pointers contain the same address
  • != negates ==
  • <=, >=, <, > compares two pointers
  • It's useful to have pointers that point toward the outside area to use them as bounds. However, errors can occur during deference

Operators+ and -

  • With p as a pointer of type t*:
    • p + i: Shifts p by sizeof(t) * i bytes
    • p - i: Shifts p by sizeof(t) * -i bytes

Operators ++ and --

  • ++: Increments a pointer to the next block of memory
  • --: Decrements a pointer to the previous block of memory
  • Useful for iterating through arrays

Function Static Variables

  • Static variables can be associated with a function
  • They are declared with the keyword static
  • Static variables are allocated at the beginning of the program and freed at the end
  • Initialized to 0 by default

Memoization

  • When calling a function with the same arguments, simply reuse the previous result.

Functions as Arguments

  • Enables passing functions as arguments to other functions
  • Supported languages include Java, C++, Python, Haskell
  • Examples include map and filter functions

Function Pointers

  • Function pointers are typed
  • They can be included inside of structs and arrays
  • Syntax matters

Callbacks

  • This can be implemented in C via function pointers
  • Need to create a function and pass a pointer of the function to another function

Function Tables Implementation

  • Function table: array containing function pointers
  • Access functions using array indexing

Standard Library Functions

  • qsort exists in the stdlib.h file
    • base: pointer to the first element of the array
    • nmemb: number of elements in the table
    • size: individual element size
    • compar: pointer to a function used to compare two elements
  • void* enables greater abstraction
  • Conversions or casts will be required to use it

Searching a Collection

  • bsearch exists in the stdlib.h file

Standard I/O Library

  • stdio implies the Standard Input Output library
  • This is implemented when you #include <stdio.h>

Stdio Library

  • Includes macros like:
    • EOF: denotes the end of file
    • stdin, stdout, stderr: standard input/output channels
    • NULL: signifies a null pointer and the FILE struct is used to represent data streams.
  • Types:
    • FILE: data stream
    • size_t: number of bytes
    • fpos_t: position in a flux
  • External variables such as optarg, opterr, optind, optopt manage function arguments.
  • Consists dozes of functions

General Operations: Opening and Closing

  • fclose(FILE *): closes a data stream
  • fdopen(int, const char *): opens a data stream with a file descriptor
  • fopen(const char *, const char *): opens a data stream
  • freopen(const char *, const char *, FILE *): reopens a data stream

Removal and Renaming

  • remove(const char *): deletes a file or directory
  • rename(const char *, const char *): renames a file or directory

Temporary file management

  • tmpnam(char *): return a temporary filename
  • tmpfile(void): creates a temporary file

General information

  • feof(FILE *): Checks if the end of the stream has been reached
  • fileno(FILE *): Gets the file descriptor of a flux
  • ctermid(char *): gets terminal name
  • cuserid(char *): gets user's name

Error Handling

  • clearerr(FILE *): clears EOF and error indicators
  • ferror(FILE *): checks if there was an error
  • perror(const char *): prints an error message to stderr

Character Manipulation

  • fgetc(FILE *): reads a character from a flux
  • getc(FILE *): equivalent to fgetc
  • fputc(int, FILE *): write a character to a flux
  • putc(int, FILE *): equivalent to fputc
  • ungetc(int, FILE *): puts back a character on a flux

Standard Channels

  • getchar(void): equivalent to getc(stdin)
  • putchar(int): write a character to stdout

Byte Manipulation

  • fread(void *, size_t, size_t, FILE *): reads bytes from a flux
  • fwrite(const void *, size_t, size_t, FILE *): write bytes from a flux
  • getw(FILE *): reads a words from a flux
  • putw(int, FILE *): write a word to stdout

Manipulating Strings

  • fgets(char *, int, FILE *): reads a line from a flux
  • fputs(const char *, FILE *): write a string to a flux
  • gets(char *): reads a string from stdin
  • puts(const char *): write a string to stdout

Formatted I/O

  • fprintf(FILE *, const char *, ...): write formatted output to a flux
  • fscanf(FILE *, const char *, ...): reads formatted output from a flux
  • vfprintf(FILE *, const char *, va_list): the same as fprintf with va_list arguments
  • printf(const char *, ...): is the same as fprintf, but to stdout
  • scanf(const char *, ...): is the same as fscanf, but from stdin
  • sprintf(char *, const char *, ...): writes formatted output to a string
  • snprintf(char *, size_t, const char *, ...): same as sprintf with safety
  • sscanf(const char *, const char *, int ...): parses formatted input from a string.
  • vprintf(const char *, va_list): formatted output with va_list on stdout.
  • vsnprintf(char *, size_t, const char *, va_list): same as snprintf with va_list
  • vsprintf(char *, const char *, va_list): same as sprintf with va_list

Moving through data streams

  • fseek(FILE *, long int, int): adjust position in a flux
  • fseeko(FILE *, off_t, int): same as fseek withoff_t offset
  • ftell(FILE *): returns courante position in a flux
  • ftello(FILE *): same as ftell using the type off_t
  • fsetpos(FILE *, const fpos_t *): Modifies the position in a flux
  • fgetpos(FILE *, fpos_t *): Retrieves the position in a flux
  • rewind(FILE *): reset position at the beginning of the file

Arguments and Buffers

  • getopt(int, char * const[], const char): Manages command line arguments. LEGACY

Buffers

  • fflush(FILE *): flushes a buffer
  • setvbuf(FILE *, char *, int, size_t): configures buffereing strategy in flux
  • setbuf(FILE *, char *): configure unbuffered flux strategy

Inter-Process Communication

  • pclose(FILE *): close a channel communication
  • popen(const char *, const char *): open a channel communication

Locking threads

  • flockfile(FILE *): Lock a flux
  • ftrylockfile(FILE *): Tries version without lock
  • funlockfile(FILE *): Unlock a flux
  • getc_unlocked(FILE *): not secured flux
  • putc_unlocked(int, FILE *): not secured flux
  • getchar_unlocked(void): not secured flux
  • putchar_unlocked(int): not secured flux

Standard channels

  • Programs interact with standard I/O through three channels:
    • Stdin (canal 0): Standard input.
    • Stdout (canal 1): Standard output
    • Stderr (canal 2): Standard error.
  • By default:
    • Stdin reads keyboard input line buffered
    • Stdout displays to the terminal line buffered
    • Stderr displays to the terminal unbuffered

Standard Input

  • A program can read data
  • Listens for the keyboard

Standard Output

  • A program can write it to the terminal.
  • The default is to write the data

Standard output for errors

  • Can write using standard error output
  • By default, it displays on the terminal

Return values

  • Unix programs return code that indicate program was successful
  • Has semantics for its exit status:
    • Zero for normal termination
    • Non-zero, indicates abnormal termination
  • The return value is stored into a variable

C's returning

  • Value from main
  • Good Practice: always indicates returning value
  • Function to exit - Allows clean exit from a program - Flushes open streams - Removes temporary files

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Pointers in Computer Science Quiz
5 questions
Puntatori in C++: Concetti Base
25 questions
Use Quizgecko on...
Browser
Browser