Skip to content

6. Τύποι δεδομένων (Data Types)

6.2 Πρωτογενείς (βασικοί) τύποι δεδομένων

6.2.1 Αριθμητικοί τύποι

6.2.1.1 Ακέραιοι (Integer)

ranges_integer_types.c
#include <stdio.h>
#include <limits.h>

int main() {
    printf("Ranges for integer types in C:\n");
    printf("char: %d to %d\n", CHAR_MIN, CHAR_MAX);
    printf("unsigned char: 0 to %u\n", UCHAR_MAX);
    printf("short: %d to %d\n", SHRT_MIN, SHRT_MAX);
    printf("unsigned short: 0 to %u\n", USHRT_MAX);
    printf("int: %d to %d\n", INT_MIN, INT_MAX);
    printf("unsigned int: 0 to %u\n", UINT_MAX);
    printf("long: %ld to %ld\n", LONG_MIN, LONG_MAX);
    printf("unsigned long: 0 to %lu\n", ULONG_MAX);
    printf("long long: %lld to %lld\n", LLONG_MIN, LLONG_MAX);
    printf("unsigned long long: 0 to %llu\n", ULLONG_MAX);

    return 0;
}

Παράδειγμα εκτέλεσης σε υπολογιστή Apple M2Pro

$ gcc --version
Apple clang version 16.0.0 (clang-1600.0.26.6)
Target: arm64-apple-darwin24.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$ gcc ranges_integer_types.c && ./a.out
Ranges for integer types in C:
char: -128 to 127
unsigned char: 0 to 255
short: -32768 to 32767
unsigned short: 0 to 65535
int: -2147483648 to 2147483647
unsigned int: 0 to 4294967295
long: -9223372036854775808 to 9223372036854775807
unsigned long: 0 to 18446744073709551615
long long: -9223372036854775808 to 9223372036854775807
unsigned long long: 0 to 18446744073709551615

6.2.1.2 Κινητής Υποδιαστολής (Floating Point)

floating_point.py
1
2
3
4
5
6
7
8
import math

a = 0.1 + 0.2
print("0.1 + 0.2 =", a)

print("Is 0.1 + 0.2 exactly 0.3?", a == 0.3)

print("Is 0.1 + 0.2 approximately 0.3?", math.isclose(a, 0.3))
$ python floating_point.py
0.1 + 0.2 = 0.30000000000000004
Is 0.1 + 0.2 exactly 0.3? False
Is 0.1 + 0.2 approximately 0.3? True

6.2.1.3 Μιγαδικοί αριθμοί (Complex Numbers)

Παραδείγματα με τιμές μιγαδικού τύπου στην Python

complex_type_example.py
z1 = complex(3, 4)  # 3 + 4j
z2 = 1 - 2j

sum_z = z1 + z2
diff_z = z1 - z2
prod_z = z1 * z2
quot_z = z1 / z2

abs_z1 = abs(z1)

conj_z1 = z1.conjugate()

real_part = z1.real
imag_part = z1.imag

print(f"z1: {z1}, z2: {z2}")
print(f"Sum: {sum_z}")
print(f"Difference: {diff_z}")
print(f"Product: {prod_z}")
print(f"Quotient: {quot_z}")
print(f"Absolute value of z1: {abs_z1}")
print(f"Conjugate of z1: {conj_z1}")
print(f"Real part of z1: {real_part}, Imaginary part of z1: {imag_part}")
$ python complex_type_example.py
z1: (3+4j), z2: (1-2j)
Sum: (4+2j)
Difference: (2+6j)
Product: (11-2j)
Quotient: (-1+2j)
Absolute value of z1: 5.0
Conjugate of z1: (3-4j)
Real part of z1: 3.0, Imaginary part of z1: 4.0

6.2.1.4 Δεκαδικοί αριθμοί (Decimal)

BCD (Binary-Coded Decimal): Κάθε ψηφίο αναπαρίσταται από το δικό της σύνολο δυαδικών ψηφίων.

Για παράδειγμα ο δεκαδικός αριθμός 146 αναπαρίσταται στο BCD ως μια ακολουθία από 3 ομάδες 4 ψηφίων, δηλαδή ως 0001 0100 0110

decimal_example.py"
1
2
3
4
5
6
7
8
from decimal import Decimal

a = Decimal('0.1')
b = Decimal('0.2')
c = a + b

