I was trying to swap the elements in the array (which is extremely basic, but when I try to change the index of the array, it mess up the whole array)
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int swap;
int position;
char temp[1000];
char *i;
swap = 1;
while (swap == 1)
{
swap = 0;
position = 1;
while (position < (argc - 1))
{
if (strcmp(argv[position], argv[position + 1]) > 0)
{
strcpy(temp, argv[position + 1]);
strcpy(argv[position], argv[position + 1]);
strcpy(argv[position + 1], temp);
}
position++;
}
}
return (0);
}
from the code above, if I put "hi" and "hello", instead of printing "hello" "hi", it brings "hello" "lo" which is super bizarre.
However, when I just simply use pointer (the code below), it works flawlessly.
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int swap;
int position;
char temp[1000];
char *i;
swap = 1;
while (swap == 1)
{
swap = 0;
position = 1;
while (position < (argc - 1))
{
if (strcmp(*(argv + position), *(argv +position + 1)) > 0 )
{
i = *(argv + position);
*(argv + position) = *(argv + (position + 1));
*(argv + position + 1) = i;
swap = 1;
}
position++;
}
}
return (0);
}
could you tell me what is wrong with the first way of doing?