2021-02-07 22:31:04 +03:00
|
|
|
### Generic array
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-07 22:31:04 +03:00
|
|
|
### Overview
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
- Type generic array/vector.
|
2020-12-27 08:00:22 +03:00
|
|
|
- Index access is possible (e.g float* arr; 'printf("%f", arr[i]')).
|
|
|
|
|
|
|
|
|
2021-02-07 22:31:04 +03:00
|
|
|
### Usage
|
2020-12-27 08:00:22 +03:00
|
|
|
|
|
|
|
|
|
|
|
```c
|
2021-02-05 16:35:10 +03:00
|
|
|
#include "sc_array.h"
|
2021-01-31 02:52:06 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
#include <stdio.h>
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
void example_str()
|
|
|
|
{
|
|
|
|
char **p, *it;
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
sc_array_create(p, 0);
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
sc_array_add(p, "item0");
|
|
|
|
sc_array_add(p, "item1");
|
|
|
|
sc_array_add(p, "item2");
|
|
|
|
|
2021-02-03 08:09:50 +03:00
|
|
|
printf("\nDelete first element \n\n");
|
2021-01-31 02:52:06 +03:00
|
|
|
sc_array_del(p, 0);
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
sc_array_foreach (p, it) {
|
|
|
|
printf("Elem = %s \n", it);
|
|
|
|
}
|
|
|
|
|
|
|
|
sc_array_destroy(p);
|
|
|
|
}
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
void example_int()
|
|
|
|
{
|
|
|
|
int *p;
|
|
|
|
|
|
|
|
sc_array_create(p, 0);
|
|
|
|
|
|
|
|
sc_array_add(p, 0);
|
|
|
|
sc_array_add(p, 1);
|
|
|
|
sc_array_add(p, 2);
|
2020-12-27 08:00:22 +03:00
|
|
|
|
2021-02-07 22:31:04 +03:00
|
|
|
for (size_t i = 0; i < sc_array_size(p); i++) {
|
2020-12-27 08:00:22 +03:00
|
|
|
printf("Elem = %d \n", p[i]);
|
|
|
|
}
|
|
|
|
|
|
|
|
sc_array_destroy(p);
|
2021-02-05 16:35:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
example_int();
|
|
|
|
example_str();
|
2021-01-31 02:52:06 +03:00
|
|
|
|
2021-02-05 16:35:10 +03:00
|
|
|
return 0;
|
|
|
|
}
|
2020-12-27 08:00:22 +03:00
|
|
|
```
|
|
|
|
|
|
|
|
##### Note
|
|
|
|
|
|
|
|
Array pointer is not stable. If you pass the array to another function which
|
|
|
|
can add items, do it by passing reference of the array pointer :
|
|
|
|
|
|
|
|
```c
|
|
|
|
void some_function_to_add_elems(long **p)
|
|
|
|
{
|
|
|
|
sc_array_add(*p, 500);
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
long *p;
|
|
|
|
|
|
|
|
sc_array_create(p, 0);
|
|
|
|
sc_array_add(p, 300);
|
|
|
|
|
|
|
|
// Pass via address of p
|
|
|
|
some_function_to_add_elems(&p);
|
|
|
|
sc_array_destroy(p);
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|