Computer Science 210 Computer Organization: Arrays and Pointers
Computer Science 210 Computer Organization: Arrays and Pointers
Computer Organization
The syntax
Here we initialize all of the array’s cells and visit them all
while (1){
printf("Enter a number or 0 to stop: ");
scanf("%d", &number);
if (!number)
break;
array[length] = number;
length++;
if (length == max){
printf("Maximum number of numbers entered\n");
break;
}
}
int main(){
int max = 100;
int numbers[max];
int length = getNumbers(numbers, max);
if (length > 0)
printf("The average is %f\n",
sum(numbers, length) / (double) length);
else
printf("No numbers were entered\n");
}
The element type of the array parameter must be specified, but its physical
size need not be
Therefore, this function can process an integer array of any physical size
The logical size (length) is passed too, because the array might not be full
How Parameters Are Passed to Functions
• Parameters of basic types (char, int, float,
and double) are passed by value (a copy of the
value of the argument is placed in temporary
storage on the runtime stack)
The & operator returns the actual memory address (a large integer, probably)
of a variable
The * operator says that the variable alias can contain a pointer to a
memory location that can hold an int
number alias
The memory for alias
10 contains garbage until it is set
to a value
Assigning an Address
int number = 10;
int *alias;
The variables number and alias can access the same storage location
aCopy number alias
The memory for alias now
10 10 contains the address of
number
Access by Indirection (Dereferencing)
int number = 10;
int *alias = NULL; // Set the pointer variable to empty
Its operand must be a pointer variable, and it must contain the address of
another cell in memory
The value NULL from stdio is used to indicate the empty pointer
Aliasing and Side Effects
int number = 10;
int *alias = NULL; // Set the pointer variable to empty
int main(){
float a, b, c, root1, root2;
printf("Enter a, b, and c: ");
scanf("%f%f%f", &a, &b, &c);
quadraticRoots(a, b, c, &root1, &root2);
printf("Root1: %f\nRoot2: %f\n", root1, root2);
}
int main(){
int i, max = 5, array[max];
for (i = 0; i < max; i++)
array[i] = i + 1;
int main(){
int i, max = 5, array[max];
for (i = 0; i < max; i++)
array[i] = i + 1;
Strings in C