C_basics @ Author Name | 2023-07-27T20:08:27+01:00 | 2 minutes read | Update at 2023-12-06T00:27:08Z

Cut out summary from your post content here.

C-style 2D array

  1. Fully fixed

    int static_arr[3][4];
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            printf("Address of static_arr[%d][%d]: %p\n", i, j, &static_arr[i][j]);
        }
    }
    printf("\n");
    
  2. Fully free

    int** fully_free_arr = (int **)malloc(3 * sizeof(int *));
    for (i = 0; i < 3; i++) {
        dynamic_arr1[i] = (int *)malloc(4 * sizeof(int));
    }
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            fully_free_arr[i]+j = i*j;
            *(fully_free_arr+i)+j = i*j; //or
            fully_free_arr[i][j] = i*j;  //or
        }
    }
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 4; j++) {
            printf("Address of dynamic_arr1[%d][%d]: %p\n", i, j, &dynamic_arr1[i][j]);
        }
    }
    
  3. Column fixed

  4. Row fixed

NULL and nullprt

NULL and nullptr are both used in C++ programming to represent null pointer values, but there are key differences between them:

  • NULL: This is a macro that is a null pointer constant. It’s a value that a pointer can take to represent that it’s not pointing to any valid memory location. NULL is a carryover from C to C++ and is typically defined as 0 or (void*)0.
  • nullptr: This is a keyword introduced in C++11 to represent a null pointer. nullptr is of type std::nullptr_t, which can be implicitly converted into any pointer type. It’s a special type that’s not an integer, and its purpose is to solve ambiguity problems that arise with NULL.

Here’s an example that illustrates the problem that nullptr solves:

void foo(int);
void foo(char*);

foo(0);       // calls foo(int)
foo(NULL);    // might call either foo depending on if NULL is defined as 0 or (void*)0
foo(nullptr); // unambiguously calls foo(char*)

In this case, nullptr guarantees that the call will be made to foo(char*), whereas NULL might not, depending on how it’s defined.

© 2020 - 2024 Li Yuanhao's Blog

Powered by Hugo with theme Dream.

avatar

Li Yuanhao's BlogJust do it

Social Links