print("0.1 + 0.2 using Decimal:", c)
print("Is 0.1 + 0.2 exactly 0.3?", c == Decimal('0.3'))
$ python decimal_example.py
0.1 + 0.2 using Decimal: 0.3
Is 0.1 + 0.2 exactly 0.3? True

6.2.2 Boolean Τύποι

true_false.cpp
#include <iostream>

int main() {
    bool a = true;
    bool b = false;

    bool c = 1;  // Equivalent to true
    bool d = 0;  // Equivalent to false

    std::cout << "a (true) = " << a << std::endl;
    std::cout << "b (false) = " << b << std::endl;
    std::cout << "c (1) = " << c << std::endl;
    std::cout << "d (0) = " << d << std::endl;

    // implicit conversion
    int x = true + false;  // true (1) + false (0) = 1
    std::cout << "true + false = " << x << std::endl;

    bool result = (5 > 3);  // true
    std::cout << "5 > 3 is " << result << std::endl;

    return 0;
}
$ g++ true_false.cpp && ./a.out 
a (true) = 1
b (false) = 0
c (1) = 1
d (0) = 0
true + false = 1
5 > 3 is 1

6.2.3 Τύποι χαρακτήρων

ascii.c
#include <stdio.h>

int main() {
    char ch;

    // Print ASCII values for characters A-Z and a-z
    printf("Character    ASCII Value\n");
    printf("------------------------\n");

    for (ch = 'A'; ch <= 'Z'; ch++) {
        printf("    %c          %d\n", ch, ch);
    }

    printf("\n");

    for (ch = 'a'; ch <= 'z'; ch++) {
        printf("    %c          %d\n", ch, ch);
    }

    // Demonstrate ASCII values for digits and special characters
    printf("\nAdditional ASCII characters:\n");
    printf("Space: ASCII %d\n", ' ');
    printf("0: ASCII %d\n", '0');
    printf("9: ASCII %d\n", '9');
    printf("!: ASCII %d\n", '!');
    printf("@: ASCII %d\n", '@');
    printf("#: ASCII %d\n", '#');

    return 0;
}
$ gcc ascii.c && ./a.out
Character    ASCII Value
------------------------
    A          65
    B          66
    C          67
    D          68
    E          69
    F          70
    G          71
    H          72
    I          73
    J          74
    K          75
    L          76
    M          77
    N          78
    O          79
    P          80
    Q          81
    R          82
    S          83
    T          84
    U          85
    V          86
    W          87
    X          88
    Y          89
    Z          90

    a          97
    b          98
    c          99
    d          100
    e          101
    f          102
    g          103
    h          104
    i          105
    j          106
    k          107
    l          108
    m          109
    n          110
    o          111
    p          112
    q          113
    r          114
    s          115
    t          116
    u          117
    v          118
    w          119
    x          120
    y          121
    z          122

Additional ASCII characters:
Space: ASCII 32
0: ASCII 48
9: ASCII 57
!: ASCII 33
@: ASCII 64
#: ASCII 35

6.3 Τύποι συμβολοσειρών χαρακτήρων

string_example.c
#include <stdio.h>
#include <string.h>

int main() {
  char str[] = "Hello, C!";

  int length = strlen(str);

  printf("String: %s\n", str);
  printf("Length of the string: %d\n", length);

  return 0;
}
$ gcc string_example.c && ./a.out
String: Hello, C!
Length of the string: 9
string_example.cpp
#include <iostream>
#include <string>  

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";

    // Concatenation
    std::string result = str1 + ", " + str2 + "!";  // No need for strcat
    std::cout << "Concatenated string: " << result << std::endl;

    // Getting string length
    std::cout << "Length of result: " << result.length() << std::endl;

    // Substring extraction
    std::string sub = result.substr(0, 5);  // Extract "Hello"
    std::cout << "Substring: " << sub << std::endl;

    // Finding a substring
    size_t pos = result.find("World");
    if (pos != std::string::npos) {
        std::cout << "'World' found at position: " << pos << std::endl;
    }

    // Replacing a substring
    result.replace(pos, 5, "C++");
    std::cout << "After replace: " << result << std::endl;

    // Comparing strings
    if (str1 == "Hello") {
        std::cout << "str1 is 'Hello'" << std::endl;
    }

    // Converting a string to C-style string
    const char* cstr = result.c_str();
    std::cout << "C-style string: " << cstr << std::endl;

    return 0;
}
$ g++ string_example.cpp && ./a.out
Concatenated string: Hello, World!
Length of result: 13
Substring: Hello
'World' found at position: 7
After replace: Hello, C++!
str1 is 'Hello'
C-style string: Hello, C++!

