IOS Development Series-arrays and strings of c language, ios development-c Array

Source: Internet
Author: User

IOS Development Series-arrays and strings of c language, ios development-c Array
Overview

An array has a special position in C language. It has many features. For example, its storage is continuous, and its name is the address of an array. In C, there is no String type. To represent a String, you must use a String array. Today, we will introduce the following three aspects:

One-dimensional array

The operations on one-dimensional arrays are relatively simple, but note that the array length must be fixed and cannot be initialized using variables. If values are assigned at the same time, the array length can be omitted, the compiler automatically calculates the length of the array. At the same time, the array cannot be declared first and then assigned a value once (each element can be assigned a value one by one ).

# Include <stdio. h> int main () {int len = 2; // int a [len] = {1, 2}; // error, cannot make the variable int a [2]; // correct a [0] = 1; a [1] = 2; // a [2] = 3; // exceeds the array length, but the compiler does not check, run int B ['a'] = {1, 2, 3}; // 'A' = 97, so it can be used as an array length, but the following elements are not initialized, the default value is 0 for (int I = 0; I <97; ++ I) {printf ("B [% d] = % d \ n", I, B [I]);} int c [2*3]; // 2*3 is a fixed value and can be used as an array length int d [] = {1, 2, 3 }; // If values are assigned at the same time during initialization, the array length can be omitted. The current number is 3}
Extended-storage of Arrays

Arrays are stored in a contiguous space in the memory. If you know the array type (int, float, etc.) and initial address, you can know the addresses of other elements, at the same time, because the array name is equal to the address of the first element of the array, when the array is used as a parameter (which can be omitted when used as a parameter), it is actually passed as a reference.

# Include <stdio. h> int main () {int const l = 3; int a [l] = {1, 2, 3}; for (int I = 0; I <l; ++ I) {// since the current 32-bit compiler, the length of the int type is 4 bytes, it can be determined that the differences between the three addresses are 4 printf ("a [% d] = % d, address = % x \ n", I, a [I], & a [I]);}/* current output result: a [0] = 1, address = c9f95c a [1] = 2, address = c9f960 a [2] = 3, address = c9f964 */}

Let's take a look at the storage structure of the defined array in the memory.

Let's take a look at the passing of an array (not an array element, but an array) as a parameter.

# Include <stdio. h> void changeValue (int a []) {a [0] = 10;} int main () {int a [2] = {1, 2}; changeValue (); for (int I = 0; I <2; ++ I) {printf ("a [% d] = % d \ n", I, a [I]);} /* print the result a [0] = 10 a [1] = 2 */}
Multi-dimensional array

Multi-dimensional arrays can be considered as a special one-dimensional array, but each element is a one-dimensional array. Let's take a look at the initialization and assignment of multi-dimensional arrays.

# Include <stdio. h> int main () {int a [2] [3]; // two rows and three columns. a two-dimensional array can be considered as a special one-dimensional array, each element is a one-dimensional array a [0] [0] = 1; a [0] [1] = 2; a [0] [2] = 3; a [1] [0] = 4; a [1] [1] = 5; a [1] [2] = 6; for (int I = 0; I <2; ++ I) {for (int j = 0; j <3; ++ j) {printf ("a [% d] [% d] = % d, address = % x \ n", I, j, a [I] [j], & a [I] [j]) ;}/ * print result a [0] [0] = 1, address = f8fb24 a [0] [1] = 2, address = f8fb28 a [0] [2] = 3, address = f8fb2c a [1] [0] = 4, address = f8fb30 a [1] [1] = 5, address = f8fb34 a [1] [2] = 6, address = f8fb38 * // initialize and assign a value directly to int B [2] [3] = {1, 2, 3 },{ 4, 5, 6 }}; // The Value assignment order of the array is first from the first column of the first row, then the second column of the First row... then the first column in the second row ..., so we can also write the following form as int c [2] [3] = {1, 2, 3, 4, 5, 6}; // You can also initialize only part of the data, the other elements are 0 int d [2] [3] = {1, 2, 3, 4} by default; for (int I = 0; I <2; ++ I) {for (int j = 0; j <3; ++ j) {printf ("d [% d] [% d] = % d \ n", I, j, d [I] [j]) ;}} /* print the result d [0] [0] = 1 d [0] [1] = 2 d [0] [2] = 3 d [1] [0] = 4 d [1] [1] = 0 d [1] [2] = 0 * // Of course, the value assigned below can also be int e [2] [3] = {{}, {4, 5, 6 }}; // The row number can be omitted, but the column number cannot be omitted, because in the order indicated above, it cannot determine how many rows int f [] [3] = {1, 2, 3}, {4, 5, 6 }};}
Extended-multi-dimensional array storage

