Passing array not pointer to a function in C [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I want to pass an array to a function such that if I use the sizeof operator on array inside the function body, I should get the actual size of the array and not that of a pointer. For e.g -
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,0};
printf("Array size = %d\n", sizeof(arr)/sizeof(int)); ---> O/P = 40/4 = 10
func(arr);
}
void func(int arr[])
{
printf("Array size = %d\n", sizeof(arr)/sizeof(int)); --->O/P = 4/4 = 1
}
The printf statement in the main function prints 10 while the one in func prints 1. Is it possible to do so in C language?
EDIT: I know other alternatives like wrapping the array into a struct etc. Actually, I was trying to solve a problem given on TopCoders site and the requirement of one problem is that I have to write a function(requirement given below). Now I am confused that how I am going to calculate the size of the int[] donations array inside int maxDonations(int[] donations) function.
Definition
Class: BadNeighbors
Method: maxDonations
Parameters: int[]
Returns: int
Method signature: int maxDonations(int[] donations)
(be sure your method is public)
If you want, I can post the entire question.

A cheap way would be to wrap the array into a struct and pass that (or a pointer to the struct).
However, I would recommend passing an additional size_t argument that specifies the size of the array. This would make your function more flexible.

In C you cannot pass an array as a parameter to a function directly. You can pass a structure, a pointer or some other numeric value, but not an array.

Based on the constraints in your question, this question is impossible to answer.
In C, sizeof is an operator, rather than a function: you correctly mention this in your question. However, C operators are evaluated at compile time, rather than runtime, which means that you cannot use sizeof in a function in the way you want to - at compile time the compiler cannot tell how func() is going to be called.
Looking at the problem as set, I am assuming it is this one:
http://www.cs.duke.edu/csed/algoprobs/neighbors.html
The required method signature on that page is:
public int maxDonations(int[] donations)
although for some reason, you've omitted the public keyword in your question. This keyword indicates that the language in question is not C, and this example solution looks very much as if it is written in Java, in which language this is a non-problem, arrays have a length member.
I'd suggest you clarify the requirements for the question from your teacher/website/whatever to check what is really expected.

Related

Defining A Function Pointer Using Assignment In c

I'm learning C. I know what the first line is doing; it's making a pointer to a function with no arguments and it returns an int. But wtf is the second doing?
My guess is that it is casting an int into a function? But what does it mean to turn an int into a function?
Also, why does it cause an error when I try to call the function: 'function()'?
int (*function) ();
function = (int (*) ()) (1000);
Overall, the code is nonsense. Where did you get it from?
it's making a pointer to a function with no arguments
Rather, it is making a pointer to a function with obsolete style parameter list.
But wtf is the second doing?
It assigns the function pointer to point at address 1000 (decimal), my means of a cast from int to the function pointer type.
why does it cause an error when I try to call the function: 'function()'?
Likely because there is no such function allocated at address 1000. You might not even have access to that area etc.
learning function pointer is pain in ass.
simple example maybe help for better understand.
suppose you want point to this function:
int sum (int a , int b) {
return a+b;
}
so you need define a pointer with same type:
int *pointerToSum (int, int);
and simply assign it to function:
pointerToSum = ∑
if you want use it:
(*pointerToSum)(3, 5); //8
you can use function-pointer tag to find out more complex answers.
your question delete by people because there is duplicate question asked before.
I implement function-pointer for myself and it's a little complex and you can see in : exercise of function pointer
I wish you the best.

What is the significance of asterisks postfixing a variable type in a method header? [duplicate]

This question already has answers here:
difference between int* i and int *i
(9 answers)
Why is the asterisk before the variable name, rather than after the type?
(12 answers)
Closed 3 years ago.
I have been trying to learn C as a programming language, and have been trying to solve sample problems on site like LeetCode in C programs. When I was reading over some of the skeleton code that was provided as a function header for a problem on LeetCode that I want to solve in C, the function header had asterisks post fixing some of the types, specifically like this:
int* twoSum(int* nums, int numSize, int target, int* returnSize) {
/* Code goes here */
}
After doing a fair bit of reading, I learned that prefixing a variable with an asterisk when declaring a variable reserves the variable as a pointer, but I have not been able to find anything about what it means when the type specifier itself is post fixed with an asterisk.
The spaces there don't matter.
int* nums is identical to int *nums. So are int * nums and int*nums.
All four of these declare nums as pointer to int.
It's a matter of style preference (though I wouldn't use that last one), with no effect on the generated code.