6.4 Τύπος Απαρίθμησης (Enumeration Types)

enum_example.c
#include <stdio.h>

enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

int main() {
  enum Day today;

  today = WEDNESDAY;

  printf("Today is WEDNESDAY, which has an integer value of: %d\n", today);

  switch (today) {
    case MONDAY:
      printf("Start of the workweek!\n");
      break;
    case FRIDAY:
      printf("Weekend is near!\n");
      break;
    case SUNDAY:
    case SATURDAY:
      printf("It's the weekend!\n");
      break;
    default:
      printf("A regular weekday.\n");
      break;
  }

  return 0;
}
$ gcc enum_example.c && ./a.out
Today is WEDNESDAY, which has an integer value of: 3
A regular weekday.

6.5 Τύποι Διατάξεων (Array Types)

ragged.c
#include <stdio.h>
#include <stdlib.h>

int main() {
  int rows = 3;
  int* arr[rows];

  // Allocate different lengths for each row
  arr[0] = (int*)malloc(3 * sizeof(int));
  arr[1] = (int*)malloc(5 * sizeof(int));
  arr[2] = (int*)malloc(2 * sizeof(int));

  arr[0][0] = 1;
  arr[0][1] = 2;
  arr[0][2] = 3;
  arr[1][0] = 4;
  arr[1][1] = 5;
  arr[1][2] = 6;
  arr[1][3] = 7;
  arr[1][4] = 8;
  arr[2][0] = 9;
  arr[2][1] = 10;

  for (int i = 0; i < rows; i++) {
    printf("Row %d: ", i + 1);
    for (int j = 0; j < (i == 0 ? 3 : (i == 1 ? 5 : 2)); j++) {
      printf("%d ", arr[i][j]);
    }
    printf("\n");
  }

  for (int i = 0; i < rows; i++) {
    free(arr[i]);
  }

  return 0;
}
$ gcc ragged.c && ./a.out
Row 1: 1 2 3 
Row 2: 4 5 6 7 8 
Row 3: 9 10 

6.6 Συσχετιστικοί πίνακες (Associative Arrays)

associative_array.cpp
#include <iostream>
#include <map>
#include <string>

int main() {
  std::map<std::string, int> associativeArray;

  associativeArray["apple"] = 3;
  associativeArray["banana"] = 5;
  associativeArray["orange"] = 2;

  std::cout << "apple: " << associativeArray["apple"] << std::endl;
  std::cout << "banana: " << associativeArray["banana"] << std::endl;
  std::cout << "orange: " << associativeArray["orange"] << std::endl;

  for (const auto& pair : associativeArray) {
    std::cout << pair.first << ": " << pair.second << std::endl;
  }

  return 0;
}
$ g++ assiative_array.cpp && ./a.out
apple: 3
banana: 5
orange: 2
apple: 3
banana: 5
orange: 2
associative_array.py
# Creating an associative array using a dictionary
associative_array = {}

associative_array["apple"] = 3
associative_array["banana"] = 5
associative_array["orange"] = 2

print(f"apple: {associative_array['apple']}")
print(f"banana: {associative_array['banana']}")
print(f"orange: {associative_array['orange']}")

for key, value in associative_array.items():
    print(f"{key}: {value}")
$ python associate_array.py
apple: 3
banana: 5
orange: 2
apple: 3
banana: 5
orange: 2

6.7 Τύποι εγγραφών (Record Types)

record_example.c
#include <stdio.h>
#include <string.h>

struct Student {
  int id;
  char name[50];
  float grade;
};

int main() {
  struct Student student1;
  student1.id = 1;
  strcpy(student1.name, "John Doe");
  student1.grade = 92.5;

  struct Student student2 = {2, "Jane Smith", 88.0};

  printf("Student 1:\n");
  printf("ID: %d\n", student1.id);
  printf("Name: %s\n", student1.name);
  printf("Grade: %.2f\n\n", student1.grade);

  printf("Student 2:\n");
  printf("ID: %d\n", student2.id);
  printf("Name: %s\n", student2.name);
  printf("Grade: %.2f\n", student2.grade);

  return 0;
}
$ gcc record_example.c && ./a.out
Student 1:
ID: 1
Name: John Doe
Grade: 92.50

Student 2:
ID: 2
Name: Jane Smith
Grade: 88.00
named_tuple.py
from collections import namedtuple

