Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
For example, in order not to pass the entire array to the function, but only a pointer to it, thereby avoiding creating a copy of the array, reducing memory consumption and function call time
Because it's convenient :) There are complex data types - structures, unions, which are full of pointers to other pointers, etc. Very often, data objects of this type are aggregated into arrays and addressed by pointers - you get one pointer and you can iterate over a huge array.
C is a system language and get as a value a pointer that addresses an array containing pointers to elements, each of which is a pointer to something you can finally work with - easily :D
for example, to pass by reference rather than by value. This is required:
a. when the array can and must change during the execution of the function;
b. when there are 100,000,000,000,000,000,000 (10^20) values in the array. Passing such arrays to functions by value somewhat slows down the program;
in. your choice (write in the comments).
To begin with, the question is why the concept of an array was introduced into the language, and not left with pointers - because typing is good. Those. at the compilation stage, it will be possible to understand whether the correct variables were passed to the function / method, and you can also find out which method to use (methods with the same name and different types of parameters, plus C ++ templates in the piggy bank)
Accordingly, in order not to transfer the entire array as a copy into methods, introduced the concept of a link (it is not only defined for arrays, but also for any objects)
Imagine, for example, that you have a point that is described by an array of its coordinates:
And then you make an array of such points:
And then you output them one by one:
Point2D *p, *q;
for (p = array, q = p + 5; p < q; p++) {
print_point(*p);
}
typedef struct {
Point2D *pt1;
Point2D *pt2;
} Line2D;
#include <stdio.h>
typedef int Point2D[2];
typedef struct {
Point2D *pt1;
Point2D *pt2;
} Line2D;
void print_point(Point2D p)
{
printf("(%d,%d)\n", p[0], p[1]);
}
void print_line(Line2D l)
{
printf("Line[\n");
print_point(*l.pt1);
print_point(*l.pt2);
printf("Line]\n");
}
int main(void)
{
Point2D array[5] = {{1, 2}, {3, 4}, {5, 6}};
Point2D *p, *q;
Line2D l;
for (p = array, q = p + 5; p < q; p++) {
print_point(*p);
}
l.pt1 = array;
l.pt2 = array + 2;
print_line(l);
return 0;
}
[[email protected] c]$ .ansi t.c -o t
[[email protected] c]$ ./t
(1,2)
(3,4)
(5,6)
(0,0)
(0,0)
Line[
(1,2)
(5,6)
Line]
[[email protected] c]$
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question