For example, the structure of array a in the memory is as follows:

Based on the storage of one-dimensional arrays, the following conclusions can be drawn for two-dimensional arrays: the array name is the address of the whole two-dimensional array, which is also the address of the array name in the first line, it is also equal to the address of the first element; the array name of the second row is equal to the address of the first element of the second row. Expression:

Multi-dimensional arrays can be further described here.

String

In C, there is no string type. To represent a string, you need to use an array of the char type, because the string itself is a combination of multiple characters. However, it should be noted that the string is a special array, and a "\ 0" must be added at its end position (0 in ASCII is a null operator, indicating that nothing is done) otherwise, the compiler does not know when the string has ended. When the string value is directly assigned, the program automatically adds "\ 0" as the end character.

//// Main. c // ArrayAndString /// Created by KenshinCui on 14-7-06. // Copyright (c) 2014 Kenshin Cui. all rights reserved. // # include <stdio. h> int main (int argc, const char * argv []) {char a [] = {'k', 'E', 'n','s ', 'H', 'I', 'n', '\ 0'}; printf ("% s", a); // result: Kenshin, note that % s is used to output the string content. If it is replaced with an integer output format, the output address is printf ("\ n"); printf ("address = % x", ); // result: address = 5fbff890 printf ("\ n"); // \ 0 cannot be omitted, if no \ 0 exists, char B [] = {'I', 'A', 'M'}; printf ("% s", B ); // if some junk data is not output as expected, print the result in the current environment: IamKenshin printf ("\ n"); printf ("address = % x", B ); // result: address = 5fbff88d printf ("\ n"); // directly assign a value to a string. You do not need to manually add \ 0, the compiler automatically adds char c [] = "Kenshin"; printf ("c = % s", c); // result: c = Kenshin printf ("\ n "); // two-dimensional array stores multiple strings char d [2] [3] = {"Kenshin", "Kaoru", "Rose", "Jack", "Tom ", "Jerry"}; return 0 ;}

From the code comment above, we can see that "Iam" is printed rather than "IamKenshin" when B is printed, because the compiler cannot determine whether the string ends, to explain why "IamKenshin" is printed, we need to understand the memory storage of a and B.

It is not hard to find that a occupies 8 bytes, and B is defined directly after a is defined. At this time, the allocated space is continuous, and B occupies 3 bytes, in this way, when B is output, the \ 0 mark is not displayed after "Iam" is output, and the program continues to output data until "\ 0" in array a is returned, therefore, the output content is "IamKenshin ".

Extended-string operation common functions

Below are some common functions related to characters and strings.

