#include <stdio.h>To break it down a bit...
int main() {
char * first_name = "John"; /* using pointer */
char last_name[] = "Doe"; /* using local array */
char name[100];
/* comparing strings */
if (strncmp(first_name, "John") != 0) return 1;
if (strncmp(last_name, "Doe") != 0) return 1;
sprintf(name, "%s %s", first_name, last_name);
return 0;
}
The first_name variable is set as a pointer, which means that we can view it but not alter it. The last_name variable is set as a local array, which means we can also alter it. We can alter the last_name in whole or in part since it is constructed as an array.
last_name[] = "Smith"; /* this would change the whole last name to `Smith` */You may be asking yourself, why is the array bracket empty? Well, it doesn't have to be. When it's left empty we allow the system to determine the number of characters. The thing to remember is that the number of characters will be one more than the string that you are defining. This is because in C you need to leave room for string termination. Therefore...
last_name[0] = "R"; /* this would change the first character in the last name, so that the last name becomes `Roe` */
char last_name[] = "Doe";
/* would be the same as */
char name[4] = "Doe";
The `strncmp` that we used to compare strings earlier could have taken on an additional argument - how many characters to compare. So that if we wanted to compare only the first three charaters of the first_name variable we could have done...
if (strncmp(first_name, "Joh", 3) != 0) return 1;
No comments:
Post a Comment