#include <stdio.h> #include <stdlib.h> extern void abc(int *x); extern void abc(
ID: 3743429 • Letter: #
Question
#include <stdio.h>
#include <stdlib.h>
extern void abc(int *x);
extern void abc(int x[20]);
extern void abc(int x[]);
void abc(int x[3]) {
printf("inside abc: size is %d ", sizeof(x));
}
int main() {
int y[15];
printf("outside abc: size is %d ", sizeof(y));
abc(y);
return EXIT_SUCCESS;
}
First, with just a couple of exceptions, any time an array name is given in a program, it is converted (by the compiler) to be a pointer to the first element of the array. The exceptions are when the array is the immediate operand of the sizeof function or the "create-pointer-to" (unary &) operator. The semantics of the [l operator in a [il mean((a)+ (i))) a is converted to be a pointer to its first element, i is added to this pointer, giving a pointer to the element in the ith position of a, and the operator makes the reference One of the anomalies of C is that the semantics of [ allows i [a] to be used as an alternative to a[i]. (You could experiment with this: instead of a [0], write o[a] when you want to access the first element in array a. Just because you can do this does not mean you should in your code... Tammy does not recommend using the 0 [a] form.) Second, any time a function's formal parameter is given as an array type, it is converted (by the compiler) to be a pointer type: "array of int" is converted to "pointer to int": "array of pointer to char" is converted to "pointer to pointer to char" 1. Given this knowledge, examine the program array.c. Compile and run the program. Explain why: no type-check errors are reported for any of the three declarations of the function abc, even though the parameter declarations appear to be inconsistent. The "extern" keyword declares the type for the function abc while the actual function definition is defined once below the three declarations Compile and run the program gcc o array array.c array 2. Why does the array seem to change size when the function is called?Explanation / Answer
1. extern void abc(int *x); extern void abc(int x[20]); extern void abc(int x[]); All three of these statements are declaration of funtion abc and since formal parameter of all these function declarations are same i.e. pointer-to-int. Hence no type-check error will be thrown and since multiple declarations are allowed in C these three declarations will also not throw any error. 2. Change in array size is due to Array Decay, which means loss of type and dimension of an array. Array passed into the function is converted to pointer-to-int which points to base address of the array but loses it's identity that it is an array and hence using sizeof() operator will print size of a pointer variable which is 8 in a typical 64-bit machine or 4 in a 32-bit machine.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.