Search code examples
cpointerssplitdynamic-memory-allocationc-strings

Passing NULL pointer to pointer and expect allocating for main


I was checking pointer to pointer, passing it without allocating. I want to allocate a[0]="something str" a[1]="some thing str" a[2]="something str" a[3]="something str" in pp function. Can I do this (allocating and filling with strcpy in pp function) and get it returned back to main?

This is my attempt:

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

#define MAX_LEN 100
// float 3
void pp(char *arr, char *delimiter, char **a)
{
    int i = 0;
    *a = malloc(sizeof(char) * 10);
}

int main(int argc, void **argv)
{
    char *arr = "1.77 1.65 1.56 5.555 6.1";

    char **f;
    pp(arr, " ", &f[0]);
}

I thought I could just allocate individual char * and then populate as strcpy(*(a+x),"something") but it causes segfaults at *a = malloc(sizeof(char) * 10);.


Solution

  • You have multiple bugs in your code.

    You do not initialized f but access f[0].

    You allocate memory for 10 single char but not for pointers in your function.

    Also the overall approach is broken.

    You could try like this:

    #include <stdio.h>
    #include <malloc.h>
    #include <string.h>
    
    #define MAX_LEN 100
    
    void pp(char *arr,char *delimiter,char ***a)
    {
    // TODO: Handle NULL pointers.
    
        int i=0;
        // TODO: Calculate number of strings using arr and delimiter...
        int num = 10;
        *a=malloc((num+1) * sizeof(**a));
        for (int k = 0; k < num; k++)
        {
            (*a)[k] = malloc( 1+ length of string to copy) ;
            strcpy((*a)[k], <string to copy>);
        }
        (*a)[num] = NULL; // indicate end of array.
    }
    
    int main(int argc,void **argv)
    {
        char *arr="1.77 1.65 1.56 5.555 6.1";
        char **f;
        pp(arr, " ", &f);
        int i = 0;
        while (f[i] != NULL)
        {
          printf("string #%d: %s\n", i, f[i]);
          i++;
        }
    }
    

    You should also think about a way how to report the number of found substrings back to the caller. In the example I added an extra pointer holding NULL to terminate the array.