Michal Fiala
Michal Fiala

Reputation: 75

How to parse an array in C

I wanted to parse an input string (path) into the array.

For example, if the input is

cd("C/Hra/Halo 4/Hra");

The array should contains {"C","Hra","Halo 4","Hra"}, but it contains {"C","Hra","Halo 4,"HraC"}. My friend suggested me to put "\0" for each string, but it doesn't work.

Can someone please suggest me how to repair it?

My code:

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
 void cd(char* path){
    printf("Path %s \n",path);
    int count = 0;
    int i = 0;
    int length = (int)strlen(path);
    for(i;i<length;i++){
        if(path[i]=='/')
         count ++;
    }
  char foldersName[count][255];
  char str[strlen(path)];
  strcpy(str,path);
  char * pch;
  pch = strtok (str,"/");
  count = 0;
  while (pch != NULL)
  {
    strcpy(foldersName[count],pch);
    strcat(foldersName[count],"\0");
    pch = strtok (NULL, "/");
    count ++;
  }
  printf("----------------Tokens-----------\n");
  for(i =0;i<count;i++){
    printf("%s \n",foldersName[i]);
  }
}

 int main(int argc, char *argv[])
{

   cd("C/Hra/Halo 4/Hra");

}

Upvotes: 0

Views: 5180

Answers (1)

P.P
P.P

Reputation: 121427

str doesn't have space for the null byte.

Change

   char str[strlen(path)];

to

   char str[strlen(path)+1];

Similarly char foldersName[count][255]; needs change in size too: char foldersName[count+1][255];. With the way, you count /, you could endup with a count value that's far bigger than the necessary. For example, a path could end with a trailing / (/usr/bin/), there can be multiple consecutive / in a path (/usr//bin//lib//) etc. The same could pose a problem when you tokenize the string on /.

strtok() returns a null byte terminated string. So, you don't need to do: strcat(foldersName[count],"\0");.

Your program contains several other minor issues/limitations too:

  • use size_t for storing the return value of strlen().
  • Be aware that strtok() modifies its input (that's why you had to make a copy of path).
  • foldersName[count][255]; allocates a variable length array (VLA). If path is very long (contains too many /) then the allocation could fail which can't be easily detected.
  • If any of the path components are longer then 255 you'll have buffer overflow.

Upvotes: 1

Related Questions