Mastering C Pointers, Structures, and Unions

Posted by Anonymous and classified in Computers

Written on in English with a size of 8.51 KB

Pointers in C

A pointer is a variable that stores the memory address of another variable. They are essential in C for dynamic memory allocation, array manipulation, and implementing complex data structures.

1. Declaring and Initializing Pointers

A pointer variable must be declared to hold the address of a specific data type.

A. Declaration

The asterisk (*) is the dereference operator or value-at-address operator. When declaring a pointer, it signifies that the variable is a pointer to a specific type.

data_type *pointer_name;
  • Example: int *ip; // Declares ip as a pointer that can hold the address of an integer variable.

B. Initialization

A pointer is initialized by assigning it the address of a variable using the address-of operator (&).

int num = 100;
int *ip;
ip = # // 'ip' now holds the memory address of 'num'.
  • You can also declare and initialize in one line: int *ip = #

2. Accessing Address and Value using Pointers

C uses two special operators related to pointers:

OperatorNamePurposeExampleResult
&Address-of OperatorReturns the memory address of a variable.&nume.g., 0x7ffee46 (memory address)
*Dereference OperatorReturns the value stored at the address contained in the pointer variable.*ip100 (the value of num)

Example of Accessing Value

int num = 50;   // num stores 50
int *p = # // p stores address of num

printf("Address of num: %p\n", &num); // Output: Address (e.g., 0x7fff...)
printf("Value of num: %d\n", num);    // Output: 50

printf("Value stored in p: %p\n", p);  // Output: Same address as above
printf("Value at address stored in p: %d\n", *p); // Output: 50

*p = 75; // Change the value *through* the pointer
printf("New value of num: %d\n", num); // Output: 75

3. Pointers and Arrays

Pointers and arrays are closely related in C. Array names are essentially constant pointers to the first element of the array.

A. Array Name as a Pointer

When an array name is used without square brackets ([]), it represents the base address (the address of the first element, index 0).

  • For an array int arr[5];, the following expressions are equivalent:
    • arr is the address of the first element.
    • &arr[0] is the address of the first element.

B. Accessing Elements using Pointer Arithmetic

You can access any element of an array using the base pointer and pointer arithmetic.

  • Address Calculation: If p is a pointer to the start of the array, p + i gives the address of the i-th element. C automatically scales the address by the size of the data type.
  • Value Access: To get the value of the i-th element, you dereference the calculated address: *(p + i).
Array NotationPointer NotationMeaning
arr[i]*(arr + i)Value of the element at index i
&arr[i]arr + iAddress of the element at index i

Example:

int data[] = {10, 20, 30};
int *ptr = data; // 'ptr' stores the address of 'data[0]'

// Accessing the second element (index 1)
printf("Value using array: %d\n", data[1]);    // Output: 20
printf("Value using pointer: %d\n", *(ptr + 1)); // Output: 20

Key Advantage

The pointer/array relationship allows functions to efficiently process large arrays by passing only the base address (a pointer) rather than copying the entire array content.

That's a great final topic! C allows programmers to create User-Defined Data Types using Structures and Unions.

Structures (struct)

A structure is a user-defined, heterogeneous data type that allows you to logically group variables of different data types under a single name.

1. Definition

Defining a structure creates a template or blueprint. It does not allocate memory.

struct structure_name {
    data_type member1;
    data_type member2;
    // ... other members
};
  • Example:
    struct Student {
        int roll_number;
        char name[50];
        float percentage;
    };

2. Advantages of Structure

  • Grouping Related Data: Structures allow you to treat logically related data (like a student's ID, name, and grades) as a single unit, improving code organization.
  • Modularity: They help manage complex data in large programs by providing a clear, defined data format.
  • Function Handling: You can pass an entire structure to a function instead of passing each member individually.

3. Declaring Structure Variables

Once the structure is defined, you can declare variables of that type, which allocates memory.

struct structure_name variable1, variable2;
  • Example:
    struct Student s1, s2; // Declares two variables of type struct Student

4. Accessing Structure Members

Individual members of a structure variable are accessed using the dot operator (.).

structure_variable.member_name
  • Example:
    s1.roll_number = 101;
    strcpy(s1.name, "Alice");
    printf("Student Name: %s\n", s1.name);

5. Structure Members Initialization

You can initialize a structure variable during declaration:

struct Student s1 = {101, "Alice", 85.5}; // Order matters

You can also use designated initializers (since C99) for clarity, especially when initializing a subset of members:

struct Student s2 = {.percentage = 92.1, .roll_number = 102};

6. Array of Structures

You can declare an array where each element is a structure variable. This is useful for managing a database of records.

  • Declaration:
    struct Student class_roster[50]; // An array to hold 50 student records
  • Accessing: To access the roll number of the 5th student (index 4):
    class_roster[4].roll_number = 105;

Unions (union)

1. Union Definition

A union is similar to a structure, but all of its members share the same memory location. It is a memory-saving technique used when you know that only one member of the union will be used at any given time.

union union_name {
    data_type member1;
    data_type member2;
    // ... other members
};
  • Example:
    union Data {
        int i;
        float f;
        char str[20];
    };

2. Difference Between Structure and Union

The fundamental difference lies in memory allocation and member access:

FeatureStructure (struct)Union (union)
Memory AllocationAllocates memory for ALL members.Allocates memory only for the LARGEST member.
Total SizeSum of the sizes of all members (plus potential padding).Size of the single largest member.
Member AccessAll members can be accessed and modified simultaneously.Only one member can hold a meaningful value at any given time; writing to one member corrupts the others.
Use CaseGrouping logically related, independent data fields.Managing data where the type varies, and only one type is needed at a time (e.g., variant records).

Summary: If you need to store and access multiple data fields concurrently (like a student record), use a Structure. If you need to store data that can be one of several different types but only one at a time (to save memory), use a Union.

Related entries: