Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is there a `-Wint-conversion` warning?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?
}

>Solution :

  • char encrypted_string[strlen(string)]; is an array, that decays into a char* 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading