comparing and defining strings in C -
i looked @ other answers, not able find answer.
want compare last character of string literal "%".
strcpy(ch, fname[strlen(fname) - 1]); printf("%d\n", strcmp(ch, "%")); i want compile cl command line compiler (microsoft), , warnings:
cbx_test1.c(43) : warning c4047: 'function' : 'const char *' differs in levels of indirection 'char' cbx_test1.c(43) : warning c4024: 'strcpy' : different types formal , actual parameter 2 there wrong code, that's obvious. what?
first need consider strings in c, sequences of non-nul bytes followed nul byte, trying copy character strcpy() meant copy strings, that's why compiler complaining.
you can simple assignment, i.e.
char ch; size_t length; length = strlen(fname); ch = fname[length - 1]; and can compare ch '%' character constant this
printf("%d\n", (ch == '%')); note single quotes, wanted possible though not necessary, this
char ch[2]; size_t length; length = strlen(fname); strcpy(ch, &fname[length - 1]); printf("%d\n", strcmp(ch, "%")); notice two characters allocated "%" become string since requires terminating nul byte, %\0, don't need explicitly specify when use string literal "%" since it's implied.
you use memcmp() not necessary in case, think it's interesting mention strcmp() not way compare 2 strings in c, could1
char ch[1]; size_t length; length = strlen(fname); ch[0] = fname[length - 1]; printf("%d\n", memcmp(ch, fname + length - 1, 1)); notice in case terminating '\0' not required because instructing memcmpt() compare 1 byte.
1note fname + length - 1 equivalent &fname[length - 1]
Comments
Post a Comment