Created
April 15, 2019 08:54
-
-
Save Foadsf/22131bbc8771f5267b7987e1467af973 to your computer and use it in GitHub Desktop.
regarding this question for array append function in C using dynamic memory allocation
This file contains hidden or 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> | |
| typedef struct intlist_ { | |
| int size; | |
| int* list; | |
| } intlist; | |
| void append(intlist* arr, int value){ | |
| int* new_ptr = realloc((*arr).list, sizeof *((*arr).list) * ((*arr).size + 1u)); | |
| if (new_ptr == NULL) { | |
| fprintf(stderr, "Output memory\n"); | |
| exit (EXIT_FAILURE); | |
| } | |
| (*arr).list = new_ptr; | |
| (*arr).list[(*arr).size] = value; | |
| (*arr).size++; | |
| } | |
| int main() { | |
| intlist arr; | |
| arr.size = 4; | |
| arr.list = malloc(arr.size * sizeof(int)); | |
| arr.list[0] = 0; | |
| arr.list[1] = 5; | |
| arr.list[2] = 3; | |
| arr.list[3] = 64; | |
| // for (int ii = 0; ii < arr.size; ii++) | |
| // printf("%d, ", arr.list[ii]); | |
| append(&arr, 12); | |
| for (int ii = 0; ii < arr.size; ii++) | |
| printf("%d, ", arr.list[ii]); | |
| free(arr.list); | |
| return 0; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
regarding this question.