Reputation: 2140
Alright, so I have the following code:
char** args = (char**)malloc(10*sizeof(char*));
memset(args, 0, sizeof(char*)*10);
char* curToken = strtok(string, ";");
for (int z = 0; curToken != NULL; z++) {
args[z] = strdup(curToken);
curToken = strtok(NULL, ";")
}
I want every arg[z]
casted into an array of chars -- char string[100] -- and then processed in the algorithms I have following. Every arg[z]
needs to be casted to the variable string at some point. I am confused by pointers, but I am slowly getting better at them.
EDIT:
char string[100] = "ls ; date ; ls";
arg[0]
will be ls, arg[1]
will be date, and arg[2]
will be ls after the above code.
I want to put each argument back into char string[100] and process it through algorithms.
Upvotes: 2
Views: 1351
Reputation: 13434
one easiest way is to keep a backup of the original string in some temporary variable.
char string[100] = "ls ; date ; ls";
char temp_str[100] = {0};
strcpy (temp_str, string);
Another way is to do it by strcat
. z
has the number of agruments.
memset(string, '\0', 100);
for (i = 0; i < z; i++)
{
strcat(string, args[i]);
if (i != (z - 1))
{
//if it is last string dont append semicolon
strcat(string, ";");
}
}
Note : Take care of the boundary condition check
Upvotes: 1
Reputation: 399881
This:
char** args = (char**)malloc(10*sizeof(char*));
memset(args, 0, sizeof(char*)*10);
is broken code. First, you shouldn't cast malloc()
's return value. Second, args
is a pointer to ten pointers to char
. You can't set them to NULL
using memset()
, there's no guarantee that "all bytes zero" is the same as NULL
. You need to use a loop.
Upvotes: 0
Reputation: 96119
If you want the parts of string copied into a fixed length string[100] then you need to malloc 100 chars for each args[] inside the loop and strncpy() the result of strtok into it. strdup will only allocate enough memory for the actual length of the supplied string (plus \0)
Upvotes: 0