arrayscpointersstructstrsep

Error while parsing characters in a char member of a struct with strsep()


I want to parse characters in a char member of a struct with strsep() but got the following error:


sep_string_space_on_struct.c:22:26: warning: incompatible pointer types passing 'char (*)[50]' to parameter of type 'char **' [-Wincompatible-pointer-types]
  while ((chunk = strsep(&records[0].date, " ")) !=NULL)
                         ^~~~~~~~~~~~~~~~
.../string.h:165:21: note: passing argument to parameter '__stringp' here
char    *strsep(char **__stringp, const char *__delim);
                       ^
1 warning  generated.

Here is the code

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

#define BUFDATE 50

typedef struct 
{
  char date[BUFDATE];
  char tags[BUFDATE];
  char task[BUFDATE];
  char next_step[BUFDATE];
} Record;

int main()
{
  Record *records = (Record *) malloc(2*sizeof(Record));

  strcpy(records[0].date, "Hello world I am a string slice function");

  printf("%s\n", records[0].date);

  char *chunk;
  while ((chunk = strsep(&records[0].date, " ")) !=NULL)
  {
    printf("%s\n", chunk);
  }
  return 0;
}


Solution

  • The problem is that the strsep function expects a pointer to a pointer as argument, not a pointer to an array.

    The type of &records[0].date is char (*)[BUFDATE], and not the expected char **.

    You can solve it by using a new variable:

    char *pointer = records[0].date;
    strsep(&pointer, " ");
    

    The reason for passing a pointer to an actual pointer, and not an array, is that the strsep function updates where the pointer is pointing.