Student = namedtuple("Student", ["id", "name", "grade"])

student1 = Student(1, "John Doe", 92.5)
student2 = Student(2, "Jane Smith", 88.0)

print("Student 1:")
print(f"ID: {student1.id}")
print(f"Name: {student1.name}")
print(f"Grade: {student1.grade}\n")


print("Student 2:")
print(f"ID: {student2.id}")
print(f"Name: {student2.name}")
print(f"Grade: {student2.grade}")
$ python named_tuple.py
Student 1:
ID: 1
Name: John Doe
Grade: 92.5

Student 2:
ID: 2
Name: Jane Smith
Grade: 88.0

6.8 Τύποι Πλειάδας (Tuple Types)

tuple_example.py
# 1. Creating Tuples
tuple1 = (1, 2, 3, 4)  # A tuple of integers
tuple2 = ("apple", "banana", "cherry")  # A tuple of strings
tuple3 = (1, "banana", 3.14, True)  # A tuple with mixed data types
tuple4 = ()  # An empty tuple
tuple5 = (1,)  # A tuple with a single element (note the comma)

# 2. Accessing Tuple Elements (Indexing and Slicing)
print("First element of tuple1:", tuple1[0])  # Indexing
print("Last element of tuple2:", tuple2[-1])  # Negative indexing
print("Slicing tuple3 (from index 1 to 3):", tuple3[1:3])  # Slicing

# 3. Tuple Immutability (Can't modify elements)
# tuple1[0] = 100  # This would raise an error since tuples are immutable

# 4. Concatenating Tuples
tuple6 = tuple1 + tuple2  # Concatenating two tuples
print("\nConcatenated tuple6:", tuple6)

# 5. Repeating Tuples
tuple7 = tuple2 * 2  # Repeating tuple2 twice
print("\nRepeated tuple7:", tuple7)

# 6. Length of a Tuple
print("\nLength of tuple1:", len(tuple1))

# 7. Checking Membership
print("\nIs 'apple' in tuple2?", "apple" in tuple2)  # Membership test
print("Is 10 in tuple1?", 10 in tuple1)

# 8. Iterating through a Tuple
print("\nIterating through tuple3:")
for item in tuple3:
    print(item)

# 9. Nested Tuples
nested_tuple = (1, 2, (3, 4, 5))  # Tuple within a tuple
print("\nNested tuple:", nested_tuple)
print("Accessing element in nested tuple:", nested_tuple[2][1])  # Accessing inner tuple element

# 10. Tuple Unpacking
x, y, z = (10, 20, 30)  # Unpacking a tuple
print("\nTuple unpacking:")
print("x =", x, "y =", y, "z =", z)

# 11. Counting Occurrences of an Element
tuple8 = (1, 2, 2, 3, 4, 2)
print("\nCount of '2' in tuple8:", tuple8.count(2))

# 12. Finding the Index of an Element
print("Index of '3' in tuple8:", tuple8.index(3))
$ python named_tuple.py
First element of tuple1: 1
Last element of tuple2: cherry
Slicing tuple3 (from index 1 to 3): ('banana', 3.14)

Concatenated tuple6: (1, 2, 3, 4, 'apple', 'banana', 'cherry')

Repeated tuple7: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

Length of tuple1: 4

Is 'apple' in tuple2? True
Is 10 in tuple1? False

Iterating through tuple3:
1
banana
3.14
True

Nested tuple: (1, 2, (3, 4, 5))
Accessing element in nested tuple: 4

Tuple unpacking:
x = 10 y = 20 z = 30

Count of '2' in tuple8: 3
Index of '3' in tuple8: 3

6.9 Τύποι Λίστας (List Types)

list_example.py
# 1. Creating Lists
list1 = [1, 2, 3, 4]  # A list of integers
list2 = ["apple", "banana", "cherry"]  # A list of strings
list3 = [1, "banana", 3.14, True]  # A list with mixed data types
list4 = []  # An empty list
list5 = [1]  # A list with a single element

# 2. Accessing List Elements (Indexing and Slicing)
print("First element of list1:", list1[0])  # Indexing
print("Last element of list2:", list2[-1])  # Negative indexing
print("Slicing list3 (from index 1 to 3):", list3[1:3])  # Slicing

# 3. Modifying List Elements
list1[0] = 100  # Modify an element at a specific index
print("\nAfter modifying list1:", list1)

# 4. Adding Elements to a List
list2.append("orange")  # Adding an element to the end of the list
print("\nAfter appending 'orange' to list2:", list2)

list2.insert(1, "grape")  # Inserting an element at a specific position (index 1)
print("After inserting 'grape' at index 1:", list2)

# 5. Removing Elements from a List
list2.remove("banana")  # Removing an element by value
print("\nAfter removing 'banana' from list2:", list2)

removed_element = list2.pop(1)  # Removing and returning an element by index
print("After popping index 1:", list2)
print("Removed element:", removed_element)

# 6. Concatenating Lists
list6 = list1 + list2  # Concatenating two lists
print("\nConcatenated list6:", list6)

# 7. Repeating Lists
list7 = list2 * 2  # Repeating list2 twice
print("\nRepeated list7:", list7)

# 8. Length of a List
print("\nLength of list1:", len(list1))

# 9. Checking Membership
print("\nIs 'apple' in list2?", "apple" in list2)  # Membership test
print("Is 10 in list1?", 10 in list1)

# 10. Iterating through a List
print("\nIterating through list3:")
for item in list3:
    print(item)

# 11. Nested Lists
nested_list = [1, 2, [3, 4, 5]]  # List within a list
print("\nNested list:", nested_list)
print("Accessing element in nested list:", nested_list[2][1])  # Accessing inner list element

# 12. List Unpacking
x, y, z = [10, 20, 30]  # Unpacking a list
print("\nList unpacking:")
print("x =", x, "y =", y, "z =", z)

# 13. Counting Occurrences of an Element
list8 = [1, 2, 2, 3, 4, 2]
print("\nCount of '2' in list8:", list8.count(2))

# 14. Finding the Index of an Element
print("Index of '3' in list8:", list8.index(3))
$ python list_example.py
First element of list1: 1
Last element of list2: cherry
Slicing list3 (from index 1 to 3): ['banana', 3.14]

After modifying list1: [100, 2, 3, 4]

After appending 'orange' to list2: ['apple', 'banana', 'cherry', 'orange']
After inserting 'grape' at index 1: ['apple', 'grape', 'banana', 'cherry', 'orange']

After removing 'banana' from list2: ['apple', 'grape', 'cherry', 'orange']
After popping index 1: ['apple', 'cherry', 'orange']
Removed element: grape

Concatenated list6: [100, 2, 3, 4, 'apple', 'cherry', 'orange']

Repeated list7: ['apple', 'cherry', 'orange', 'apple', 'cherry', 'orange']

Length of list1: 4

Is 'apple' in list2? True
Is 10 in list1? False

Iterating through list3:
1
banana
3.14
True

Nested list: [1, 2, [3, 4, 5]]
Accessing element in nested list: 4

List unpacking:
x = 10 y = 20 z = 30

Count of '2' in list8: 3
Index of '3' in list8: 3

6.10 Τύποι Ενώσεων (Union Types)

union_example.c
#include <stdio.h>

union Data {
  int intVal;
  float floatVal;
  char charVal;
};

int main() {
  union Data data;

  data.intVal = 10;
  printf("data.intVal = %d\n", data.intVal);

  data.floatVal = 3.14;
  printf("data.floatVal = %.2f\n", data.floatVal);

  data.charVal = 'A';
  printf("data.charVal = %c\n", data.charVal);

  printf("After overwriting, data.intVal = %d\n", data.intVal);
  printf("After overwriting, data.floatVal = %.2f\n", data.floatVal);

  return 0;
}
$ gcc union_example.c && ./a.out
data.intVal = 10
data.floatVal = 3.14
data.charVal = A
After overwriting, data.intVal = 1078523201
After overwriting, data.floatVal = 3.14

6.11 Τύποι Δεικτών και Τύποι Αναφοράς (Pointer Types and Reference Types)

pointer_vs_reference.cpp
#include <iostream>

// Function that uses a reference to modify the original value
void modifyByReference(int &x) {
    x = x * 2; // Modifying the original value by reference
}

// Function that uses a pointer to modify the original value
void modifyByPointer(int *x) {
    if (x != nullptr) { // Check if the pointer is not null
        *x = *x * 2; // Dereferencing the pointer and modifying the value
    }
}

