SlideShare a Scribd company logo
C Programming
Lecture 14
Arrays
What is an Array?
• An array is a sequence of data items that are:
– all of the same type
• a sequence of integers, or a sequence of characters, or a sequence
of floats, etc.
– indexible
• you can indicate or select the first element or second element
or ...
– stored contiguously in memory
• each element of the sequence is stored in memory immediately
after the previous element
One-Dimensional Arrays
• Declaration of a one-dimensional array.
– int grade[3];
• Provides space in memory to store three grades (as in grades on
three of your quizzes)
• Example of Assignments
grade[0] = 95; /* 1st element index is 0 */
grade[1] = 88; /* 2nd element index is 1 */
grade[2] = 97; /* 3rd element index is 2 */
Accessing Array Elements
• The following code segment will print the three grades stored
in the array on the previous slide (assume i has been declared
as an int variable):
for (i = 0; i < 3; ++i)
printf(“Grade %d is %dn”, i, grade[i]);
• Output
Grade 0 is 95
Grade 1 is 88
Grade 2 is 97
Arrays and Pointers
• An array name is also the name of a pointer constant to the
base address (beginning) of the array in memory.
• Using “made up” addresses (as we have before in discussing
pointers):
95 88 97
grade 1000 1004 1008 < addresses in memory
0 1 2 < index of array element
values stored in
each element
The address stored in grade would be 1000
Using a Symbolic Constant
as the Size of the Array
• It is considered good programming practice to define
the size of an array as a symbolic constant:
– In the next example, if the size of a class changes then the
symbolic constant at the top of the program is easily
changed.
– The program would then be recompiled so it can be used
with the larger array of grades.
Example of Entering Values into an Array, then Displaying the Values
#include <stdio.h>
#define N 20 /* Number of students in class */
int main(void)
{
int grade[N]; /* declare array with N elements */
int i;
/* Enter the grades for a quiz */
for (i = 0; i < N; ++i) {
printf(“Enter quiz grade %d: “, i + 1);
scanf(“%d”, &grade[i]);
}
/* display the grades that were entered */
printf(“Here are the grades that were enteredn”);
for (i = 0; i < N; ++i)
printf(“Grade %d is %d”, i + 1, grade[i]);
}
Note that the user is shown grades starting with grade 1,
but what the user thinks of as grade 1 is stored in
grade[0] in the array.
Initialization of Arrays
As with simple variables, arrays can be initialized within a
declaration.
– An array initializer is a sequence of initializing values written as a
brace-enclosed, comma-separated list.
float x[4] = {-1.1, 0.2, 33.0, 4.4};
x[0] is initialized to -1.1
x[1] is initialized to 0.2
etc.
More on Initialization of Arrays
• If a list of initializers is shorter than the number of array
elements, the remaining elements are initialized to zero.
• If an external or static array is not initialized, then the system
automatically initializes all elements to zero.
• Uninitialized automatic and constant arrays start with
garbage values -- whatever happens to be in memory when
the array is allocated.
Declaring and Initializing
an Array Without a Size
• If an array is declared without a size and is initialized to a
series of values, it is implicitly given the size of the number of
initializers.
int a[] = {3, 4, 5, 6};
is equivalent to
int a[4] = {3, 4, 5, 6};
Range of Values
Allowed for a Subscript
• Assume a declaration:
int i, a[size];
• To access an element of the array, we can write
a[expr], where expr is an integral expression.
• expr is called a subscript and the value of the
subscript must lie in the range 0 to size - 1.
“Subscript Out of Bounds”
• If a subscript from the previous example lies outside
the range 0 to size - 1 then:
– A run-time error occurs.
– The system will stop executing your program and display a
message such as “subscript out of bounds”.
– Sometimes no error message is displayed, but your
program will begin to produce unexpected results.
Relationship Between
Arrays and Pointers
• An array name represents the address of the beginning of the
array in memory.
– When an array is declared, the compiler must allocate a base address
and a sufficient amount of storage (RAM) to contain all the elements
of the array.
– The base address of the array is the initial location in memory where
the array is stored.
• It is the address of the first element (index 0) of the array.
Passing Arrays to Functions
• In a function definition, a formal parameter that is
declared as an array is actually a pointer.
– When an array is passed, its base address is passed call-by-
value.
– The array elements themselves are not copied.
– As a notational convenience, the compiler allows array
bracket notation to be used in declaring pointers as
parameters.
Example of Passing an Array to a Function
int sum(int a[], int n) /* n is size of the array */
{
int i, s = 0;
for (i = 0; i < n; ++i)
s += a[i];
return s;
}
alternative function definition:
int sum(int *a, int n) /* n is size of the array */
{
int i, s = 0;
for (i = 0; i < n; ++i)
s += a[i];
return s;
}
Notice -- no size here. That
was provided in the original
declaration of the array.
Equivalence of int a[]; and int *a;
• As part of the header of a function definition the
declaration
int a[]; is equivalent to int *a;
• Within the body of a function, these are not
equivalent.
– The first will create a constant pointer (and no storage
for an array).
– The second will create a pointer variable.
Ad

