C: Format %s expects argument of type char* in funny strings program -


i making program check funny strings. understand exercise read this.

my code here:

#define max_str_length 10  char* reverse(char *str) {     char *reversedstr = malloc(strlen(str));     (int = 0; < max_str_length; i++) {         (int j = max_str_length - 1; j > 0; j--) {             reversedstr[i] = str[j];         }     }     return reversedstr; }  int isfunny(char *str, char *reversedstr) {     (int = 1; < max_str_length; i++) {         if (str[i] - str[i - 1] != reversedstr[i] - reversedstr[i - 1]) {             return 0;         }     }     return 1; }  int main() {      /* enter code here. read input stdin. print output stdout */         int numberofstrings;     scanf("%i", &numberofstrings);      char **strings;     (int = 0; < numberofstrings; i++) {         scanf("%s", &strings[i]);     }      char **reversedstrings;     (int = 0; < numberofstrings; i++) {         reversedstrings[i] = reverse(strings[i]);     }      (int = 0; < numberofstrings; i++) {         if (isfunny(strings[i], reversedstrings[i])) {             printf("funny\n");         }         printf("not funny\n");     }      return 0; } 

the error getting following:

solution.c: in function 'main': solution.c:35:9: warning: format '%s' expects argument of type 'char *', argument 2 has type 'char **' [-wformat=]          scanf("%s", &strings[i]); 

i don't understand why though.

my aim make array of strings, called strings, , store there strings read. why strings[i] char** ?

i appreciate or tips.

thanks!

apparently have char * , passing it's address, wrong, scanf() wants char pointer each "%s" specifier, , fix code use

char string[10]; scanf("%s", string); 

the array automatically becomes char pointer when passed scanf() above, that's not enough.

your array of char suggest of fixed size, , if wasn't, using scanf() dangerous, suppose each array in array of char arrays has 10 elements, each string want read must have 9 characters, can instruct scanf() stop reading when read 9 characters this

scanf("%9s", strings[i]); 

if don't this, reading characters possible, illegal, causing what's called undefined behavior.

if want array of strings, of 5 strings 9 characters each, can try

char strings[5][10]; int  i; (i = 0 ; < 5 ; ++i)     scanf("%9s", strings[i]); 

note: need & address of operator example, when pass int value, because scanf() modifes data pointed passed pointer, need make pointer int variable want scan value, use & address of operator, since pass pointer containing address of variable.

suggestion: check return value of malloc(), returns null on failure, , dereferencing null poitner, undefined behavior, must careful not cause undefined behavior because it's hard debug.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -