C: adding elements to an array -
i'm trying test program creates array 0 elements in it, adds elements (reallocating memory each time), , printing out elements. but, keep getting errors when try run it.
int main(int argc, const char * argv[]) { int num = 0; int n = 10; int **array = malloc(0); (int = 0; < n; ++i) { ++num; array = realloc(array, num * sizeof(int*)); array[num-1] = &i; } (int j = 0; j < n; ++j) { printf("%d", &array[j]); // error 1 } return 0; } i'm sorry didn't include errors original post. think fixed 1 of them. here other:
error 1: format specifies type 'int' argument has type 'int *'
this answer based on assumption printing simple array, since don't show output expect. using 1 more step of indirection need, , many variables. take note indexing different length (often 1).
#include <stdio.h> #include <stdlib.h> int main(void) { int i, n = 10; int *array = null; // no need double star, or fake allocation (i = 0; < n; ++i) { array = realloc(array, (i + 1) * sizeof(int)); // remove *, add 1 num elements array[i] = i; } (i = 0; < n; ++i) { printf("%d", array[i]); // remove & } free(array); // don't forget return 0; } program output:
0123456789 in practice, should assign result of realloc pointer variable, check it's ok, , replace original pointer var.
Comments
Post a Comment