More Related Content

Similar to C array and Initialisation and declaration (20)

Array
ArrayArray
Array
PralhadKhanal1
 
Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............Module_3_Arrays - Updated.pptx............
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
Array 2 hina
Array 2 hina Array 2 hina
Array 2 hina
heena94
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
Ashim Lamichhane
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
Python array
Python arrayPython array
Python array
Arnab Chakraborty
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
Ch08
Ch08Ch08
Ch08
Arriz San Juan
 
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
5 ARRAYS AND STRINGSjiuojhiooioiiouioi.pptx
teddiyfentaw
 
Array
ArrayArray
Array
hjasjhd
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Arrays
ArraysArrays
Arrays
Steven Wallach
 
Session 7 En
Session 7 EnSession 7 En
Session 7 En
SamQuiDaiBo
 
Session 7 En
Session 7 EnSession 7 En
Session 7 En
guest91d2b3
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
Arrays
ArraysArrays
Arrays
VenkataRangaRaoKommi1
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 

More from BalaKrishnan466 (15)

Switch and control statement for c language
Switch and control statement for c languageSwitch and control statement for c language
Switch and control statement for c language
BalaKrishnan466
 
c-Looping-Statements-P-Suman statement for c
c-Looping-Statements-P-Suman statement for cc-Looping-Statements-P-Suman statement for c
c-Looping-Statements-P-Suman statement for c
BalaKrishnan466
 
Switch and control looping statement for C
Switch and control looping statement for CSwitch and control looping statement for C
Switch and control looping statement for C
BalaKrishnan466
 
Switch and looping statement for c language
Switch and looping statement for c languageSwitch and looping statement for c language
Switch and looping statement for c language
BalaKrishnan466
 
C language Looping and conditional statement
C language Looping and conditional statementC language Looping and conditional statement
C language Looping and conditional statement
BalaKrishnan466
 
Control structure and Looping statements
Control structure and Looping statementsControl structure and Looping statements
Control structure and Looping statements
BalaKrishnan466
 
Control structure and Looping statements
Control structure and Looping statementsControl structure and Looping statements
Control structure and Looping statements
BalaKrishnan466
 
Control structure and Looping statements
Control structure and Looping statementsControl structure and Looping statements
Control structure and Looping statements
BalaKrishnan466
 
Decision making in C(2020-2021) statements
Decision making in C(2020-2021) statementsDecision making in C(2020-2021) statements
Decision making in C(2020-2021) statements
BalaKrishnan466
 
Basic operators and it's types in c languages
Basic operators and it's types in c languagesBasic operators and it's types in c languages
Basic operators and it's types in c languages
BalaKrishnan466
 
Queues operation using data structure in c
Queues operation using data structure in cQueues operation using data structure in c
Queues operation using data structure in c
BalaKrishnan466
 
Stack operation in data structure in c language
Stack operation in data structure in c languageStack operation in data structure in c language
Stack operation in data structure in c language
BalaKrishnan466
 
