Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c - About string length, terminating NUL, etc

I'm currently learning C and I'm confused with differences between char array and string, as well as how they work.

Question 1:

Why is there a difference in the outcomes of source code 1 and source code 2?

Source code 1:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char c[2]="Hi";
    printf("%d
", strlen(c));   //returns 3 (not 2!?)
    return 0;
}

Source code 2:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char c[3]="Hi";
    printf("%d
", strlen(c));   //returns 2 (not 3!?)
    return 0;
}

Question 2:

How is a string variable different from a char array? How to declare them with the minimum required index numbers allowing to be stored if any (please read the codes below)?

char name[index] = "Mick";   //should index be 4 or 5?

char name[index] = {'M', 'i', 'c', 'k'};   //should index be 4 or 5?

#define name "Mick"   //what is the size? Is there a ?

Question 3:

Does the terminating NUL ONLY follow strings but not char arrays? So the actual value of the string "Hi" is [H][i][] and the actual value of the char array "Hi" is [H][i]?

Question 4:

Suppose c[2] is going to store "Hi" followed by a (not sure how this is done, using gets(c) maybe?). So where is the stored? Is it stored "somewhere" after c[2] to become [H][i] or will c[2] be appended with a to become c[3] which is [H][i][]?

It is quite confusing that sometimes there is a following the string/char array and causes trouble when I compare two variables by if (c1==c2) as it most likely returns FALSE (0).

Detailed answers are appreciated. But keeping your answer brief helps my understanding :) Thank you in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Answer 1: In code 1 you have a char array that is not a string; in code 2 you have a char array that is also a string.

Answer 2: A string is a char array in which (at least) one element has the value 0; if you leave the size part empty, the compiler will automatically fill it with the minimum possible value.

char astring[] = "foobar"; /* compiler automagically uses 7 for size */
printf("%d
", (int)sizeof astring);

Answer 3: a char array in which one of the elements is NUL is a string; a char array where no elements are NUL is not a string.

Answer 4: an array defined to hold two elements (char c[2];) cannot hold three elements. If it is going to be a string it can only be the empty string or a string with 1 character.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...