I need to find a way to reverse a string using pointers in C. I'm not supposed to use array notation or string library functions either.
Here is my current code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//Reverse2
char *forward = "123";
char *back = malloc(sizeof(char) * 4);
reverse2(forward, back);
return 0;
}
void reverse2(char *string, char *string2) {
int counter = 0;
char *string1 = string;
while (*string1) {
counter += 1;
string1 += 1;
}
string1--;
int i;
for (i = 0; i <= counter; i++) {
*string2 = *string1;
string2 += 1;
string1--;
}
printf("%s", string2);
}
This is the error it gives when I run it in ideone:
Compilation error #stdin compilation error #stdout 0s 0KB
prog.c:8:2: warning: implicit declaration of function 'reverse2' is invalid in C99 [-Wimplicit-function-declaration]
reverse2(forward, back);
^
prog.c:41:6: error: conflicting types for 'reverse2'
void reverse2(char* string, char* string2){
^
prog.c:8:2: note: previous implicit declaration is here
reverse2(forward, back);
^
1 warning and 1 error generated.
'\0'-terminating byte forstring2.void reverse2(char* string, char* string2);beforemainto get rid of the warning.reverse2function beforemain. But some times it is not as easy as that, for example with cycling dependencies or when you are using a function from another compile unit. The line I suggested is called a function prototype, it's basically telling the compiler "hey, there is a function calledreverse2that takes to pointers tochar". So even if the compiler hasn't seen the code of the function, by the time it reaches it's first call, it already knows if the arguments match the specification.mallocat all to solve this problem. I'm pretty sure your professor will grade the answer higher if you do the reverse in place.stringstring1string2and so on. They are no better thanijk. Make the code readable with something likevoid reverse2(char* source, char* dest)and get rid of the unnecessary localstring1.