//// Main. c // ArrayAndString /// Created by Kenshin Cui on 14-7-04. // Copyright (c) 2014 Kenshin Cui. all rights reserved. // # include <stdio. h> int main (int argc, const char * argv []) {/* character operation */putchar ('A'); // result:, putchar can only output one character at a time: printf ("\ n"); putchar (97); // result: a printf ("\ n"); char; a = getchar (); // getchar () can only receive one character at a time. It can receive space, tab, and press ENTER printf ("a = % c", ); printf ("\ n");/* string operation */char B [] = "Kenshin"; prin Tf ("B = % s", B); printf ("\ n"); puts (B); // puts is used to output a single string and cannot format the output like printf, printf ("\ n"); char c [10]; scanf ("% s", c) will be automatically added; // note that c does not need to be written as & c, because the c itself represents the array address printf ("c = % s \ n", c); // note that even if the input content is greater than 10, it can be correctly output, however, the following gets () function does not work with printf ("\ n"); // gets () function. Note that it is not safe, because it is easy to cause overflow when receiving a string, we recommend that you do not use char d [10]; gets (d); // gets can only receive one string at a time, but scanf can receive multiple; scanf can not receive spaces and tabs; gets can be printf ("d = % s", d); printf ("\ n "); char e [] = {'k', 's', '\ 0'}; p Rintf ("% lu", strlen (e); // The result is: 2, not 3, because \ 0 is not included in the length printf ("\ n "); char f [] = {"Kenshin"}; printf ("% lu", strlen (f); // The result is: 7 printf ("\ n "); char g [5]; strcpy (g, "hello, world! "); Printf (" % s ", g); // The result is: hello, even if the defined g length is 5, but it can also be completely copied to printf ("\ n"); char h [5]; char I [] = {'A', 'B', 'C ', '\ 0', 'D', 'E', 'F',' \ 0'}; strcpy (h, I); printf ("% s", h ); // The result is abc. When the first \ 0 is returned, printf ("\ n"); strcat (I, "ghi"); printf ("% s ", i); // The result is abcghi. Note that it is not abcdefghi or strcat. Use "ghi" to overwrite the content from I 1st \ 0, and add \ 0 to overwrite the content, in the memory, it should be: {'A', 'B', 'C', 'G', 'h', 'I', '\ 0 ', 'F', '\ 0'} printf ("\ n"); char j [] = "abc"; char k [] = "aBc "; char l [] = "acb"; char m [] = {'A', '\ 0'}; printf ("% d, % d, % d ", strcmp (j, k), strcmp (k, l), strcmp (l, m )); // if the first character or \ 0 is different, the difference between the two is returned. Result: 32,-33,99 printf ("\ n"); return 0 ;}

Note that gets is not safe in Xcode, because Xcode uses the gcc compiler and cannot compile the gets () function correctly in the gcc compiler. We recommend that you use fgets ().


C character array, input/output string format (for your advice)

% S indicates that a string is output and the given character pointer variable name is str. Then, the system first outputs the first character data it points to, and then automatically adds str to 1, to point to the next character, and then output another character .... So until the end sign '\ 0' is encountered (\ 0 is automatically appended, so the end position of the string can be determined during output )~

In C, the pointer array is different from the string array.

# Include "stdio. h"
# Include "string. h"
Void shellsort (char v [] [10], int n );
Void writeline (char linp [] [10], int n );
Main ()
{
Char line [] [10] = {"C ++", "Fortran", "Basic", "Pascal", "Foxbase "};
Int n = 5;
Shellsort (line, n );
Writeline (line, n );
}

Shellsort (char v [] [10], int n)
{
Char * temp, * t [5];
Int I, j;

For (I = 0; I <n; I ++)
T [I] = & v [I];

For (I = 0; I <N-2; I ++)
For (j = n-1; j> I; j --)
If (strcmp (t [J-1], t [j])> 0)
{
Temp = t [j];
T [j] = t [J-1];
T [J-1] = temp ;}
}

Writeline (char linp [] [10], int n)
{
Int I;
For (I = 0; I <n; I ++)
Printf ("% s \ n", linp [I]);
}
The above is the modified program;
The key lies in
If (strcmp (v [J-1], v [j])> 0)
{T = v [j]; v [j] = v [J-1]; v [J-1] = t ;}
Here v [j] = v [J-1]; this sentence is not correct, because this is two addresses, but also two arrays, can not be assigned a value
I used another set of pointers to point to this array.

The definition of your function is very strange. Even more strange, such definition can also be compiled.
It is recommended that you define it like me. Otherwise, it is very difficult for others to look at the program.

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.