In C,how to define an array which is of a length specified by the user?
I tried writing a code, but outputs were strange. Sometimes first two elements are correctly displayed, sometimes only first. Other seems some random values (extremely large sometimes). May be the problem is in initializing the pointer. First I didn't use the pointer p in readArray() function. I don't really know why I am using it now, or whether there should be a separate pointer when &A[0] is same as A.
here is the code
#include <stdio.h>
void printArray(int arr [], int size);
int * readArray(int size);
int main(){
int size; // size of array to be given by user
printf("Enter the size of the array ");
scanf("%d",&size);
printArray(readArray(size),size);
getchar();
return 0;
}
int * readArray(int size){
int A [size], i, *p;
p=&A[0];
for (i=0;i<size;i++){
printf("\nEnter the element no. %d: ",i+1);
scanf("%d",(p+i));
A[i]=*(p+i);
}
return &A[0];
}
void printArray(int *arr, int size){
int i=0;
for (i=0; i<size;i++){
printf("%d ", *(arr++));
}
printf("\n");
getchar();
}
I searched and couldn't get a solution. I got some things for C++ like this but not for C. Is there anything like new in C? (new allocates memory in C++ and java, how its different from malloc?)
PS: This is my first post in this forum, though I went through posting instruction, tell me if I should keep something in mind. Also I have done coding in Java for like 1 year, so don't hesitate to include complex solution, but as I am beginner in C/C++. I read first five chapters of "the complete reference C++, fourth edition" by Herbert Schildt (i.e. I think I understand basics of arrays and pointers) if thats useful anywhere to answer this question.
Thanks and regards