Quick C language manual (III): array, String, Structure

Source: Internet
Author: User

Definition, initialization, and use of one-dimensional arrays
The format for defining a one-dimensional array is as follows:
Type array name [array size];
The subscript range of an array always starts from 0 (therefore, the maximum subscript is one minus the array size ). The following statement defines a 10-type long integer array:
long value[10];
This is equivalent to the following Pascal statement:
var value:array[0..9]of longint;
The left endpoint of the array range in C language cannot be customized. Its Array subscript can only start from 0.

The following methods can be used to initialize an array:
long value[10] = { 0, 8, 2, 0, 3 } ;
long value[10] = { [1]=8, [2]=2, [4]=3 } ;
The preceding two statements are equivalent. The previous method first assigns values to the first five digits of the array in sequence, and the latter method initializes only the three positions of the array. The value corresponding to the subscript not involved in the initialization is automatically set to 0.
The C language allows the array size to be a variable, but such an array cannot be initialized as above during definition.
This initialization method is only used when defining arrays and cannot be used for value assignment in programs. Arrays cannot be directly assigned values. You cannot assign array a to array B.

The array method in the program is the same as Pascal. The following program will output a prime number of less than 1000:
#include <stdio.h>
#include <stdbool.h>
int main()
{
   bool isPrime[1000];
   int i,j;
  
   for(i=2;i<1000;i=i+1)
      isPrime[i]=true;
      
   for(i=2;i<1000;i=i+1)
   {
      if (isPrime[i])
      {
          printf("%d ",i);
          for(j=2*i;j<1000;j=j+i)
             isPrime[j]=false;  
      }
   }
  
   return 0;
}

When a one-dimensional array is used as a function parameter, the array size can be left blank to adapt to arrays of different lengths. You usually need another parameter to tell the function how big your array is. The following function returns the maximum value in the array:
long maxValue ( long length, long array[] )
{
   long i, max = 0;
   for ( i=0; i<length; i=i+1)
      if (array[i]>max) max = array[i];
   return max;
}

The following code legally calls the above function.
long a[5] = { 1, 5, 7, 3, 4 };
printf( "%d" , maxValue( 5,a ) );

