Search code examples
arrayscstringpointersdouble-pointer

Use of triple pointer over double pointer when only reading value of double pointer?


This code only looks like this as the use of structs and global variables is prohibited in the assignment.

It works either way, but I was wondering whether only using a double pointer would reallocate a temporary copy of the pointer.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void allocateData(char ***dptrArrayData, int *intArraySize)
{
    *dptrArrayData = (char**)malloc(*intArraySize*sizeof(char*));
    for (int i = 0; i < *intArraySize; i++)
    {
        (*dptrArrayData)[i] = (char*)malloc(12*sizeof(char));
        (*dptrArrayData)[i] = "Lorem Ipsum";
    }
}

void printDataDoublePointer(char **dptrArrayData, int intArraySize)
{
    for (int i = 0; i < intArraySize; i++)
    {
        printf("Text:%s at index:%d\n",dptrArrayData[i],i);
    }
}

void printDataTriplePointer(char ***dptrArrayData, int *intArraySize)
{
    for (int i = 0; i < *intArraySize; i++)
    {
        printf("Text:%s at index:%d\n",(*dptrArrayData)[i],i);
    }
}
int main()
{
    char **dptrArrayData;
    int intArraySize = 5;
    allocateData(&dptrArrayData,&intArraySize);
    printDataDoublePointer(dptrArrayData,intArraySize);
    printDataTriplePointer(&dptrArrayData,&intArraySize);
    return 0;
}

Solution

  • It works either way, but I was wondering whether only using a double pointer would reallocate a temporary copy of the pointer.

    I take you to be asking about the difference between

    void printDataDoublePointer(char **dptrArrayData, int intArraySize)
    

    and

    void printDataTriplePointer(char ***dptrArrayData, int *intArraySize)
    

    . In each case the function receives copies of all argument values presented by the caller. This is the essence of pass-by-value semantics, which are the only function-call semantics C provides.

    But there is no reallocation involved. When a pointer is passed as a function argument, only the pointer is copied, not the object to which it points. The function receives an independent pointer to the same object the original points to.