EDIT 04/19/2014:
Thanks every one, it finally worked thanks to your answers. I'll leave my original post bellow, in case an other beginner ends up on this topic, he could learn from my mistakes. Again, thanks for your time, and sorry I couldn't thank you sooner, but I was in no condition. See you around.
ORIGINAL POST:
I'm trying to learn how to code, but let just say that I'm far from a master level ( - so far! - ).
I got a bunch of PDF with lots of exercices in order to practice programming, and of course, I'm stuck on one of them.
I have to make a "ft_strrev", that would reverse a string. Here's what I did so far:
#include <unistd.h>
void ft_putchar(char c)
{
write (1, &c, 1);
}
void ft_putstr(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
ft_putchar(str[i]);
i++;
}
}
int ft_strlen(char *str)
{
int i;
i = 0;
while (str[i] != '\0')
{
i++;
}
return(i);
}
void ft_strrev(char *str)
{
int i;
int j;
char *str2;
i = 0;
j = ft_strlen(str);
str2 = str;
while (j != 0)
{
str[i] = str2[j];
i++;
j--;
}
ft_putstr(str);
}
int main()
{
ft_strrev("yolo");
return(0);
}
Sorry if your eyes are bleeding or something =)
So I get a segfault, and I tried many times now to change things but it wont help. I'd like to understand why and how I should fix that.
Thanks already, sorry for my poor English skills.
Edit (I don't know if I'm supposed to delete my previous message);
Thanks a lot every one. So, with your help, I tried to change alot of things. Here's what I have now:
ft_putchar(char c);
ft_putstr(char *str);
ft_serlen(char *str);
void ft_swap(char *a, char *b)
{
char tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void ft_strrev(char *str)
{
int i;
int j;
i = 0;
j = ft_strlen(str) - 1;
while (i < j/2)
{
ft_swap(str[i], str[j]);
i++;
}
ft_putstr(str);
}
int main()
{
char *str;
str = "abcd\0";
ft_strrev(str);
return(0);
}
As a result, gcc tells me:
$ gcc -Wall -Werror -Wextra ft_strrev.c
ft_strrev.c: In function ‘ft_strrev’:
ft_strrev.c:51:3: erreur: passing argument 1 of ‘ft_swap’ makes pointer from integer without a cast [-Werror]
ft_swap(str[i], str[j]);
^
ft_strrev.c:32:7: note: expected ‘char *’ but argument is of type ‘char’
void ft_swap(char *a, char *b)
^
ft_strrev.c:51:3: erreur: passing argument 2 of ‘ft_swap’ makes pointer from integer without a cast [-Werror]
ft_swap(str[i], str[j]);
^
ft_strrev.c:32:7: note: expected ‘char *’ but argument is of type ‘char’
void ft_swap(char *a, char *b)
^
So it's not that I don't want to try to find out why it doesnt work by myself, but I have already had this issue with other exercices and I never found how I was supposed to fix it, as the many answers to that issue I found on the internet didnt help. And I don't think I'll go far in C programming if this remained unfixed. I know this must be a stupid as it looks, but I might need your help on this one as well please (and then I'll leave you alone, I swear).