C 數(shù)組

2018-05-19 18:00 更新

學(xué)習(xí)C - C數(shù)組

什么是數(shù)組?

數(shù)組包含固定數(shù)量的具有相同類型的數(shù)據(jù)項。

數(shù)組中的數(shù)據(jù)項被稱為元素。

我們在名字之后放置一個方括號 [] 之間的數(shù)字。

long numbers[10];

方括號之間的數(shù)字定義了數(shù)組包含的元素數(shù)量。

它被稱為數(shù)組維。

數(shù)組索引值從零開始,而不是一個。

以下代碼顯示如何平均存儲在數(shù)組中的十個等級。


#include <stdio.h>

int main(void)
{
  int grades[10];                          // Array storing 10 values
  unsigned int count = 10;                 // Number of values to be read
  long sum = 0L;                           // Sum of the numbers
  float average = 0.0f;                    // Average of the numbers

  printf("\nEnter the 10 grades:\n");      // Prompt for the input

  // Read the ten numbers to be averaged
  for(unsigned int i = 0 ; i < count ; ++i)
  {
    printf("%2u> ",i + 1);
    scanf("%d", &grades[i]);               // Read a grade
    sum += grades[i];                      // Add it to sum
  }

  average = (float)sum/count;            // Calculate the average
  printf("\nAverage of the ten grades entered is: %.2f\n", average);
  return 0;
}

上面的代碼生成以下結(jié)果。



我們可以使用[]語法定義數(shù)組。

例如,我們定義int和char的數(shù)組。

int number [5];char chars [10];

我們也可以從struct構(gòu)造數(shù)組。

  struct employee{ 
      int id; 
      char name[10]; 
      char country[5]; 
  }; 

  struct employee list[5]; 

例子

以下代碼顯示數(shù)組中的所有值。

您可以通過索引訪問數(shù)組元素值。


#include <stdio.h>

int main(void)
{
  int grades[10];
  unsigned int count = 10;                 // Number of values to be read
  long sum = 0L;                           // Sum of the numbers
  float average = 0.0f;                    // Average of the numbers

  printf("\nEnter the 10 grades:\n");      // Prompt for the input

  // Read the ten numbers to be averaged
  for(unsigned int i = 0 ; i < count ; ++i)
  {
    printf("%2u> ",i + 1);
    scanf("%d", &grades[i]);               // Read a grade
    sum += grades[i];                      // Add it to sum
  }
  average = (float)sum/count;              // Calculate the average

  for(unsigned int i = 0 ; i < count ; ++i) {
    printf("\nGrade Number %2u is %3d", i + 1, grades[i]);
  }
  printf("\nAverage of the ten grades entered is: %.2f\n", average);
  return 0;
}

上面的代碼生成以下結(jié)果。


例2

聲明一個數(shù)組后,我們可以設(shè)置并獲取數(shù)組。


  #include <stdio.h> 

  struct employee{ 
      int id; 
      char name[10]; 
      char country[5]; 
  }; 

  int main() { 
      // define array 
      int numbers[5]; 
      char chars[10]; 
      struct employee list[5]; 

      // insert data 
      int i; 
      for(i=0;i<5;i++){ 
          numbers[i] = i; 

          list[i].id = i; 
          sprintf(list[i].name,"usr %d",i); 
          sprintf(list[i].country,"DE"); 
      } 
      sprintf(chars,"hello c"); 

      // display data 
      for(i=0;i<5;i++){ 
          printf("%d %c\n",numbers[i],chars[i]); 
          printf("struct. id: %d, name: %s, country : %s \n", 
                  list[i].id,list[i].name,list[i].country); 
      } 
      printf("%s\n",chars); 

      return 0; 
  } 

上面的代碼生成以下結(jié)果。

運(yùn)算符地址

運(yùn)算符的地址&,返回其操作數(shù)的存儲器地址。

以下代碼顯示如何輸出一些變量的地址:


    #include<stdio.h>

    int main(void)
    {
      // Define some integer variables
      long a = 1L;
      long b = 2L;
      long c = 3L;

      // Define some floating-point variables
      double d = 4.0;
      double e = 5.0;
      double f = 6.0;

      printf("A variable of type long occupies %u bytes.", sizeof(long));
      printf("\nHere are the addresses of some variables of type long:");
      printf("\nThe address of a is: %p  The address of b is: %p", &a, &b);
      printf("\nThe address of c is: %p", &c);
      printf("\n\nA variable of type double occupies %u bytes.", sizeof(double));
      printf("\nHere are the addresses of some variables of type double:");
      printf("\nThe address of d is: %p  The address of e is: %p", &d, &e);
      printf("\nThe address of f is: %p\n", &f);
      return 0;
    }

上面的代碼生成以下結(jié)果。

數(shù)組和地址

這是一個包含四個元素的數(shù)組的聲明:

long number[4];

數(shù)組名稱 number 用于標(biāo)識數(shù)組的內(nèi)存地址。

索引值表示數(shù)組元素內(nèi)存地址的偏移量。

以下代碼為數(shù)組中的每個元素設(shè)置一個值,并輸出每個元素的地址和內(nèi)容:


#include <stdio.h>

int main(void)
{
    int data[5];
    for(unsigned int i = 0 ; i < 5 ; ++i)
    {
      data[i] = 12*(i + 1);
      printf("data[%d] Address: %p  Contents: %d\n", i, &data[i], data[i]);
    }
    return 0;
}

上面的代碼生成以下結(jié)果。

初始化數(shù)組

要初始化數(shù)組的元素,請在括號中指定初始值,并在聲明中用逗號分隔。

例如:

double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };

如果初始值比元素少,則不初始化值的元素將被設(shè)置為0.因此,如果寫入:

double values[5] = { 1.5, 2.5, 3.5 };

前三個元素將用大括號之間的值初始化,最后兩個元素將被初始化為0。

要將整個數(shù)組初始化為零,請?zhí)峁┮粋€值為0的元素:

double values[5] = {0.0};

然后將使用0.0初始化整個數(shù)組。

當(dāng)您指定初始值列表時,可以省略數(shù)組的大小。

編譯器將假定元素的數(shù)量是列表中的值的數(shù)量:

int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

數(shù)組的大小由列表中初始值的數(shù)量決定。

查找數(shù)組的大小

sizeof 運(yùn)算符計算變量占用的字節(jié)數(shù)。

您可以將 sizeof 運(yùn)算符應(yīng)用于類型名稱,如下所示:

printf("The size of a variable of type long is %zu bytes.\n", sizeof(long));

sizeof運(yùn)算符也使用數(shù)組。

假設(shè)您使用以下語句聲明一個數(shù)組:

double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };

您可以使用以下語句輸出數(shù)組占用的字節(jié)數(shù):

printf("The size of the array, values, is %zu bytes.\n", sizeof values);

這將產(chǎn)生以下輸出:

The size of the array, values, is 40 bytes.

因此,您可以使用 sizeof 運(yùn)算符來計算數(shù)組中的元素數(shù)量:

size_t element_count = sizeof values/sizeof values[0];

element_count 的類型為 size_t ,因為sizeof運(yùn)算符產(chǎn)生size_t類型值。

可以將sizeof運(yùn)算符應(yīng)用于數(shù)據(jù)類型,以下代碼返回雙維數(shù)組的數(shù)組維度。

size_t element_count = sizeof values/sizeof(double);

用于計算數(shù)組長度或維度的完整源代碼如下。


#include <stdio.h>

int main(void)
{
    double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };
    size_t element_count = sizeof(values)/sizeof(values[0]);
    printf("The size of the array is %zu bytes ", sizeof(values));
    printf("and there are %u elements of %zu bytes each\n", element_count, sizeof(values[0]));

    return 0;
}

上面的代碼生成以下結(jié)果。

例3

當(dāng)您使用循環(huán)來處理數(shù)組中的所有元素時,可以使用sizeof運(yùn)算符。

例如:


#include <stdio.h>

int main(void)
{
    double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };
    double sum = 0.0;
    for(unsigned int i = 0 ; i < sizeof(values)/sizeof(values[0]) ; ++i){
      sum += values[i];
    }
    printf("The sum of the values is %.2f", sum);

    return 0;
}

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號