Hi,
I am writing a reverse function, to reverse a string, but when I am compiling I am getting an error, and I know its from the malloc line of code. This is the first time i have used malloc, but I want the function to work for any length of string.
#include <stdio.h>
#include <stdlib.h>
//reverse a string
int mystrlen(char *s);
void reverse(char *s);
int main() {
char string1[80];
printf("Enter string:");
gets(string1);
reverse(string1);
printf("%s",string1);
}
int mystrlen(char *s) {
int i=0;
while (s[i] != '\0') {
i++;
}
return i;
}
void reverse(char *s) {
int i=0, length;
char *p;
length = mystrlen(s);
p = malloc(length+1); //this line here
while (s[i] != '\0') {
p[i] = s[length-(i+1)];
i++;
}
s[i] = '\0';
free(p);
}
my understanding is that malloc will return a pointer. In my case p.
I declared char *p as a character, so p is of char type and a pointer to the char.
This is the error I get:
In function `void reverse(char*)':
error: invalid conversion from `void*' to `char*'