int main() {
    int a = 5;
    int b = 10;

    std::cout << "Original values:\n";
    std::cout << "a = " << a << ", b = " << b << std::endl;

    // Call function with reference
    modifyByReference(a);
    std::cout << "\nAfter modifyByReference:\n";
    std::cout << "a = " << a << ", b = " << b << std::endl;  // a is modified by reference

    // Call function with pointer
    modifyByPointer(&b);
    std::cout << "\nAfter modifyByPointer:\n";
    std::cout << "a = " << a << ", b = " << b << std::endl;  // b is modified by pointer

    return 0;
}
$ g++ pointer_vs_reference.cpp && ./a.out
Original values:
a = 5, b = 10

After modifyByReference:
a = 10, b = 10

After modifyByPointer:
a = 10, b = 20

6.11.2 Λειτουργίες δεικτών

Ανάθεση (assignment) και αποαναφορά (dereference)

pointer_operations.c
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    int *ptr1 = &x, *ptr2 = &y;

    printf("Before swapping: x = %d, y = %d\n", x, y);
    swap(ptr1, ptr2);
    printf("After swapping: x = %d, y = %d\n", x, y);

    return 0;
}
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10

6.11.3 Προβλήματα με δείκτες

6.11.3.1 Αιωρούμενοι Δείκτες (Dangling Pointers)

dangling_pointer1.c
#include <stdio.h>
#include <stdlib.h>

int main() {
  int *p1 = (int *)malloc(sizeof(int));
  if (p1 == NULL) {
    printf("Memory allocation failed!\n");
    return -1;
  }
  *p1 = 42;
  printf("Value in allocated memory: %d\n", *p1);
  int *p2 = p1;
  free(p1);
  printf("Memory has been freed.\n");

  printf("Value in dangling pointer: %d\n", *p2);  // Undefined behavior!
}
$ gcc dangling_pointer1.c && ./a.out
Value in allocated memory: 42
Memory has been freed.
Value in dangling pointer: 0

6.11.3.2 Χαμένες μεταβλητές δυναμικής δέσμευσης σωρού

memory_leakage.c
#include <stdio.h>
#include <stdlib.h>

void createMemoryLeak(int iteration) {
    int *ptr = (int *)malloc(5 * sizeof(int)); // Allocating memory for 5 integers
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return;
    }

    // Assigning values
    for (int i = 0; i < 5; i++) {
        ptr[i] = i * 10;
    }

    // Printing values
    printf("Allocated memory region %d: ", iteration);
    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);
    }
    printf("\n");

    // Memory leak occurs because we forget to free(ptr)
    printf("Memory at address %p is not freed.\n", (void*)ptr);
}

void memoryLeak() {
    for (int i = 0; i < 3; i++) {
        createMemoryLeak(i + 1);
    }
}

int main() {
    memoryLeak();
    return 0;
}
$ gcc memory_leakage.c && ./a.out
Allocated memory region 1: 0 10 20 30 40 
Memory at address 0x144605e40 is not freed.
Allocated memory region 2: 0 10 20 30 40 
Memory at address 0x144605dc0 is not freed.
Allocated memory region 3: 0 10 20 30 40 
Memory at address 0x144605de0 is not freed.

6.11.3.3 Δείκτες στη C και στη C++

Αριθμητική δεικτών στη C

pointer_arithmetic.c
#include <stdio.h>

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int *ptr = arr;

  printf("Array elements using pointer arithmetic:\n");
  for (int i = 0; i < 5; i++) {
    printf("%d ", *(ptr + i));
  }
  printf("\n");

  return 0;
}
$ gcc pointer_arithmetic.c && ./a.out
Array elements using pointer arithmetic:
1 2 3 4 5 

void δείκτες

void_pointers.c
#include <stdio.h>

void printValue(void *ptr, char type) {
  switch (type) {
    case 'i':
      printf("Integer: %d\n", *(int *)ptr);
      break;
    case 'f':
      printf("Float: %.2f\n", *(float *)ptr);
      break;
    case 'c':
      printf("Character: %c\n", *(char *)ptr);
      break;
    default:
      printf("Unknown type\n");
  }
}

int main() {
  int a = 10;
  float b = 5.5;
  char c = 'A';

  void *ptr;

  ptr = &a;
  printValue(ptr, 'i');

  ptr = &b;
  printValue(ptr, 'f');

  ptr = &c;
  printValue(ptr, 'c');

  return 0;
}
$ gcc void_pointers.c && ./a.out
Integer: 10
Float: 5.50
Character: A

6.11.7.3 Διαχείριση Σωρού

  • Reference counter
  • Mark and Sweep

Garbage Collection (Mark & Sweep) - Computerphile