Some dialects of C have variable-length arrays (VLA), notably C99 (and GCC accepts them....)
But your teacher probably wants you to understand C dynamic memory allocation, and you should also test when scanf
fails, so you might code:
int main(void) {
int size, i;
printf("Enter the size of the arrays:\n");
if (scanf("%d", &size)<1) {
perror("scan size");
exit(EXIT_FAILURE);
};
Actually, you'll better test against the case of size
being negative! I leave that up to you.
int *arr1 = calloc(size, sizeof(int));
if (arr1==NULL) {
perror("calloc arr1");
exit(EXIT_FAILURE);
}
You always need to handle failure of calloc
or malloc
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++) {
if(scanf("%d", &arr1[size])<1) {
perror("scanf arr1[size]");
exit(EXIT_FAILURE);
}
}
scanf_s
is only existing in C11, and on a C11 compliant implementation you could use VLAs
I leave the rest up to you. You want to code a for
loop to print every element of the array.
Of course you should call free
appropriately (and I am leaving that to you). Otherwise, you have a memory leak. Some systems have valgrind to help hunting them. Don't forget to compile with all warnings & debug info (with GCC use gcc -Wall -g
) then use the debugger (e.g. gdb
).
Don't forget that a programming language is a specification (written in some document), not a software. You may want to glance into n1570. And you need to understand what undefined behavior means.