I need to create a program which:
- initially allocate an array to read in and hold up to 5 temperatures.
- prompt the user to enter temperatures and type the value -100.0 when they are finished
- if the user fills up the array your program should dynamically allocate a new array which is double the size.
- copy the old values across to the new array. deallocate the old array.
- continue reading into the new array.
- print the new array out when it's done
I'm completely new to C and I'm kinda stuck. I know how to create a dynamic array, but I don't know how to create a new array which constantly grows once the old array is filled up.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int i,k; //loop count
int j = 5; //initial array size
int* temp = malloc(sizeof(int)*j);
int* newtemp;
for (i = 0; i < j; i++){ //loop to read in temperature
printf("enter temperature: ");
scanf("%d",(temp+i));
if (i=j){
j = j*2; //double the size of initial array
int* newtemp = malloc(sizeof(int)*j);
strcpy(*newtemp,temp); // copy string
for (k = 0; k < j; k++){ //loop to read in temperature
printf("enter temperature: ");
scanf("%d",(temp+i+k));
}
}
switch (temp[i]){
case (-100):
temp[i] = '\0';
i = 5; //loop ends
break;
}
}
return 0;
}
The error messages:
tempp.c:18:16: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(*newtemp,temp);
^
In file included from tempp.c:3:0:
/usr/include/string.h:121:14: note: expected ‘char * restrict’ but argument is of type ‘int’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
^~~~~~
tempp.c:18:25: warning: passing argument 2 of ‘strcpy’ from incompatible pointer type [-Wincompatible-pointer-types]
strcpy(*newtemp,temp);
^~~~
In file included from tempp.c:3:0:
/usr/include/string.h:121:14: note: expected ‘const char * restrict’ but argument is of type ‘int *’
extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
I know that my code is messy and I really don't know the right method to reallocate a new array while it constantly grows. Please help me with this. Thank you!
strcpyto copyints, as instrcpy(*newtemp,temp);And*newtempis wrong.strcpy, which,as @PaulOgilvie said cannot be used for copying an array of integers, you can usereallocfor re-allocation. It even preserves memory contents so you do not have to copy after expanding.if (i=j){is suspicious. I'd expectif (i==j){jis a horrible name for storing array size. Ex.tempsizewould be a better name.