I'm not new to C, but this doesn't make sense in my mind. in my char encrypt
function, I get this warning:
crypt.h: In function ‘encrypt’:
crypt.h:32:9: warning: returning ‘char *’ from a function with return type ‘char’ makes integer from pointer without a cast [-Wint-conversion]
32 | return(encrypted_string);
| ^
Please note: This is supposed to return char
not char*
I have fixed this seemingly by changing it to char *encrypt
. But that doesn't make sense.
Can somebody explain how and why this works this way? The code seems to work, but clarity would be nice.
Here's my code:
char encrypt(char string[])
{
// allocating new buffer for encrypted string
// note: normal string
char encrypted_string[strlen(string)];
// comparing string to cipher
for(int i = 0; i < strlen(string); i )
{
for(int j = 0; j < strlen(CHARSET); j )
{
if(string[i] == CHARSET[j])
{
encrypted_string[i] = CIPHER[j];
break;
}
}
}
return(encrypted_string);// returns pointer?
}
CodePudding user response:
char encrypted_string[strlen(string)];
is an array, that decays into achar*
whenever used in an expression.- Your function returns
char
, an integer type. - Thus: "returning ‘char *’ from a function with return type ‘char’"
Related post: "Pointer from integer/integer from pointer without a cast" issues
Please note: This is supposed to return char not char*
That really doesn't make any sense.
I have fixed this seemingly by changing it to char *encrypt. But that doesn't make sense.
Well true, but maybe not for the reason you thought...You can't return a pointer to a local array inside a function, as explained by any decent beginner-level learning material (and thousands of other SO posts).
You can fix your program by using caller allocation instead and return the result through a parameter. Or return a char*
to a dynamically allocated string, but in that case mind memory leaks.
Also possible bugs here: for(int j = 0; i < strlen(CHARSET); i )
. Should probably be j
not i
.