String in C Language
The C language also uses character arrays as strings. Defining a char a [20] is equivalent to defining a string of no more than 20 characters. Pascal uses a [0] to record the length of a string. The content of a string starts from a [1]. However, C does not directly record the length of a string. A [0] indicates the first character of a string, finally, the string ends with an ascii code 0 (or a character '/0. You can directly assign a string to a character array, or use the % s identifier in printf to output a character array. Remember, a [2] indicates the third character in the string, because the array subscript of C starts from 0.
Observe the following code:
int i;
char a[20]="matrix67.com";

for (i=0;i<20;i=i+1)
   printf("%d ",a[i]);
printf("/n%c/n",a[2]);
printf("%s/n",a);
printf("%16s/n",a);
printf("%.8s/n",a);
printf("%16.8s/n",a);

Program output:
109 97 116 114 105 120 54 55 46 99 111 109 0 0 0 0 0 0 0 0
t
matrix67.com
    matrix67.com
matrix67
        matrix67

The = or + operator is invalid for the string.

The following function returns the number of characters in a string:
int stringLength( char a[] )
{
   int count=0;
   while ( a[count] )
      count=count+1;
   return count;
}

If the string is too long when you assign a value, you can use either of the following methods to write the string. First, add a backslash at the end of the line to indicate the connection to the next line. Second, each line is marked with double quotation marks (the compiler will automatically connect it ). The following two codes are equivalent. Note that the second line in the first code must be written in the top level; otherwise, the space before the second line must be included in the string.
char blogTitle[100]="Matrix67: My Blog - 50% Informatics, 50% /
Mathematics, and 50% Imagination";

char blogTitle[100]="Matrix67: My Blog - 50% Informatics, 50% "
                 "Mathematics, and 50% Imagination";

Like an array, the value assignment to a string can only be used for definition, but not in a program.

Definitions, initialization, and usage of multi-dimensional arrays
The format for defining a multi-dimensional array is as follows:
Type array name [size 1] [size 2]... [size N];
For example, the following statement defines a three-dimensional array:
int matrix[100][100][2];
Similarly, the size of each dimension starts from 0. Therefore, the preceding statement is equivalent:
var matrix:array[0..99][0.99][0..1]of integer;

The initialization of multi-dimensional arrays is similar to that of one-dimensional arrays. For example, we often need to define the direction constant:
const int dir[4][2] = { {1,0},{0,1},{-1,0},{0,-1} };
This can also be directly written:
const int dir[4][2] = { 1, 0, 0, 1, -1, 0, 0, -1 };
The initialization of multi-dimensional arrays is also undefined. Therefore, it can be written as follows:
const int dir[4][2] = { [0][0]=1, [1][1]=1, [2][0]=-1, [3][1]=-1 };

When using multi-dimensional arrays in the program, multiple square brackets must be used. That is, dir [2] [1] cannot be written as dir [2, 1].

When a multi-dimensional array is used as a function parameter, only the size of the first dimension can be left empty. Therefore, the first two of the following three functions are valid, and the third is invalid.
long function_1( int m, int n, long a[20][20] );
long function_2( int m, int n, long a[][20] );
long function_3( int m, int n, long a[][] );

To make parameters still apply to arrays of various sizes, the C language allows defining functions like this:
long function_4( int m, int n, long[m][n] );
For example, the following function recursively calculates the determinant:
long determinant( int n, long a[n][n] )
{
    if (n==1) return(a[0][0]);
    
    int i,j,k;
    long ans = 0;
    long sub[n-1][n-1];
    
    for ( i=0; i<n; i=i+1 )
    {
        for ( j=1; j<n; j=j+1 )
        {
           for ( k=0; k<i; k=k+1 )
              sub[j-1][k]=a[j][k];
           for ( k=i+1; k<n; k=k+1 )
              sub[j-1][k-1]=a[j][k];
        }
        ans = ans + (1-i%2*2)*a[0][i]*determinant(n-1, sub);
    }
    return ans;    
}

The following code snippet correctly calls the above function:
long a[4][4]={
               { 1, 4, -1,  4 },
               { 2, 1,  4,  3 },
               { 4, 2,  3, 11 },
               { 3, 0,  9,  2 }
             };
printf( "%d" , determinant(4,a) );

Structure definition, initialization, and usage
The record type in Pascal is called "structure" in C language ". You can define a structure as follows:
Struct structure name
{
Several variables (fields) are defined here)
};

Note that the curly braces must be followed by a semicolon. The following defines a date structure:
struct date
{
   int year;
   short month,day;
};

In this way, you get a type name named struct date. Like the definition of variables, the definition of a structure can only be used later in the current function (the current statement block. Therefore, the structure definition is usually placed before all functions as a global definition. Then, you can write the following statement:
struct date today;

The structure is used in the same way as Pascal's record type. For example, the following function is used to calculate the day of a day (Zeller formula ):
int zeller( struct date t )
{
   if (t.month<3)
   {
      t.year = t.year - 1;
      t.month = t.month + 12;
   }
   int c = t.year / 100;
   int y = t.year % 100;
   int ans = ( c/4 - 2*c + y + y/4 + (26*(t.month+1))/10 + t.day - 1 ) % 7;

   if (ans>0) return ans;
   else return ans+7;
}

Assigning an initial value to a structure is similar to array initialization. The following two statements are equivalent:
struct date myBirthday = { 1988, 5, 16 };
struct date myBirthday = { .year=1988, .month=5, .day=16 };
This method can also be used for value assignment in the program, but a type conversion is required (see the "term usage" section here ). For example, the following three code snippets are equivalent:
myBirthday.year = 1988;
myBirthday.month = 5;
myBirthday.day = 16;

myBirthday = (struct date){ .year=1988, .month=5, .day=16 };
myBirthday = (struct date){ 1988, 5, 16 };
The following statement calls the Zeller function and outputs the day of the week for every 13 days since January 1, 1583. This article has nothing to do with: Does anyone know why I started to calculate it from 1583?
int y,m;
for ( y=1583; y<=2000; y=y+1)
   for ( m=1; m<=12; m=m+1 )
      printf( "%d ", zeller( (struct date){y,m,13} ) );

Matrix67 original
Please indicate the source of the post

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.