fixedynarr.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <stdio.h>
  2. #include <stddef.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. struct IntArrayStr{
  6. int *data;
  7. size_t length;
  8. size_t capacity;
  9. };
  10. void read_int_array_str(struct IntArrayStr *in_str) {
  11. for (size_t i = 0; i < in_str->length; i++) {
  12. printf("digit:%zu = %d\n", i, in_str->data[i]);
  13. }
  14. }
  15. struct IntArrayStr *create_int_array_str(size_t in_capacity) {
  16. struct IntArrayStr *mystr = malloc(sizeof(struct IntArrayStr)); //allocate memory for struct
  17. mystr->data = malloc(sizeof(int) * in_capacity); //make sure the pointer in the struct points to the array
  18. mystr->length = 0; //forgot to actually assign a value to the struct
  19. mystr->capacity = in_capacity;
  20. if (mystr->data == NULL) {
  21. exit(0);
  22. }
  23. return mystr;
  24. }
  25. /* push value to struct, also handle realloc */
  26. void push_int_array_str(int in_int, struct IntArrayStr *in_str){
  27. if (in_str->length == in_str->capacity) { //check if already full
  28. in_str->capacity*=2; //if so we should double
  29. printf("intarray capacity is now:%zu\n", in_str->capacity);
  30. int *temp; //create a temporary pointer
  31. temp = realloc(in_str->data, sizeof(int)*in_str->capacity); //realloc the data into a new bucket
  32. if(temp == NULL){exit(0);}; //check if actually valid
  33. in_str->data = temp; //if valid, make sure the pointer in the struct points to the realloced block
  34. }
  35. in_str->data[in_str->length] = in_int;
  36. printf("number:%zu = %d\n", in_str->length, in_str->data[in_str->length]);
  37. in_str->length++; //didn't read the flow when transferring and accidentally put this in the if block
  38. printf("intarray length is now:%zu\n", in_str->length);
  39. //also had an off-by-one error because I increased length before doing anything
  40. }
  41. int main() {
  42. srand(time(NULL));
  43. printf("input numbers:\n");
  44. struct IntArrayStr *myintarraystr = create_int_array_str(2);
  45. int input;
  46. size_t length = 10;
  47. while (input != -1) {
  48. scanf("%d", &input);
  49. push_int_array_str(input, myintarraystr);
  50. }
  51. read_int_array_str(myintarraystr);
  52. free(myintarraystr->data);
  53. free(myintarraystr);
  54. return 0;
  55. }