Some basic knowledge of array in C language summary _c language

Source: Internet
Author: User
Tags array length

Initializing an array

int ages[3] = {4, 6, 9};
int nums[10] = {1,2}; The rest is automatically initialized to 0
int nums[] = {1,2,3,5,6};//To determine the number of array elements based on the number of elements in curly braces
int nums[5] = {[4] = 3,[1] = 2};//Specify the number of elements, and give the specified element Initialize
int nums[3]; nums[0] = 1; nums[1] = 2; nums[2] = 3;////First defined, then initialized

Defined but uninitialized, the array has a value, but is a garbage value.
For arrays, once an element is initialized, the other elements are assigned a value of 0.
Calculate the number of elements in an array

int count = sizeof (array)/sizeof (array [0])//Array length = Total bytes occupied by array/number of bytes occupied by array elements

Array considerations

When defining an array [], you can only write integer constants or expressions that return integer constants.

int ages[' A '] = {;

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

int Ages[5 + 5] = {;

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

int ages[' A ' + 5] = {;

printf ("ages[0] =%d\n", Ages[0])

Wrong wording.

No number of elements specified (int nums[] = {1,2,3,5,6}; This is possible, but it is wrong to declare it first and not initialize it.

int a[]; Error

[] cannot put variables in

int number = ten;

int Ages[number]; No error, but no initialization, inside is a random value
  > int number = ten;
  > 
  > int Ages[number] = {19, 22, 33}//Direct error

 -> int ages10[5];
  > 
  > Ages10 = {;  Error. Initialization of a one-time (all assignment) can only be done when the array is defined

-Access array bounds.

Memory allocations for arrays:

Variable in memory is from large to small addressing (in bytes in memory), such as 00000000 00000000 00000000 00001010 in memory, 00001010 addresses are minimal, and arrays are somewhat different, and the elements of the array are naturally stored from top to bottom, The address of the entire array as the head element. (but the bytes that make up the element are the same as the large to the small)

Note: Characters are stored in memory in binary form of the corresponding ASCII value, not in the form of the table above. In this example, the address of the array x is 0x08 the address of its first element, and the address of the array CA is 0x03.
Note the array is out of bounds, and the bounds access to other content (for example, there are two arrays in memory next to each other, the first array may access the elements of the second array), and even the program crashes.

When an array name is used as a function argument, the number of elements in the divisor cannot be dynamically computed in a function because it is automatically converted to a pointer type.

The pointer type defaults to 8 bytes under the 64-bit compiler.

Sometimes we might want to dynamically compute the number of arrays in a function, so we might do this:

void Printmyarray (int myarray[]) {
   int length = sizeof (myarray)/sizeof (myarray[0));
   for (int i = 0; i < length; i++) {
    printf ("%i", Myarray[i]);
   }

int main () {
  int myarray[5] = {1,2,3,4,5};
  Printmyarray (myarray);
  return 0;
}

You can see in the Printmyarray function that we dynamically compute the number of incoming arrays, but the result is wrong because it only outputs the first two digits.

This is because when an array is considered as a parameter of a function, the array is thought of as a pointer, so it is 8 bytes, so the calculated length is 2, so you can only output the first two digits.

Solution: We need to give a new parameter to get length, calculate the length in main (), and then pass in the Printmyarray.

void Printmyarray (int myarray[], int length) {for
  (int i = 0; i < length; i++) {
    printf ("%i", Myarray[i]); 
    

   

The idea of "landfills law":

Give such a question, for example. Requires 6 0~9 digits to be entered from the keyboard, sorted after output.

There are many ways in which the word "landfills" means to first define a 10-digit array (0~9) and initialize it to 0.

Then accept the user's input (which can be used for loops), and the key step is to change the value entered by the user as the subscript for the array, the corresponding value of the subscript to 1 (landfills), and then the For loop output the index in the array with a value of 1.

Space change time, suitable for less data
//  1. Define an array, save the integer that the user entered
//Be  sure to initialize the array, otherwise there may be some random value
  int numbers[10] = {0};  2. Receive user input integer
//  2.1 definition variable to receive user input
  int index =-1;
  for (int i = 0; i < 6; i++) {
    printf ("Please enter%d integer \ n", i + 1);
    scanf ("%d", &index);
The value    entered by the user as an index to modify the corresponding element in the array is 1
//    pointer back to demo just the problem
    numbers[index] = 1;
  }

  int length = sizeof (numbers)/sizeof (numbers[0));
  for (int i = 0; i < length; i++) {
    if (1 = numbers[i]) {
      //Output Index
      printf ("%d", I);
    }
  }

The point of this approach is that the initial values in the array are 0, and the index of the array and the user input number is one by one corresponding, so only the user input number of the corresponding index of the element to 1, and then for the loop output equivalent to the ordered output, and finally get the result.

However, this approach is problematic, such as when a user enters a duplicate number, but the above procedure only outputs the same number once. Our approach is to add up the number of elements of the same index, and then add a layer of loops to output.

  1. Define array, save user input
  int numbers[10] = {0};  2. Receive user input integer
//  2.1 definition variable to receive user input
  int index =-1;
  for (int i = 0; i < 6; i++) {
    printf ("Please enter%d integer \ n", i + 1);
    scanf ("%d", &index);
The value of the corresponding element in the array is modified by the value    entered by the user as an index of 1
//    Assuming the user entered a 1,1,1,2,2,2
    numbers[index] = Numbers[index] + 1;
  }

  int length = sizeof (numbers)/sizeof (numbers[0));
  for (int i = 0; i < length; i++) {
//    j = 1 because if the value stored in the array element is 0 without outputting
//    I corresponding to the elements in the storage space, it is necessary to output several
    for (int j = 1; J <= Numbers[i]; j + +) {
      printf ("%d", I);//1 1 1 2 2 2
    }
  }

Select sort

The main idea is that basically the first element in the default array is the maximum (minimum) value, and then the element is compared to each subsequent element, in order from large to small as an example, when the first value encounters a larger one, it is exchanged. After the first round, the first is the biggest. Then proceed to the second round, from the second number of the first to compare, encounter more than the second number of the exchange, so that after the second round the second number is the second largest, and so on, continue to choose, and finally complete the sorting.

void Selectsort (int numbers[], int length) {for
  (int i = 0; i < length; i++) {for
    (int j = i + 1; J < Leng Th J + +) {
      if (Numbers[i] < numbers[j]) {
        int temp = numbers[i];
        Numbers[i] = numbers[j];
        NUMBERS[J] = temp;

}}} int main (int argc, const char * argv[]) {
  int myarray[] = {7, 1, -3, $};
  int length = sizeof (myarray)/sizeof (myarray[0));
  Selectsort (myarray, length);
  for (int i = 0; i < length; i++) {
    printf ("%i", Myarray[i]);
  return 0;
}

In writing you can think this way: when the first number is compared, i = 0, then J should equal i + 1, because the first number should start with the second number, and compare length-1 times; When i = 1 o'clock, j = 2, and compare length-2 times, and so on; The above is written from large to small sort.

Bubble sort

The main idea is to compare the two adjacent elements to a small to large sort, for example, then the first element begins and the second compares, if the first one is larger than the second, then it is exchanged; then the second and third elements are compared, and so on, after the first round, then the last element of the array is the largest, Analogy

void Bubblesort (int numbers[], int length) {for
  (int i = 0; i < length-1; i++) {for
    (int j = 0; J < Leng Th-i-1; J + +) {
      if (Numbers[j] > numbers[j + 1]) {
        int temp = numbers[j];
        NUMBERS[J] = numbers[j + 1];
        Numbers[j + 1] = temp;
      }

}} int main (int argc, const char * argv[]) {
  int myarray[] = {7, 1, -3, $};
  int length = sizeof (myarray)/sizeof (myarray[0));
  Bubblesort (myarray, length);
  for (int i = 0; i < length; i++) {
    printf ("%i", Myarray[i]);
  return 0;
}

Note that this is different from the choice of sorting, compared to the numbers[i] and numbers[j], but to the comparison of Numbers[j] and numbers[j+1], while the outer loop of I represents the number of rounds to compare, the inner loop is the real each round of the comparison. Here is sorted from small to large.

Binary find

Binary lookup as the name implies, we find the maximum value of the array max, the minimum min to the middle value mid, and then use mid as an array of the corresponding elements, using this element and the target value key to compare:

If Numbers[mid] > key, then the key between Min and Mid, then set Max to Mid-1,min unchanged, and then recalculate mid, repeat the above steps, and finally find the key.

If NUMBERS[MID] < key, then the key between mid and Max, then set min as Mid + 1,max unchanged, and then recalculate mid, repeat the above steps, and finally find the key.

Note that the end condition here, it is possible to have this key in the array, there may not be, then when min > Max, indicating that the array does not have this key, be careful of this situation.

The binary lookup requires that the array be ordered. (Ordered table)

int binsearch (int myarray[], int length, int key) {
  int index =-1;

  int max = length-1;
  int min = 0;
  int mid = (max + min)/2;

  while (min <= max) {
    if (Myarray[mid] > key) {
      max = mid-1;
    } else if (Myarray[mid] < key) {
      min = mid + 1;
    } else if (myarray[mid] = = key) {
      index = mid;
      break;
    Mid = (max + min)/2;
  }

  return index;
}

int main (int argc, const char * argv[]) {
  int myarray[] = { -3, 1, 7, N, $};
  int length = sizeof (myarray)/sizeof (myarray[0));
  int index = Binsearch (myarray, length,);
  printf ("Index:%i", index);
  return 0;
}

First I assume that index =-1 indicates that there is no corresponding value. Then get the value of the Max,min,mid, notice the condition of the while loop, where I use the loop when min <= max, when min > Max jumps out of the loop, indicating that the value of the key was not found. In the loop body, as we just analyzed, when the myarray[mid] = = key shows that we found the value, then the index is set to find the subscript of the value, and then jump out of the loop. index =-1 if no value is found.

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.