string - "incompatible type for argument 1 of ‘strcpy’" error in C -
i writing program must define own versions of following functions:
int atoi ( const char * str ); int strcmp ( const char * str1, const char * str2 ); char * strcpy ( char * destination, const char * source ); char * strcat ( char * destination, const char * source ); char * strchr ( char * str, int character );
inside main function, required declare array called wordlist of type myword of size 20. then, using strtok() library function, extract each word string mystring , store in wordlist. however, keep getting error message:
incompatible type argument 1 of ‘strcpy’
for line:
strcpy(wordlist[i], token);
how fix problem? far, have:
#include <stdio.h> #include <string.h> struct myword{ char word[21]; int length; }; int main(void){ typedef struct myword myword; int = 0; myword wordlist[20]; char *mystring = "the cat in hat jumped on lazy fox"; char *token; token = strtok(mystring, " "); while(mystring != null){ strcpy(wordlist[i], token); token = strtok(null, " "); printf("%s\n", wordlist[i]); i++; } }
the corrected code is
#include <stdio.h> #include <string.h> typedef struct myword{ char word[21]; int length; }myword; int main(void){ int = 0; myword wordlist[20]; char mystring[] = "the cat in hat jumped on lazy fox"; char *token; token = strtok(mystring, " "); while(token != null){ strcpy(wordlist[i].word, token); token = strtok(null, " "); printf("%s\n", wordlist[i].word); i++; } }
- c-string member of struct
word
, must pass memberstrcpy
,printf
- your loop must check
token
returnedstrtok
check if end of string reached strtok
modify string job, string must modifiable, cannot use pointer string literal.
Comments
Post a Comment