Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing array of pointers to char

Tags:

arrays

c

pointers

When I try to compile the following code I receive an error: "Type error in argument 1 to 'allocate'; found 'char * *', expected 'char *" at the line indicated (<<<<<). Explanations would be appreciated.

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

void allocate(char *dt);

int  main(void)
{
  char *data[3];

  allocate(data); <<<<<
    return 0;
}

void allocate(char *dt)
{ 
  int i;
  char buf[] = "A test string";

  for (i = 0; i < 3; i++){
    strcpy(&dt[i], buf);
    printf("%s\n", dt[i]);
  }
} 

My understanding is that I should call allocate thus: allocate(&data) but with this I receive the following error: "Type error in argument 1 to 'allocate'; found 'char * (*)[3]', expected 'char *'".

It should be obvious that I am trying to make the contents of *data[] == buf.


1 Answers

It looks like allocate is trying to allocate three strings dynamically and assign them to each member of an array of three char* pointers.

Arrays decay to pointers when you pass them as function arguments which is what you want, so the declaration of allocate needs to be void allocate(char**). Passing in data will pass in a pointer to the first element of the array, i.e. a pointer to a char*.

In allocate you will need to allocate some memory for the new strings. I'm presuming that as this is a test example you really do want separate copies of the strings for each member of the array.

Of course, at this point you will probably want a deallocate function and make sure that this is always called to perform the corresponding free for the new mallocs.

void allocate(char** dt)
{ 
    int i;
    size_t len;

    char buf[] = "A test string";
    len = sizeof buf;

    for (i = 0; i < 3; i++)
    {
        dt[i] = malloc(len);
        if (dt[i] != NULL)
        {
            memcpy(dt[i], buf, len);
            printf("%s\n", dt[i]);
        }
    }
}
like image 100
CB Bailey Avatar answered Apr 29 '26 19:04

CB Bailey