I'm having trouble in adding integers to a dynamic array reader, so the second function in the code below. Why do the added numbers in the output look weird? I'm guessing there's a memory problem, I'm somehow allocating new memory incorrectly.
int *create_dyn_array(unsigned int n)
{
int *array = malloc(n * sizeof(*array));
for (size_t i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
return array;
}
int *add_dyn_array(int *arr, unsigned int num, int newval)
{
int *temp = NULL;
temp = realloc(arr, (num + 1)*sizeof(int));
arr = temp;
int *newarray = arr;
while(*arr) {
arr++;
}
int testarray[1];
int *ptr = testarray;
int j = 1;
while (j > 0) {
*ptr = newval;
ptr++;
j--;
}
ptr = testarray;
while(*ptr) {
*arr++ = *ptr++;
}
return newarray;
}
void printarray(const int *array, int size) {
printf("{ ");
for (int i = 0; i < size; ++i) {
printf("%d, ", array[i]);
}
printf(" }\n");
}
int main()
{
int *array = create_dyn_array(5);
printarray(array, 5);
array = add_dyn_array(array, 5, 10);
printarray(array, 6);
array = add_dyn_array(array, 6, 100);
printarray(array, 7);
array = add_dyn_array(array, 7, 1000);
printarray(array, 8);
return 0;
}
What is wrong in the realloc logic?

realloc(...);temp[num]=newval; return temp;, nothing more should be needed. That is if you're trying to addnewvalto the end of the array. If that was supposed to do something else, explain that in the question.