Created
July 6, 2012 21:22
-
-
Save kucaahbe/3062818 to your computer and use it in GitHub Desktop.
C dynamic arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct S { | |
int a; | |
}; | |
int main() | |
{ | |
struct S *arr=(struct S *) malloc(2*sizeof(struct S)); | |
unsigned int s_size=0; | |
arr[0].a=10; | |
arr[1].a=20; | |
printf("array size:%d\n",s_size); | |
printf("arr[0]=%d\n",arr[0].a); | |
printf("arr[1]=%d\n",arr[1].a); | |
free(arr); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
struct S { | |
int a; | |
}; | |
void add_one_element(struct S **arr, int *count, const int value) | |
{ | |
struct S *temp_val; | |
if (*count==0) { | |
temp_val = malloc(sizeof(struct S)); | |
} else { | |
temp_val = (struct S *) realloc(*arr,(1+*count) * sizeof(struct S *)); | |
} | |
if (temp_val==NULL) { | |
perror("malloc"); | |
abort; | |
} | |
(*(temp_val+*count)).a = value; | |
*arr = temp_val; | |
(*count)++; | |
} | |
int main() | |
{ | |
struct S *arr; | |
unsigned int arr_size=0; | |
printf("size of struct S :%d\n",sizeof(struct S)); | |
printf("size of struct S * :%d\n",sizeof(struct S *)); | |
assert(arr_size==0); | |
add_one_element(&arr,&arr_size, 123); | |
assert(arr_size==1); | |
add_one_element(&arr,&arr_size, 456); | |
assert(arr_size==2); | |
add_one_element(&arr,&arr_size, 789); | |
assert(arr_size==3); | |
add_one_element(&arr,&arr_size, 1010); | |
assert(arr_size==4); | |
assert(arr[0].a==123); | |
assert(arr[1].a==456); | |
assert(arr[2].a==789); | |
assert(arr[3].a==1010); | |
free(arr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment