简体   繁体   中英

how to use character arrays in strcmp() functions

I initialized a character array with a size of four When I input any character to the character array as

char a[4];
a[1]='z';
printf("The character array is %s\n", a);

The output shows me

The character array is

But then I change a little bit

char a[4];
a[1]='z';
printf("The first character of the array is %s\n", a[1]);

The output shows me

The first character of the array is z

Why is that ? How can I use my character arrays such as if I want them to be compared using strcmp() functions. Please help me....

In the first piece of code, you only set one element of the array. The other three elements are uninitialized. So when you call printf and pass in a it reads those uninitialized bytes. Doing so invokes undefined behavior , which in this case manifests as nothing being printed.

What probably happened in this particular case is that the first element of the array, ie the one with index 0, was probably 0. This value is used to terminate strings, so a was viewed as an empty string.

Also:

The first character of the array is z

No it is not. Arrays in C start with index 0, not index 1.

If you want to copy a string into an array, use strcpy :

strcpy(a, "z");

In this code snippet

char a[4];
a[0]='z';
a[1]='y';
printf("The character array is %s\n", a);

the array does not contain a string (a sequence of characters terminated with a zero character). However you are trying to output it as a string using the conversion specifier %s .

Instead you should write

printf("The character array is %*.*s\n", 2, 2, a);

In this code snippet

char a[4];
a[0]='z';
a[1]='y';
printf("The first character of the array is %c\n", a[0]);
printf("The second character of the array is %c\n", a[1]);

again the array does not contain a string. However you are outputting separate characters. So there is no problem.

If you want to store a string in the array you should append it with zero character. For example

char a[4];
a[0]='z';
a[1]='y';
a[2] = '\0';
printf("The character array is %s\n", a);

The standard C string function strcmp deals with strings. So arrays that you are going to use with this function shall contain strings.

Otherewise you can use another standard function memcmp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM