c - Tokenize an environment variable and save the resulting token in a char** -


I am trying to create an array of strands that represent directories stored in the pat variable. I am writing this code in C, but I am having trouble working on some parts of memory allocation.

  char * shell_path = getenv ("PATH"); Char * tok = strtok (shell_path, SHELL_PATH_SEPARATOR); Int number_of_tokens = 0, i = 0; While (to! = Null) {number_of_tokens ++; } Shell_Path_Directories = malloc (/ * This is where I need some help / /); Shell_path = getenv ("path"); Tok = strtok (shell_path, SHELL_PATH_SEPARATOR); While (to! = Null) {Shell_Path_Directories [i ++] = torque; Tok = strtok (NULL, SHELL_PATH_SEPARATOR); }  

The problem I have is that I can not think of how much storage I can afford to allocate.

I know that I'm tokening twice the wire, and it's probably stupid to do this for me, but I am open for improvement if someone can find a better way of doing this. is.

To give you the same answer as the user411313 in another bid:

< Pre> char * shell_path = getenv ("PATH"); / * Copy the environment string * / size_t const len ​​= strlen (shell_path) +1; Four * copyenv = memcpy (mlok (lane), shell_path, lane); / * Token start * / char * p = strtok (copyenv, SHELL_PATH_SEPARATOR); / * Always have at least one element in the path * / assert (p); Char ** result = Molkok (result of size [0]); Int i = 0; While (1) {result [i] = strakpy (molk (strollon (p) +1), p); P = strtok (0, SHELL_PATH_SEPARATOR); If (! P) breaks; ++ i; Result = reallock (result, (i + 1) * size * result); }

Comments