Flow chart and algorithm working progress
Flow chart and algorithm working progressFlow chart and algorithm working progress
Flow chart and algorithm working progress
BalaKrishnan466
 
Algorithms and Flowchart usages in C laguage
Algorithms and Flowchart usages in C laguageAlgorithms and Flowchart usages in C laguage
Algorithms and Flowchart usages in C laguage
BalaKrishnan466
 
Data types and it's usage in c languages
Data types and it's usage in c languagesData types and it's usage in c languages
Data types and it's usage in c languages
BalaKrishnan466
 
Switch and control statement for c language
Switch and control statement for c languageSwitch and control statement for c language
Switch and control statement for c language
BalaKrishnan466
 
c-Looping-Statements-P-Suman statement for c
c-Looping-Statements-P-Suman statement for cc-Looping-Statements-P-Suman statement for c
c-Looping-Statements-P-Suman statement for c
BalaKrishnan466
 
Switch and control looping statement for C
Switch and control looping statement for CSwitch and control looping statement for C
Switch and control looping statement for C
BalaKrishnan466
 
Switch and looping statement for c language
Switch and looping statement for c languageSwitch and looping statement for c language
Switch and looping statement for c language
BalaKrishnan466
 
C language Looping and conditional statement
C language Looping and conditional statementC language Looping and conditional statement
C language Looping and conditional statement
BalaKrishnan466
 
Control structure and Looping statements
Control structure and Looping statementsControl structure and Looping statements
Control structure and Looping statements
BalaKrishnan466
 
Control structure and Looping statements
Control structure and Looping statementsControl structure and Looping statements
Control structure and Looping statements
BalaKrishnan466
 
Control structure and Looping statements
Control structure and Looping statementsControl structure and Looping statements
Control structure and Looping statements
BalaKrishnan466
 
Decision making in C(2020-2021) statements
Decision making in C(2020-2021) statementsDecision making in C(2020-2021) statements
Decision making in C(2020-2021) statements
BalaKrishnan466
 
Basic operators and it's types in c languages
Basic operators and it's types in c languagesBasic operators and it's types in c languages
Basic operators and it's types in c languages
BalaKrishnan466
 
Queues operation using data structure in c
Queues operation using data structure in cQueues operation using data structure in c
Queues operation using data structure in c
BalaKrishnan466
 
Stack operation in data structure in c language
Stack operation in data structure in c languageStack operation in data structure in c language
Stack operation in data structure in c language
BalaKrishnan466
 
Flow chart and algorithm working progress
Flow chart and algorithm working progressFlow chart and algorithm working progress
Flow chart and algorithm working progress
BalaKrishnan466
 
Algorithms and Flowchart usages in C laguage
Algorithms and Flowchart usages in C laguageAlgorithms and Flowchart usages in C laguage
Algorithms and Flowchart usages in C laguage
BalaKrishnan466
 
Data types and it's usage in c languages
Data types and it's usage in c languagesData types and it's usage in c languages
Data types and it's usage in c languages
BalaKrishnan466
 
Ad

Recently uploaded (20)

Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Ad

