Passing an array as an argument to a function in C
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
so you are modifying the values in main.
For historical reasons, arrays are not first class citizens and cannot be passed by value.
Passing an Array as Argument to Function in C
char request[]
is not the same as char *request[MAXSTRING]
. The former declares an array of characters (i.e. a string), the latter an array of pointers to char, i.e. an array of strings.
So declare it correctly in your function:
int findMatches (const char *filename, char *request[]) {
Next you will need a way to detect the end of the array of strings contained in request
. Either pass a count to findMatches()
or arrange for the last string to be NULL. If using a count you can redefine the function to accept a count:
void findMatches (const char *filename, char *request[], int n) {
for (int i = 0; i < n; i++) {
printf("%s \n", request[i]);
}
}
And call it like this:
findMatches("filename.txt", request, agrc-1);
Also, the use of MAXSTRING
in char *request[MAXSTRING]
seems confused. You seem to want an array of strings, but MAXSTRING
seems to be a maximum length of a string. It's unlikely that you will have 1000 arguments to your program.
Passing an array as function argument without defining a variable
You can make use of a compound literal. Something like
function((int []){3, -11, 0, 122});
Which way is better to pass arrays as function arguments in C?
Which way is better to pass arrays as function arguments in C?
I am going for Door #4. The receiving function needs to know the size.
void myFunction(size_t array_element_count, int *param);
Alternatively code could use a terminating sentinel, but there are no special "I-am-not-an-int" values.
In terms of the below, they emit the same code. This is a style issue. As such, follow the group's style guide. For me I favor size_t array_element_count, int param[array_element_count]
as most informative to code's intent.
void myFunction(size_t array_element_count, int *param);
void myFunction(size_t array_element_count, int param[array_element_count]);
void myFunction(size_t array_element_count, int param[]);
In terms of style, f(size, ptr)
vs f(ptr, size)
, I recall reading on the next C rev promoting f(size, ptr)
. IAC, with more complex arrays and VLA support , the below is useful:
foo(size_t row, size_t col, matrix[row][col]);
Passing an array as a parameter in C
This function declaration
void func(int v[]){
v[0] = 1;
}
is adjusted by the compiler to the declaration
void func(int *v){
v[0] = 1;
}
From the C Standard (6.7.6.3 Function declarators (including prototypes))
7 A declaration of a parameter as ‘‘array of type’’ shall be
adjusted to ‘‘qualified pointer to type’’, where the type qualifiers
(if any) are those specified within the [ and ] of the array type
derivation. If the keyword static also appears within the [ and ] of
the array type derivation, then for each call to the function, the
value of the corresponding actual argument shall provide access to the
first element of an array with at least as many elements as specified
by the size expression
On the other hand, in this call
func(v);
the array designator v
is implicitly converted to a pointer to its first element.
The C Standard (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.
That is the function call is equivalent to
func( &v[0] );
So in fact the first element of the array is passed to the function by reference through a pointer to it. Dereferencing the pointer by means of the subscript operator (the expression v[0]
is equivalent to the expression *v
)
v[0] = 1;
the referenced first element of the array is changed.
C - passing array in function an get its size
In C you must pass in not only the array, which decays to a pointer, but the size of the array as well. In C the common convention is (array, size):
void print_array(int a[], size_t s) {
for (size_t i = 0; i < s; ++i) {
... a[i] ...
}
}
Where you call it like:
print_array(a, 5);
Passing array to function vs Passing variables to function
When you pass an array, you are actually passing the base address of the same, which is a pointer to the first array element in the memory. It is inherently a call by reference, so you don't need to explicitly use a reference or &
while passing into your swap function. arr
decays to &(arr[0])
.
On the other hand, variables are not by default passed by value, and you need to explicitly use a &
to pass them by reference to get their values swapped in their memory locations and not just specific to the scope of the swap function.
Related Topics
Is #Pragma Once a Safe Include Guard
How to Clear a Stringstream Variable
Multi-Character Constant Warnings
What Is the Correct Way of Using C++11'S Range-Based For
Enum to String in Modern C++11/C++14/C++17 and Future C++20
How to Remove Unused C/C++ Symbols With Gcc and Ld
Why Cast Unused Return Values to Void
Are There Any Valid Use Cases to Use New and Delete, Raw Pointers or C-Style Arrays With Modern C++
Why How to Use Auto on a Private Type
Rvalue Reference Is Treated as an Lvalue
How to Construct a C++ Fstream from a Posix File Descriptor
Does Initialization Entail Lvalue-To-Rvalue Conversion? Is 'Int X = X;' Ub
When Should Std::Move Be Used on a Function Return Value
Is There a Max Array Length Limit in C++
Are There Benefits of Passing by Pointer Over Passing by Reference in C++