Today's questions about cross-border problems and return value problems

foreword

1. What's wrong with the following code

(1) Answers to questions

2. Why does the main function return 1?

(2) Answers to questions

Summarize


foreword

Learning programming language is like an ocean, there are too many knowledge points that need to be known, understood, and learned. Today I will share two little knowledge.


1. What's wrong with the following code

int main()
{
   char szstr[10];
   strcpy(szstr, "0123456789");

}

(1) Answers to questions

1) The first problem is that it is out of bounds. The array szstr has only 10 spaces, and the number characters 0~9 also have 10 spaces. Another thing to note is that \0 occupies a space, so the space of the array is not enough.

2) Advanced compilers do not allow the use of strcpy, thinking it is unsafe; for example, VS, etc., and when you follow the prompts to change, you will find that the compiler recommends using strcpy_s, which has three parameters, and the second is the number of copies. Then this can effectively avoid the out-of-bounds problem. If the number filled in exceeds the capacity of the array, the compilation will not pass.

2. Why does the main function return 1?

int main()
{
int x=3;
printf("%d",x);
return 1;

}

(1) Answers to questions

In the C standard, it is considered that 0 means success, and non-zero means failure. The value returned here will give us a prompt message to see if the code exits normally. Therefore, in the main function, we are used to writing return 0 to indicate that the code exits normally, and to indicate that the others exit abnormally, indicating that there is a problem with the code.  


Summarize

The above is what I want to share with you today. Although it is a relatively small point, it does not add up to a thousand miles. Come on!

Guess you like

Origin blog.csdn.net/weixin_62456756/article/details/128336066