Those things in C language

Source: Internet
Author: User
Tags array definition

The number of types of variables stored:

1: Static variable: Any variable declared outside of any fast code is always stored in static memory, that is, memory that is not part of the stack.

For this type of variable. You cannot specify a storage type for them.

2: Stored in the stack, called an automatic variable. Automatic variables are created when the program executes the code that declares the automatic variable.

These automatic variables are destroyed by themselves when the program's execution flow leaves the code.

3: Register variable: The keyword register can be used for the declaration of automatic variables, suggesting that they should be stored in the machine's hardware registers instead of

In memory, such variables are called register variables.

The process of accessing the address it points to through a pointer is called indirect access or dereference pointers. The operator used to perform the indirection is the monocular operator *.

For example, the value of D is 100, and when we use the indirect access operator for D, it means to access memory address 100 and see the value there. Therefore: the City of *d stores

The content,

D is a pointer to an integral type, and the reference operator will produce an integer value. Similarly, indirect access to float * yields a value of type float.

About wild pointers and null pointers:

The following code is an obvious error:

int *a;

...

*a=12;

This declaration creates a pointer variable called a, and the subsequent assignment statement stores 12 in the memory location pointed to by a.

Warning:

But where exactly is a? We declare this variable, but we never initialize it, so we have no way to predict where 12 of this direct talk is stored.

From this point of view, there is no difference between pointer variables and other variables. If the variable is static. He will be initialized to 0. However, if the variable is automatic, it will not be initialized at all.

Null pointer:

#include "stdio.h"

int main ()

{

printf ("%d\n", NULL);//0

}

The standard defines a null pointer, which acts as a special pointer variable that does not point to anything. If a pointer variable is NULL, you can assign it a value of 0. To test

If a pointer variable is NULL, you can compare it to a value of 0. The 0 value is chosen because of a source code contract. Within the machine, the actual value of the null pointer may

differs from this. In this case, the compiler will be responsible for the conversion between the 0 value and the internal value.

The concept of a null pointer is very useful because it gives you a way to represent a particular pointer present and to anything. For example: A function to find a specific value in an array,

May return a pointer to an array element that is found. If the array does not contain a value for the specified condition, the function returns a null pointer, which allows the return value to convey information for two different fragments.

First, are there any elements found? Second, if found, which element is it?

Although this technique is very common in C programs. But he violates the principle of software engineering, it is very dangerous to express two different meanings with a single value, because it is very easy for the future to

Figure out which is the real intention. In a large program, this problem is more serious, because you can not in the mind of the entire design, a more convenient strategy is to let the function return two independent values. :

The first is a status value that indicates whether the lookup was successful, followed by a pointer, and when the status value prompt finds success, it points to the element to find.

A pointer can be dereferenced to get the value it points to. But in terms of definition, a null pointer is made to everything. Therefore, it is illegal to dereference a null pointer.

Before you can dereference a pointer, you must determine that it is not a null pointer.

Warning: What happens if you have indirect access to a null pointer? This is dependent on the compiler. On some machines, it accesses the memory location zero, so that it can ensure that the memory location is zero

No variables are stored, but the machine does not prevent you from accessing the location, which is unfortunate because the program contains an error, but the machine hides its symptoms, making the error difficult to find.

On other machines, indirect access to a null pointer throws an error and terminates the program. It is much better to announce this error than to hide it, because it is easier for programmers to fix it.

Tips:

It would be a blessing if all pointer variables (not just pointer variables in static) could be initialized to NULL, but that is not the case. Regardless of how your machine reacts to the behavior of dereferencing a null pointer, the initialization of all pointer variables to display is the best practice. If you already know that the pointer will be initialized to the address of the type, initialize it to that address, or initialize it to null. A well-styled program checks it before it is dereferenced. This initialization strategy can save a lot of debugging time.

Pointer:

*&a=25;

The meaning of this code is: Assign the value 25 to the variable A.

First, the & operator generates the address of the variable A, which is a pointer constant (note: The pointer does not need to know its actual value), and then the * operator accesses the address indicated by its operand. In this expression, the operand is the address of a, so the value 25 is stored directly in a.

Another big difficulty:

Assuming that variable a is stored in position 100, the following statement is used:

* 100=25;

It goes up like assigning a value of 25 to a, because a is a variable stored in position 100. However, this is wrong.

This statement is illegal. Because the type of literal value 100 is an integer, the indirect access operation can only be used for pointer type expressions. If you do want to store 25 in location 100, you must use coercion type conversion.

* (int *) 100=25;

Forcing a type conversion converts the value 100 from "Integer" to "integer pointer", so that indirect access to it is legal. If a is stored in position 100, then this statement is to store the value 25 in a.

Calculates the length of a string

#include "stdio.h"

#include "Stdlib.h"

strlen (char *string)

