dynamic array c
// Use malloc to allocate memory
ptr = (castType*) malloc(size);
int *exampl = (int*) malloc(sizeof(int));
// Use calloc to allocate and inizialize n contiguous blocks of memory
ptr = (castType*) calloc(n, size);
char *exampl = (char*) calloc(20, sizeof(char));
3.83
6
Array a;
int i;
initArray(&a, 5); // initially 5 elements
for (i = 0; i < 100; i++)
insertArray(&a, i); // automatically resizes as necessary
printf("%d\n", a.array[9]); // print 10th element
printf("%d\n", a.used); // print number of elements
freeArray(&a);
Thank you!
6
0
4
1
ptr = (castType*) malloc(size);
Thank you!
1
0
4
1
ptr = (castType*)calloc(n, size);
Thank you!
1
0
4
7
int main(int argc, char *argv[])
{
int i;
double* p; // We uses this reference variable to access
// dynamically created array elements
p = calloc(10, sizeof(double) ); // Make double array of 10 elements
for ( i = 0; i < 10; i++ )
*(p + i) = i; // put value i in array element i
for ( i = 0; i < 10; i++ )
printf("*(p + %d) = %lf\n", i, *(p+i) );
free(p); // Un-reserve the first array
putchar('\n');
p = calloc(4, sizeof(double) ); // Make a NEW double array of 4 elements
// ***** Notice that the array size has CHANGED !!! ****
for ( i = 0; i < 4; i++ )
*(p + i) = i*i; // put value i*i in array element i
for ( i = 0; i < 4; i++ )
printf("*(p + %d) = %lf\n", i, *(p+i) );
free(p); // Un-reserve the second array
}
Thank you!
7
0
0
0
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, int element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
Thank you!
0
0
Are there any code examples left?
New code examples in category Other
-
Other 2023-03-27 22:50:10 how to select the whole line in vscode with keyboard shortcut
-
Other 2022-03-27 22:45:24 income of a web developer
-
Other 2022-03-27 22:35:01 \pyrcc_main.py: File does not exist 'resources.qrc'
-
Other 2022-03-27 22:30:45 rick roll embed code
-
Other 2022-03-27 22:20:08 Circuit_04_Potentiometer
-
Other 2022-03-27 22:20:05 iterative power
-
Other 2022-03-27 22:15:11 flutter run all
-
Other 2022-03-27 22:10:05 when is karlson release
-
Other 2022-03-27 22:10:02 wp .htaccess example
-
Other 2022-03-27 22:00:08 bash pause in file read line by line