I was using this SO question as part of a program that needs to reverse a string. The problem I am having is that I cannot seem to get the function to work. Here is the code I have:
int main(int argc, char *argv[]){
char *test = "Testing";
fputs(test, stdout);
fputs(reverse_string(test), stdout);
}
char* reverse_string(char *str){
char temp;
size_t len = strlen(str) - 1;
size_t i;
size_t k = len;
for(i = 0; i < (len +1)/2; i++){
temp = str[k];
str[k] = str[i];
str[i] = temp;
k--;
}
return str;
}
I am getting an error that there is conflicting types for 'reverse_string'
Edit: For anyone wondering here is the code that works. See @chux's answer for an explanation.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* reverse_string(char *str){
char temp;
size_t len = strlen(str) - 1;
size_t i;
size_t k = len;
for(i = 0; i < (len +1)/2; i++){
temp = str[k];
str[k] = str[i];
str[i] = temp;
k--;
}
return str;
}
int main(int argc, char *argv[]){
char test[] = "Testing";
fputs(test, stdout);
fputs(reverse_string(test), stdout);
}
You can not pass a const char * to a char *
char *test = "Testing";
fputs(reverse_string(test), ... // bad, attempting to change constant data.
// bad as reverse_string() is assumed to return int, but fputs() expects char *
char* reverse_string(char *str) { // Bad, there's now a function conflict
Instead
char* reverse_string(char *str); // Need to declare/define function first
char test[] = "Testing";
fputs(reverse_string(test), ... // good
[Edit]
You problem was well identified (missing function declaration) by others. My suggestion takes care of the next problem. In C, a missing declaration of a function will assume int reverse_string(...) which does not match char* reverse_string(char *str).
[Edit]
As @Shafik Yaghmou suggests, modifying a string literal char *test = "Testing" will result in undefined behavior. Hence the char test[] = "Testing" which initializes test with "Testing\0", but may be modified.
[Edit]
@GreenAsJade correctly points out OP's original error message is due to the assumed int reverse_string(...) supplying an int to s in int fputs(const char * s, FILE * stream);
char *test1 = "Testing" is not the same thing as char test2[] = "Testing". test1 becomes a char * with the size of a pointer. The initial pointer value is to a string "Testing" located elsewhere in memory. test2 is a char array with size 8: length of "Testing" + 1 for '\0'. The array test2 is initialized with 'T', 'e', ... '\0' etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With