Passing anonymous parameters to functions in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I can pass arguments to a function in C in the following manner without any warnings or errors using gcc on ubuntu-64bit:
void func(char* test){
// do something here
}
void main() {
func((char*) "smaps");
}
I did not find a lot of examples about passing anonymous parameters to functions in C apart from one comment on a similar question about C++. I am thinking of using this technique (a lot) in my code which would be compiled on multiple AMD64/ARM devices as they become available (with mostly debian-based OSes). My question is, is this compiler-specific?
Output of gcc --version:
$ gcc --version
gcc (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406
UPDATE: Even though I think 4386427's was good enough for me, I would explain a bit more about the question as it was put on hold. I have a script which makes several calls to a specific function which takes in a char** as argument. I was of the view that I would need to explicitly declare a char** separately and pass it to the function by name every time I made a call to the function. I thought it would be more convenient to declare a string and pass it to the function at the same time; something like:
func( (char**) {"first_string", "second_string"} ).
My initial concern was is this allowed in C generally or is this a compiler-specific feature? 4386427's answer suggests that it is not compiler-specific, however I should be careful that the char** passed to the function would be immutable.
All parameters in C are passed by value. No information about the original object from which the value came is passed to the called function. In this sense, all C arguments are anonymous; no information about the identifier used in the calling function is passed.
In func((char*) "smaps");, the string literal "smaps" is converted to a pointer to char. Only the value of the pointer is passed to func. This is standard C.
(If you do want to pass information about an object to a function, you must do that manually. For example, you can take the address of an object and pass the resulting pointer to the function. Or you can pass the number of elements in an array to a function, along with the address of the first element.)
(In C, string literals such as "smaps" are automatically converted to a pointer to their first character, so you do not need to manually convert them with a char * cast. [This automatic conversion does not occur when the string literal is the operand of sizeof, _Alignof, or & or when it is used to initialize an array.])
It depends on what you are doing in the function. As long as you don't try to modify what test is pointing to, there is no problem. To indicate that it can't be changed, it is good to add const.
Like this the code is fine:
#include <stdio.h>
void func(const char* test){
printf("%s\n", test);
}
int main(void) {
func("smaps1");
func("smaps2");
func("smaps3");
func("smaps4");
return 0;
}
But if you try to change the value like:
void func(char* test){
test[0] = 'A';
printf("%s\n", test);
}
you have undefined behavior because modifying a string literal is undefined behavior.

How to pass a pointer to a function argument of type fixed size array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to write a lib wrapper. My wrapper function prototype looks like this
int my_wrapper(char * configstr);
The function to be wrapped looks like this.
void my_function(char config[CONFIGSTRSIZE]);
I tried to do the following:
int my_wrapper(char * configstr)
{
my_function(configstr);
return 0;
}
This compiles and works but I receive an error. Telling my that the argument is a invalid type.
discards qualifiers from pointer target type
Is there a way to perform a cast to telling the compiler that the pointer of the calling function always is a pointer of the proper size?
It's more or less impossible to change the interfaces. I thank you for your feedback.
Is there a way to perform a cast to telling the compiler that the
pointer of the calling function always is a pointer of the proper
size?
It is not possible in C. Pointers do not have information about the size. You need to pass it as the additional parameter or have this information in the dereferenced object (for example first is the size, or termination value like C strings)
First of all, the following function declaration doesn't make much sense, although legal:
void my_function(char config[CONFIGSTRSIZE]);
It creates the wrong impression that you can somehow pass an array (with a fixed size). You can't in C. What actually happens is that C adjusts any array type in a function declaration to a corresponding pointer type, so this declaration ends up to be just
void my_function(char *config);
You could write it like this to emphasize that the pointer passed should point to an array (I prefer not to, but that's a matter of style):
void my_function(char config[]);
Now for your problem, according to the error message you get, you're probably trying to pass a const-qualified pointer here. Depending on what my_function() is doing, there are two solutions:
my_function() only reads the array. Then you should change the function prototype like this:
void my_function(const char *config);
my_function() also modifies the array. Then you can't pass some const data there, but you might take a copy of your data. Assuming the data is a string, one way to do it would be the following:
// having some const char *config
char *cfgcopy = malloc(strlen(config)+1);
if (cfgcopy) { // allocation succeeded
strcpy(cfgcopy, config);
my_function(cfgcopy);
// do something with the modified cfgcopy
free(cfgcopy);
}
Instead of malloc()/strcpy(), many implementations provide a "shorthand" strdup() function you could use. But be aware strdup() isn't part of standard C.

Pass by reference and pointers [duplicate]

This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed 8 years ago.
What is the difference between passing by reference the parameters in a function and passing pointer variables as a parameter in a function ?
There is no pass by reference in C, it's always pass by value.
C developers can emulate pass by reference, by passing the pointers to a variable and the accessing it using dereferencing within the function. Something like the following, which sets a variable to 42:
static void changeTo42 (int *pXyzzy) {
*pXyzzy = 42;
}
:
int x = 0;
changeTo42 (&x);
Contrast that with the C++ true pass by reference, where you don't have to muck about with pointers (and especially pointers to pointers, where even seasoned coders may still occasionally curse and gnash their teeth):
static void changeTo42 (int &xyzzy) {
xyzzy = 42;
}
:
int x = 0;
changeTo42 (x);
I would implore ISO to consider adding true references to the next C standard. Not necessarily the full capability found in C++, just something that would fix all the problems people have when calling functions.
You might be thinking of C++. I'll cover that below.
In C there is no passing by reference. To accomplish the same feat, you can send a pointer to a variable as an argument and dereference the pointer in the method, as shown in paxdiablo's comment.
In C++, you could accomplish the same thing if you tried to pass by reference C-style (as explained previously) or if you tried passing the arguments as such:
static void multiply(int& x){
x * 7;
}
void main(){
int x = 4;
multiply(x);
}
The variable x at the end of this program would equal 28.

Resources