strcpy(temp[i],args[i]);
This is undefined behavior. strcpy
tries to access an indeterminate memory location resulting in undefined behavior.
You need to allocate memory to temp[i]
or simply use
temp[i]=strdup(args[i])
to copy the string to temp[i]
.
Also
int size = 4*sizeof(args)/sizeof(args);
would be
int size = sizeof(args)/sizeof(*args);
If you know the length of the array to be 4 then what's the use of doing all those calculation. You need to calculate it not put it like that.
Example code:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *args[] = {"sort", "myshell.c", ">", "2"};
size_t size = sizeof(args)/sizeof(*args);
char *temp[size];
size_t len = 0;
printf("SIZE: %zu\n", size);
for(size_t i = 0; i < size; ++i){
if(strcmp(args[i], ">") != 0 ){
temp[len++] = args[i];
}
}
for(size_t i = 0; i < len; i++){
printf("arg[%zu]: %s\n", i+1, temp[i]);
}
return 0;
}
Note that your comparison should be much more simpler as mentioned above.
What does strdup
do?
Internally it allocates memory and then copies the target string using strcpy
. This is not part of the standard library and implemented by POSIX.
For more detail look at this answer .