fixedynarr.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. printf("inputlength:%zu\n", in_str->length);
  12. for (size_t i = 0; i < in_str->length; i++) {
  13. printf("digit:%zu = %d\n", i, in_str->data[i]);
  14. }
  15. }
  16. struct IntArrayStr *create_int_array_str(size_t in_capacity) {
  17. struct IntArrayStr *mystr = malloc(sizeof(struct IntArrayStr)); /* allocate memory for struct */
  18. mystr->data = malloc(sizeof(int) * in_capacity); /* make sure the pointer in the struct points to the array */
  19. mystr->length = 0; //forgot to actually assign a value to the struct
  20. mystr->capacity = in_capacity;
  21. if (mystr->data == NULL) {
  22. exit(0);
  23. }
  24. return mystr;
  25. }
  26. void push_int_array_str(int in_int, struct IntArrayStr *in_str){
  27. if (in_str->length == in_str->capacity) {
  28. in_str->capacity*=2;
  29. printf("intarray capacity is now:%zu\n", in_str->capacity);
  30. int *temp;
  31. temp = realloc(in_str->data, sizeof(int)*in_str->capacity);
  32. if(temp == NULL){exit(0);};
  33. in_str->data = temp;
  34. printf("intarray length is now:%zu\n", in_str->length);
  35. }
  36. in_str->data[in_str->length] = in_int;
  37. printf("number:%zu = %d\n", in_str->length, in_str->data[in_str->length]);
  38. in_str->length++; //didn't read the flow when transfering and accidentally put this in the if block
  39. //also had an off-by-one error because I increased length before doing anything
  40. }
  41. int main() {
  42. srand(time(NULL));
  43. // change to while loop and take inputs rather than fill with random numbers
  44. printf("input numbers:\n");
  45. //int input;
  46. size_t length = 10;
  47. /* while (input != -1) { */
  48. /* scanf("%d", &input); */
  49. /* length++; */
  50. /* } */
  51. struct IntArrayStr *myintarraystr = create_int_array_str(2);
  52. for (size_t i = 0; i < length; i++) {
  53. int input = rand() % 10;
  54. push_int_array_str(input, myintarraystr);
  55. }
  56. read_int_array_str(myintarraystr);
  57. free(myintarraystr->data);
  58. free(myintarraystr);
  59. return 0;
  60. }