C array and Initialisation and declaration

  • 2. What is an Array? • An array is a sequence of data items that are: – all of the same type • a sequence of integers, or a sequence of characters, or a sequence of floats, etc. – indexible • you can indicate or select the first element or second element or ... – stored contiguously in memory • each element of the sequence is stored in memory immediately after the previous element
  • 3. One-Dimensional Arrays • Declaration of a one-dimensional array. – int grade[3]; • Provides space in memory to store three grades (as in grades on three of your quizzes) • Example of Assignments grade[0] = 95; /* 1st element index is 0 */ grade[1] = 88; /* 2nd element index is 1 */ grade[2] = 97; /* 3rd element index is 2 */
  • 4. Accessing Array Elements • The following code segment will print the three grades stored in the array on the previous slide (assume i has been declared as an int variable): for (i = 0; i < 3; ++i) printf(“Grade %d is %dn”, i, grade[i]); • Output Grade 0 is 95 Grade 1 is 88 Grade 2 is 97
  • 5. Arrays and Pointers • An array name is also the name of a pointer constant to the base address (beginning) of the array in memory. • Using “made up” addresses (as we have before in discussing pointers): 95 88 97 grade 1000 1004 1008 < addresses in memory 0 1 2 < index of array element values stored in each element The address stored in grade would be 1000
  • 6. Using a Symbolic Constant as the Size of the Array • It is considered good programming practice to define the size of an array as a symbolic constant: – In the next example, if the size of a class changes then the symbolic constant at the top of the program is easily changed. – The program would then be recompiled so it can be used with the larger array of grades.
  • 7. Example of Entering Values into an Array, then Displaying the Values #include <stdio.h> #define N 20 /* Number of students in class */ int main(void) { int grade[N]; /* declare array with N elements */ int i; /* Enter the grades for a quiz */ for (i = 0; i < N; ++i) { printf(“Enter quiz grade %d: “, i + 1); scanf(“%d”, &grade[i]); } /* display the grades that were entered */ printf(“Here are the grades that were enteredn”); for (i = 0; i < N; ++i) printf(“Grade %d is %d”, i + 1, grade[i]); } Note that the user is shown grades starting with grade 1, but what the user thinks of as grade 1 is stored in grade[0] in the array.
  • 8. Initialization of Arrays As with simple variables, arrays can be initialized within a declaration. – An array initializer is a sequence of initializing values written as a brace-enclosed, comma-separated list. float x[4] = {-1.1, 0.2, 33.0, 4.4}; x[0] is initialized to -1.1 x[1] is initialized to 0.2 etc.
  • 9. More on Initialization of Arrays • If a list of initializers is shorter than the number of array elements, the remaining elements are initialized to zero. • If an external or static array is not initialized, then the system automatically initializes all elements to zero. • Uninitialized automatic and constant arrays start with garbage values -- whatever happens to be in memory when the array is allocated.
  • 10. Declaring and Initializing an Array Without a Size • If an array is declared without a size and is initialized to a series of values, it is implicitly given the size of the number of initializers. int a[] = {3, 4, 5, 6}; is equivalent to int a[4] = {3, 4, 5, 6};
  • 11. Range of Values Allowed for a Subscript • Assume a declaration: int i, a[size]; • To access an element of the array, we can write a[expr], where expr is an integral expression. • expr is called a subscript and the value of the subscript must lie in the range 0 to size - 1.
  • 12. “Subscript Out of Bounds” • If a subscript from the previous example lies outside the range 0 to size - 1 then: – A run-time error occurs. – The system will stop executing your program and display a message such as “subscript out of bounds”. – Sometimes no error message is displayed, but your program will begin to produce unexpected results.
  • 13. Relationship Between Arrays and Pointers • An array name represents the address of the beginning of the array in memory. – When an array is declared, the compiler must allocate a base address and a sufficient amount of storage (RAM) to contain all the elements of the array. – The base address of the array is the initial location in memory where the array is stored. • It is the address of the first element (index 0) of the array.
  • 14. Passing Arrays to Functions • In a function definition, a formal parameter that is declared as an array is actually a pointer. – When an array is passed, its base address is passed call-by- value. – The array elements themselves are not copied. – As a notational convenience, the compiler allows array bracket notation to be used in declaring pointers as parameters.
  • 15. Example of Passing an Array to a Function int sum(int a[], int n) /* n is size of the array */ { int i, s = 0; for (i = 0; i < n; ++i) s += a[i]; return s; } alternative function definition: int sum(int *a, int n) /* n is size of the array */ { int i, s = 0; for (i = 0; i < n; ++i) s += a[i]; return s; } Notice -- no size here. That was provided in the original declaration of the array.
  • 16. Equivalence of int a[]; and int *a; • As part of the header of a function definition the declaration int a[]; is equivalent to int *a; • Within the body of a function, these are not equivalent. – The first will create a constant pointer (and no storage for an array). – The second will create a pointer variable.
  翻译: