Skip to content
Snippets Groups Projects
Commit 0cfeedab authored by Baviere Merlin's avatar Baviere Merlin
Browse files

partie 2 realloc

parent e7982528
No related branches found
No related tags found
No related merge requests found
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <string.h>
enum { OLD_SIZE = 10, NEW_SIZE = 20 }; enum { OLD_SIZE = 10, NEW_SIZE = 20 };
int *resize_array(int *array, size_t count) { int *resize_array(int *array, size_t old_count, size_t new_count) {
if (0 == count) { if (0 == new_count) {
return 0; return 0;
} }
int *ret = (int *)realloc(array, count * sizeof(int)); int *ret = (int *)realloc(array, new_count * sizeof(int));
if (!ret) { if (!ret) {
free(array); free(array);
return 0; return 0;
} }
if (new_count > old_count) {
memset(ret + old_count, 0, (new_count - old_count) * sizeof(int));
}
return ret; return ret;
} }
void func(void) { void func(void) {
int *array = (int *)malloc(OLD_SIZE * sizeof(int)); int *array = (int *)malloc(OLD_SIZE * sizeof(int));
if (0 == array) { if (0 == array) {
/* Handle error */ /* Handle error */
return;
} }
/*@ loop unroll OLD_SIZE; */
for (size_t i = 0; i < OLD_SIZE; ++i) { for (size_t i = 0; i < OLD_SIZE; ++i) {
array[i] = i; array[i] = i;
} }
array = resize_array(array, NEW_SIZE); array = resize_array(array, OLD_SIZE, NEW_SIZE);
if (0 == array) { if (0 == array) {
/* Handle error */ /* Handle error */
return;
} }
/*@ loop unroll NEW_SIZE; */
for (size_t i = 0; i < NEW_SIZE; ++i) { for (size_t i = 0; i < NEW_SIZE; ++i) {
printf("%d ", array[i]); printf("%d ", array[i]);
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment