"c" arrays, strings, pointers

Source: Internet
Author: User

Arrays (one) array

Concept: The construction data type used to store a set of data

Features: Only one type of data can be stored, such as all int or all char, the data in the array becomes an element.

(ii) Definition of an array

Format: type array name [number of elements];

Example: storage age of 5 persons

int agrs[5]; Open up 4x5=20 bytes of storage space in memory

You can initialize an array at the same time you define it:

int ages[5] = {17,18,19,20,21};

To iterate over an array:

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

{

printf ("ages[%d]=%d\n", I,ages[i]);

}

Attention:

(1) Initialization of arrays

①. int ages[5] = {17,18,19,20,21};//General wording

②. int ages[5] = {17,18}; Only the first two elements are assigned a value

③. int ages[5] = {[3]=10,[4]=11}; Assigns a value to the specified element, this is the third and fourth

④. int ages[] = {11,12,13}. Correct, the element on the right is determined, then the number can be omitted here for 3.

⑤. int ages[]; Error, the compiler cannot know how much storage space should be allocated

⑥. int ages[5];ages = {17,18,19,20,21};//error, can only be initialized when an array is defined

⑦. int ages[' A '] = {-N-A}; Correct, equivalent to ages[65]

⑧. int count = 5;int Ages[count]; If it is not initialized, then this is correct, the compiler will not give an error to allocate 20 bytes of storage space, ages[0]=1;ages[1]=2; You can assign a value like this to an array of elements, but the value of an element such as 2,3,4 is indeterminate.

⑨. and int count=5;int ages[count]={1,2,3,4,5}; This is a bad notation, when you define an array, the arrays are initialized, the number of elements must be constant or not written, not a variable

(2) Calculating array elements

How do I traverse an array element if it does not indicate the number of elements in it (requires using the number of array elements)?

You can use the sizeof operator to calculate the number of array elements

int count=sizeof (Ages)/sizeof (int); The total length of the array divided by the length of the element equals the number of elements

(iii) array memory storage details

Suppose there are arrays as follows:

int x[] = {n};

Char ca[5] = {' A ', ' a ', ' B ', ' C ', ' D '};

The array name represents the address of the array, the address of the array = = = Array name (CA) = = The address of the first element of the array &ca[0]

In memory, memory is addressed from large to small, the elements of the array are naturally arranged from top to bottom, and the address of the entire array is the address of the first element, after the arrays have been allocated storage space.

The memory storage details for simulating the array are as follows:

Note: Characters are stored in memory in binary form corresponding to the ASCII value, rather than in the form above.

In this example, the address of the array x is the address of its first element 0x08, and the address of the array CA is 0x03.

(iv) array-address invocation

void change (int array[])//array can be used as a function parameter, you can omit the number of array elements

{

ARRAY[0] = 100;

}

void Change2 (int a)//basic type as formal parameter of function

{

A = 200;

}

int main ()

{

int ages[5] = {1,2,3,4,5};

Change2 (Ages[0]);

Change (ages);

return 0;

}

Array arrays with the address of the ages array, if the array as a function of the parameters, this method of transmission is a call, pass the address of the entire array, modify the value of the parameter group element, is to modify the value of the actual parameter.

When you pass an array as an argument, it is treated as a pointer, using the sizeof operator in the body of the function to calculate the length of the array, the value is always 8, not the actual length of the array, because any type of pointer occupies 8 bytes of storage space.

Tip: When an array is an argument to a function, if the function body involves operations such as array traversal, the actual number of elements of the array is usually passed as a parameter to the function.

such as void Maxofarray (int array[],sizeof (ages)/sizeof (int)) {...}

(v) two-dimensional arrays

int AGES[50]; Arrays can hold data of 50 int types

int ages1[3][10]; The array can hold 3 arrays, each of which holds 10 values, with a total of 3x10=30 of debriefing values.

A two-dimensional array a,a includes two one-dimensional arrays a[0] and a[1], and each one-dimensional array consists of three elements.

Use occasions: Gobang, Tetris, etc.

Assume:

