#9 Jerry
Pokud to chces poradne zneprehlednit pro kohokoliv, kdo na to bude koukat, tak je to presne to co chces.
To same, cos vyvedl (jen vyrazne citelnejsi a pochopitelnejsi):
#include <stdio.h>
typedef struct t_point
{
double x;
double y;
} Point;
void test(Point * array_point, int t_count) {
for (int i = 0; i < t_count; ++i) {
printf("%d %g %g \n", i, array_point[i].x, array_point[i].y);
}
}
int main() {
const int max_records = 100;
Point array_point[max_records];
for (int i = 0; i < max_records; ++i) {
array_point[i].x = i;
array_point[i].y = i;
}
test( array_point, max_records);
}
S dynamicky alokovanou pameti treba takto (bez kontroly, ze alokace probehla a ze bylo zadano nejake spravne cislo):
#include <stdio.h>
#include <stdlib.h>
typedef struct t_point
{
double x;
double y;
} Point;
void test(Point * array_point, int t_count) {
for (int i = 0; i < t_count; ++i) {
printf("%d %g %g \n", i, array_point[i].x, array_point[i].y);
}
}
int main() {
int records = 1;
printf("Zadej pocet zaznamu: ");
scanf("%d",&records);
Point * array_point = (Point *)malloc(records * sizeof(Point));
for (int i = 0; i < records; ++i) {
array_point[i].x = i+1;
array_point[i].y = i*1.154;
}
test( array_point, records);
free(array_point);
}
Jeden z duvodu, proc predat adresu na pointer je ten, ze chcete zmenit pointer uvnitr funkce a aby se zmena projevila na vnejsek (obvykla chyba zacatecniku):
#include <stdio.h>
#include <stdlib.h>
typedef struct t_point
{
double x;
double y;
} Point;
int some_init(Point ** p) {
int records = 1;
printf("Zadej pocet zaznamu: ");
scanf("%d", &records);
if (records > 0) {
*p = (Point *)malloc(records * sizeof(Point));
return records;
}
return 0;
}
void test(Point * array_point, int t_count) {
for (int i = 0; i < t_count; ++i) {
printf("%d %g %g \n", i, array_point[i].x, array_point[i].y);
}
}
int main() {
Point * array_point = NULL;
int records = some_init(&array_point);
if (NULL != array_point) {
for (int i = 0; i < records; ++i) {
array_point[i].x = i+1;
array_point[i].y = i*1.154;
}
test( array_point, records);
free(array_point);
}
}
A v C++ by to byl vylozene hnusnej kod, da se to udelat mnohem jednoduseji a tak.