I have the following code and am supposed to fill in the entire main function just to demonstrate how pointers work.
e
is an integer of 4,
f
is an array of the characters in the code,
g
is a pointer to the string "ABC".
I got a good understanding of how e
and f
work, but I'm curious about the variable g
and whether it's actually a pointer to the string s
.
#include <stdio.h>
int foo(int a, char b[], char c, char *d)
{
}
int main(void)
{
char s[] = {"ABC"};
char *g = &s[2];
int e = 4;
char f[] = {'3', '7', '\0'};
int y = foo(e, f, g[2], g);
}
CodePudding user response:
This function declaration
int foo(int a, char b[], char c, char *d);
is equvalent to the following function declarations
int foo(int a, char *b, char c, char *d);
int foo(int a, char b[], char c, char d[]);
And all the function declarations declare the same one function.
A function parameter having an array type is adjusted by the compiler to pointer to the array element type.
In this call of the function
int y = foo(e, f, g[2], g);
the array designator f is converted to pointer to its first element.
You can imagine this call like
You c int y = foo(e, &f[0], g[2], g);
The variable g was initialized by the address of the third element of the array s
char *g = &s[2];
This pointer is passed to the function as the forth argument.
You could write for example
char s[] = {"ABC"};
char *g = s;
In this case the array designator s
is implicitly converted to pointer to its first element. That is the declaration
char *g = s;
is equivalent to
char *g = &s[0];
As you need to declare a pointer to the whole array as an object then you need to write
char ( *g )[4] = &s;
This quote from the C Standard will be useful (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
CodePudding user response:
The variable g points to the third element of the string "abc" i.e, c. I f you want g as a pointer for whole string then make it as,
char *g =s;