Char y[3][2]={

{' A ', ' B '},

{' C, ' D '},

{' E, ' f '}

};

Memory conditions:

Second, string (i) string basis

Note: The string must end with a.

printf ("yang\n");

Where Yang is a string constant, "yang" = ' y ' + ' a ' + ' n ' + ' g ' + '. Strings consist of a number of characters, usually using a character array to store strings, such as char name[10] = "Yang", or in the form of printf (name), which is the way to access strings through an array, but there is a warning. Because by default, the printf function accepts only string constants as arguments (not the variables).

Three ways to type a string:

    1. Char name[8] = "yang";//Arrays occupy 8 bytes of storage, but contain only 5 characters.
    2. Char Name[8] = {' Y ' + ' a ' + ' n ' + ' g ' + ' \o '};
    3. Char Name[8] = {' Y ' + ' a ' + ' n ' + ' G ' + ' 0 '};

These three types of writing are the same in memory.

Char name[] = {' Y ' + ' a '}; The preceding number is not written, it is not a string, it can be said to be an ordinary character array.

Char name[] = "Yang";

Name[1] = ' o '; changes the value of the second element of a string from a to O.

(ii) Use of the string attention point

(1) Analyze the code to understand the role of the.

Char name[]= "Yang";

Char name2[]={' o ' + ' k '};

printf ("name2=%s", name2);

%s: Print the string according to the parameters on the right (until you have encountered a)

The above code prints the result: Okyang

The following is an analysis of memory conditions:

Ask 1:char name[]= "y\0ng"; print the result why? (Oky)

Q 2: Print the value of name at this time, what is the use of%s? Y\0ng or Y?

(2) Strlen function

The Strlen function calculates the length of a string (the number of characters) but does not include the number of characters. For example, a Chinese character occupies three characters.

strlen ("haha");//Length of 4

strlen ("ha haha");//Length 7 instead of 5

Set

Char name[]= "It\0cast";

strlen (name); The value is 2 because strlen is calculated from the address of the string until it encounters a.

Assume

Char name[]= "Itcast";

Char name2[]={' o ' + ' k '};

int Size=strlen (name);

The value of size at this time is 8.

(3) Practice, write a function char_contains (char Str[],char c), if the string contains the character C, then return 1, otherwise return 0.

int Char_contains (char Str[],char c)

{

Traverse the entire string

for (int i=0,i<strlen (str); i++)

{

if (str[i]==c)

return 1;

}

return 0;

}

Invoke statement

int Result=char_contains ("Yang", ' a ');

Using the While loop

①. while (I<strlen (str))

②. while (str[i]!= ')

③. while (Str[i])

④. int I=-1;while (str[i++])

(c) Array of strings

A two-dimensional character array that stores two string arrays, each with a length of 1, and the following two types of notation, but the storage is the same.

Char name[2][10]={"Jack", "Rose"};

Char name2[2][10]={

{' J ' + ' a ' + ' C ' + ' K ' + ' + '},

{' R ' + ' O ' + ' s ' + ' e ' + ' + '}

}

Output Rose: printf ("%s", name2[1]);

Output k:printf ("%c", name2[0][3]);

Third, the pointer

Preamble Program

1 #include <stdio.h> 2  3 void change (int *n); 4  5 int main () 6  7 {8  9     int a = 90;10 one     Chang E (&a);     printf ("a =%d\n", a), and     return 0;16 (}18) Change (int *n) 20 21 {22 23     

(i) Basic knowledge points

int a = 10;

int *p; Defines a pointer of type int

p = &a; The pointer variable p points to the variable a

*p = 20; The value of variable A is 20 by using the pointer without directly modifying the variable

*p represents access to the storage space that the pointer variable p points to

Pointer one function: Ability to access (value |) According to an address value Assignment) corresponds to the amount of storage space

int in front of pointer variable p, indicating the type of pointer

①. int *p;

②. *p = 10;

Two * difference: the previous function, indicating that the defined p is a pointer, the latter's * represents the address space pointed to by the access P

(ii) Attention to the use of pointers

①. int *p;

Double d = 10.0;

p = &d; This practice is not recommended

②. int *p;

p = 200; Pointer variables can only store addresses

③. int *p;

printf ("%d\n", *p); Pointer variables are uninitialized and do not indirectly access other storage spaces

④. int *p = &a; but cannot be written as int *p;*p=&a; this notation has no meaning and can be thought of as being used with a type character.

⑤. * is a pointer operator that accesses the space pointed to by the pointer

1 #include <stdio.h> 2  3 int main () 4 {5/     * Not recommended, int *p can only point to data of type int 6     int *p; 7      8     Double A = 10.0; 9     p = &a; */12/     * Pointer variable can only store address      int *p;15      p = 200;16      */17     18     /* Pointer variable not initialized, do not indirectly access other storage space     *p;20     ("%d\n", *p);      */23     int A = 10;25     //defines a variable when the * is only a symbol, no other special meaning     int *p= &a;27     //incorrect notation     //*p = &a;30     //This time * function: access to the storage space of the variable p     *p = 20;33     char c = ' A ';     char *CP = &c;36     * cp = ' D '; Notoginseng     printf ("%c\n", *CP);     0;40}

(iii) pointer to pointer

int a = 10;

int *p = &a; Pointer to type int

int **P1 = &p; Pointer to pointer

int ***P2 = &p1; Level Three pointers

*P2 equivalent to visiting P1;

**P2 equivalent to access p;

P2 equivalent to access A;

*P1 equivalent to access p;

A star and a line.

(iv) Hands-on exercises

Write a function that calculates the and difference between A and B (a function returns two values)

Tip: One of the pointers: implementing a function that has multiple return values

1 #include <stdio.h> 2  3 int sumandminus (int n1,int n2,int *n3) 4  5 {6  7    *n3 = n1-n2; 8  9    Return N1 + n2;10 one-}12 int main () () () () (    int) a = 10;18    int b = 11;20    int sum;22 +    int min us;24    sum = Sumandminus (a,b,&minus);    printf ("and =%d, difference =%d\n", Sum,minus); 28 29}

(v) Questions relating to pointers

Note: If a pointer of any type occupies 8 bytes of storage space, why do you add a type to the pointer?

A memory analysis of the following code can prove the serious consequences of incorrect pointer type.

int i = 2;

char c = 1;

int *p = &c; Should be of type char, written as int type

printf ("Value of C is%d\n", *p); The print result is 513, not 1

printf ("C's value is%d\n", c); Value of 1

The following is a memory analysis of the results of the above code:

The pointer p is supposed to be 1 bytes of data, because the pointer is of type int, so the program naturally starts reading 4 bytes of data from the point of Address 0x0a, and the data accessed from 1 becomes 513.

Tip: The data type of the pointer is clarified, and the pointer is able to correctly access the spatial data that should be accessed.

(vi) Pointers and arrays

int ages[5] = {10,9,8,7,6};

Iterating through an array

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

printf ("%d\n", Ages[i]);

Iterating through an array using pointers

int *p;

p = ages;//can also be written as P = &ages[0]; The pointer variable p points to the first element of the array

The address of the element:

Address of the first element P &ages[0]

Address of the second element p+1 &ages[1]

Address of the third element p+2 &ages[2]

The value of the element

*p Ages[0]

* (p+1) ages[1]

* (p+2) ages[2]

Use the pointer as an array:

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

printf ("%d\n", * (P+i));

(1) Three types of access to array elements:

①. Array name [subscript]

②. Pointer variable name [subscript]

③. * (p+1)

(2) How much does +1 of the pointer variable actually add? This depends on the type of pointer, plus 1 bytes if it is a char type, or 4 bytes if it is of type int.

(3) The pointer is used to receive an array, and the pointer variable points to the first element of the array.

void change (int array[]) is equivalent to void change (int *array).

The former is stored as the first address of an array element, but it becomes a pointer when it is passed.

Example:

void change (int *array)

{

printf ("%d\n", array[2]);

printf ("%d\n", * (array+2));

}

int main ()

{

int ages[5] = {1,2,3,4,5};

Change (ages);

}

The result of the call is: the third element of the array 3

If changing to change (&ages[2]), the result of the call is 5, because at this point the array points to ages[2] and ages[2] as the first element of the array.

(vii) Pointers and strings

(1) Basic knowledge

The following two lines of code are essentially different:

①. Char name[] = "it";

②. Char *name2 = "it";//pointer variable name2 points to the first character of the string I

Char name[0] = ' y ';//change the value of the first element

printf ("%s\n", name);//print result for YT

*name2 = ' Y ';

printf ("%s\n", name2);//This time the program crashes

This is because one of the two is a string variable, and the other is a string constant. The C-language array elements are stored on the stack, and the elements inside can be arbitrarily modified, called string variables. The string constants are stored in the constant area and are not changed by the cache.

Char *name1 = "it";

Char *name2 = "it";

printf ("%p%p", name1,name2);//address is the same, stating that name1 and Name2 point to the same string.

There are two ways to master the definition of a string:

①. Using arrays

Features: The characters inside the string can be modified, which is useful when the content needs to be modified frequently.

②. Using pointers

Features: In fact, is a constant string, the characters inside cannot be modified, applicable to the content of the string does not need to be modified, and this string is often used.

(2) Array of pointers

Integer array: This array is an array of integers

Pointer array: This array contains pointers.

int ages[5];

Char *name[5] = {"Jack", "Rose", "Yang"}; Common notation for string arrays

Corresponds to:

Char name2[3][10] = {"Jack", "Rose", "Yang"};

There are two ways to save an array of strings:

①. Array of pointers (array of strings)

②. Two-D character array (array of strings)

How do I enter a string? (using arrays-because they are mutable)

int main ()

{

Char name[20];

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

scanf ("%s", name);

printf ("%s", name);

}

(eight) function that returns a pointer

Examples of programs:

1 #include <stdio.h> 2  3 char *test (); 4  5 int main () 6  7 {8  9     char *name = Test ();     pri NTF ("name =%s\n", name);     return 0;14,}16, Char *test ()//function that returns the pointer. {"     Rose"; 22 23}

(ix) Pointers to functions

The array name is the address of the array, and the function name is the address of the function.

Suppose there are functions:

void Test ()

{

printf ("Call the test function \ n");

}

void (*p) (); The function that the void pointer variable points to does not have a return value, () indicates that the function P points to has no formal parameter

p = test; Pointer p, pointing pointer p to function

There are three ways to manipulate functions:

①. Call test directly ();

②. Call with pointer variable introduction (*P) ();

③. Simplified use P ()

Practice:

Assume that a function is declared as int sum (int a,int b)

The corresponding pointer to the function should be defined as: Int (*p) (int, int);

Point the pointer variable p to the function: p = sum;

There are three ways to call this function:

(1) Int c = P (10,12);

(2) int c = SUM (10,12);

(3) int c = (*p) (10,12);

Suppose the function is declared as: double haha (double a,char *b,int c);

A pointer to the Haha function should be defined as: Double (*p) (double,char *,int) = haha;

"c" arrays, strings, pointers

Related Article

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.