{

int length=0;

/*

* Access the contents of the string in turn, counting the number of characters until a null terminator is met.

*/

while (*string++!= ')

{

Length+=1;

}

return length;

}

2: About the input and output of the string:

In the C language, there is no string type, and a character array is used to process the string.

Character Array Definitions:

char array name [constant expression] [, [constant expression]];

Description: A one-dimensional character array for storing and processing a string, a two-dimensional character array for storing and processing multiple strings at the same time;

Because character types and integers are common, you can use int to define character arrays, but there are differences, such as:

Char c[10]; /* occupies 10 bytes in memory */

int c[10]; /* occupies 40 bytes in memory */

Input/Output method: Char-per-character input output:%c, entire string input output:%s

One: Using the scanf () input string, the printf () output string:

Character Processing:

#include "stdio.h"

void Main ()

{char ch[5];

int i;

for (i=0;i<5;i++)

scanf ("%c", &ch[i]);

for (i=0;i<5;i++)

printf ("%c", Ch[i]);

}

Entire string processing:

#include "stdio.h"

void Main ()

{char ch[5];

scanf ("%s", ch);

printf ("%s", ch);

}

Description

Use the array name directly when processing in string, without &;

When entering a string, the number of characters is less than the length of the array, such as entering 5 characters, the defined character array should have at least 6 elements;

Enter the string, if a space or carriage return, enter the end, and automatically after the string to add the end of the sign ' \ n ';

When the string is output, the end of the string is encountered and the output ends.

Two: Using string processing function input and output

Prototype of a string standard function in the header file String.h (add #include <string.h>) to the header file when using string processing functions for input and output

String output function puts

Format: puts (character array)

Function: Output A string to the display (output, auto-wrap, ie ' \ n ' replaces '/')

Description: The character array must end with '/'

String input function gets

Format: Gets (character array)

Function: Enter a string in the character array from the keyboard input with the end of the carriage return, and automatically add '% '

Note: The input string length should be less than the number of character array dimensions, the string can contain spaces

For example:

#include <stdio.h>

#include <string.h>

void Main ()

{

Char str[10];

int i;

printf ("Please enter string: \ n");

Gets (str);

printf ("string entered is: \ n");

Puts (str);

}

Array:

The size of the definition array must use an integer constant or an integral constant expression. The variable is not allowed to be dynamically defined in the C language in the following table Form. For example: The following array definition statement:

Short score[100]; The right definition form

and

Short Score[n]; Incorrect way of defining

is illegal, even if an assignment statement is assigned to n before the statement in the array definition, or the N value is entered using scanf (), the above statement is also illegal.

about using scanf to enter data maybe you have a lot of questions, here is a brother Siang (Zy) on my doubts about the explanation.

Zy: The essence of a string is a char*. scanf input string, that is, to the specified location, is actually

I: But ch[5] does not define a five-character array, I enter more than five and less than 10 programs will not stop.

Here's a case for you:

int a=99,b=99;
float c=9999,d=99.99;
scanf ("%d%d%f%f", &a,&b,&c,&d);

Printf ("%d%d%f%f\n", a,b,c,d);
When the input is: 1.23 4.5 6.7, do you know how these four variable values change?

Because it is not sure of its results, in the VC environment under commissioning:

When I enter from the keyboard: 1.23 4.5 6.7 (carriage return),

The output is: 1 99 9999.000000 99.989998

For the output after the decimal point: floating point data, there are six digits after the decimal point, it varies with the operating system, not the exact number, not the direct complement 0.

But why the third number can be the exact output, after the decimal point is all 0, and the fourth number why the number after the decimal point is those?

Because the one you entered is 9999, it has no input after the decimal point, so the natural complement 0

Since float is the system default to 6-bit valid digits, float is a single-precision
Doubles are double and can be up to 16 bits.

It can be seen from the results of the calculation:

A was rewritten. After the type mismatch, scanf is automatically terminated.
But now the problem is that obviously the 1 was read away, knocking at the back of that part of the content?

Or so, where's this 56 going?

Why is it that when you enter 12 (space) 34 (space) 56 (space) from the keyboard, why does the program not wait for the user to enter C and output the execution result directly?

Just this, obviously a start to two number, knocked three, one more
And the second time required to input C, the program did not stop, did not let the input, directly passed

But what is the reason for this:

Because the scanf statement you only let input two data A and B, but you input on the keyboard directly entered three integers, actually scanf ("%d", &c), has been executed, input: 12 34 56 is equivalent to direct 56 to C, Such execution is equivalent to executing two lines of scanf statements, but in the process of writing the program, this input method is not

advocated.

Add:

For scanf ("%d%d", &a,&b), the format character in double quotation marks, if you add a space in the middle of two%d, you must strictly follow the form of scanf when typing on the keyboard, such as: 12 (space) 34, but if the scanf () This statement is modified to: scanf ("%d%d", &a,&b), then on the keyboard when entered in the two int type of number, you can enter any space, carriage return, or tab shuttlecock as a separator between two data. Therefore, when using the scanf statement, there is only a format character between the double quotation marks. Write the code directly in double quotes, and don't write a space.

, all the things that scanf input are written into memory first and then placed in the variable. Although these three auto variables are also in memory, it is strange to say so.

The scanf corresponding to that is called the stdin standard input stream, and everything you tap is placed in the standard input stream sequentially.

scanf ("%d%d", &a,&b);

First write the thing you hit stdin, and then convert the data from stdin to the specified type (the first is%d), that is, the input character stream 12 is converted to type int 12, write to the specified location (the first%d corresponds to the &a)

Input stream content is 12 34 56
The input format is specified as%d%d, which means that an integer is
Based on the greedy method, 1 is an integer, legal, 12 is an integer, legal; 12 spaces are illegal.
Then%d corresponds to 12, converts the character stream 12 to the Int 12, and writes to the variable a

Those things in C language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.