I am trying many ways to pass an array to a functions but it keeps determining the type I pass into the function as pointer. Could anyone please help?
typedef struct Process
{
int id;
int arrival;
int life;
int address[10]; //contain address space(s) of the Process
struct Process *next;
} Process_rec, *Process_ptr;
Process_ptr addProcess(Process_ptr old,int a, int b, int c, int d[10])
{
...
Process_ptr newProcess = (Process_ptr) malloc(sizeof(Process_rec));
newProcess->address = d;
...
}
main()
{
int address[10] = { 0 };
...
for loop
{
address[i] = something
}
p = addProcess(p, id,arrival,life,address);
I attempted to change the array in constructor to pointer, however, all the process I created would end up having the same array as the last Process I create.
If I use the above code, which should paste the array address[10] in main to function and then from function to struct. I keep encountering an error "incompatible types when assigning to type ‘int[10]’ from type ‘int *’", which means it considers the array d[10] in function as pointer, but I did use array instead of pointer ?!?
As explained by #Keith Thompson, if you define:
Process_ptr addProcess(Process_ptr old,int a, int b, int c, int d[10])
...then d is actually a pointer, i.e. completely equivalent to int *d.
What you want to do is this:
memcpy(newProcess->address, d, 10*sizeof(d[0]));
By the way, you don't need to cast the result of malloc. See Do I cast the result of malloc?
d is a pointer as above, and the core should be:
newProcess->address = d;
address is a static array, not pointer. array name means the array's address, and it can't be modified.
Related
In my code I need to pass a pointer to an array of pointers as a function argument. Code snippets:
struct foo * foos[] = {NULL, NULL, NULL};
some_function(&foos);
and:
static void some_function(struct foo ** foos) {
foos[0] = get_a_foo();
/* some more code here */
}
This works as expected (after some_function() returns, foos[] contains the pointers I set there), but I get a compiler warning for the call to some_function():
note: expected ‘struct foo **’ but argument is of type ‘struct foo * (*)[3]’
What’s the correct way to accomplish what I want (i.e. pass a pointer to the array of pointers to the function, so that the function can change pointers in the array)?
Pass it as some_function(foos)
struct foo ** is a pointer to a (single) pointer to a struct foo, not a pointer to an array of pointers, hence the compiler warning.
An easy way to silence the compiler warning is to call the function as follows:
some_function(&foos[0]);
This will pass a pointer to the first member, i.e. a struct foo **, rather than to the whole array; the address is the same in both cases.
If I understand what you are trying to do (fill your array of pointers with a call to a function), then your understanding of how to accomplish that is a bit unclear. You declare foos, which itself is an array. (an array of what? pointers).
You can treat it just like you would treat an array of char (from the standpoint that you can simply pass the array itself as a parameter to a function and operate on the array within a function) You can do that and have the changes visible in the caller because despite the array address itself being a copy in the function, the values it holds (the individual pointer address) remains the same.
For example:
#include <stdio.h>
char *labels[] = { "my", "dog", "has", "fleas" };
void fillfoos (char **f, int n)
{
int i;
for (i = 0; i < n; i++)
f[i] = labels[i];
}
int main (void) {
char *foos[] = { NULL, NULL, NULL };
int i, n = sizeof foos / sizeof *foos;
fillfoos (foos, n);
for (i = 0; i < n; i++)
printf ("foos[%d] : %s\n", i, foos[i]);
return 0;
}
Above foos is simply treated as an array passed to the function fillfoos which then loops over each pointer within foos filling it with the address to the corresponding string-literal contained in labels. The contents of foos is then available back in main, e.g.
Example Use/Output
$ ./bin/fillptp
foos[0] : my
foos[1] : dog
foos[2] : has
If I misunderstood your question, please let me know and I'm happy to help further.
You need a pointer to an array as clearly mentioned in the warning.
Below is a minimal code sample that explains the same.
#include<stdio.h>
typedef struct foo{
}FOO;
static void some_function(FOO* (*foos)[]) {
// foos above is a pointer to an array of pointers.
// Refer the link to start with a simple example.
// Access it like foos[0][0] which is the same as (*foos)[0]
/* some more code here */
}
int main(int argc, char **argv) {
FOO* foos[]={0,0,0}; // Here you have an array of pointers
some_function(&foos);
}
I need a container to save function pointers to certain numbers.
Like
1 = function add
2 = function sub
3 = function mult
And so on. This is for a simple interrupt handler, where depending on the interrupt number a certain function should be called.
I thought that I can do this with a structured list, but I know the size of the maximal amount of entries. So I thought about an array of strings like
const char *functions[2];
a[0] = "add";
a[1] = "sub";
But then I don't know how I can further use the strings.
Any tips or thoughts?
Thanks in advance!
EDIT: To clarify, I have 2 important functions here, one, where I want to save a function pointer together with a number into some container. And another one, which just says "goto the function which is at a certain number in that container". So the first function gets an int number (say from 1 to 50) and a pointer to a function. Those should be saved together. The second function then just gets an int number as parameter and then it should call the function which is associated with that int number in my container. What I'm asking is how I could save a pointer that points to a function together with a number.
EDIT2: I do want to save function pointers. I thought I could maybe save the function name as a string and then use it later as function name because I didn't know another way.
If you want to store and use a function pointer you can do it like this:
// the functions you want to point to
int add(int a, int b) { do stuff }
int sub(int a, int b) { do some other stuff }
...
// declare and set a function pointer
int (*myFuncPtr) (int, int);
myFuncPtr = ⊂ // points to the function "sub". The & is optional
// now use it:
int result = myFuncPtr(23, 42);
The type of a function pointer depends on the return value and the parameters of the function you want to point to.
You can make the declaration of a function pointer variable easier
by using typedef:
typedef int (*funcPtr) (int, int);
Now declare and initialize a function pointer using the typedef like this:
funcPtr myFuncPtr = &add;
Of course you can now put many of those pointers into an array
and access them by the indices:
funcPtr funcPtrs[] = { &sub, add }; // like i said, the ampersand is optional
int result = funcPtrs[0](23, 42);
You have to store function pointers, so define a new function pointer type and make an array. According to your question the all functions should take two int parameters and return and int, so the new type should be something like this:
typedef int (*operation_t)(int,int);
Now you can create an array of operation_t. The whole code:
#include <stdio.h>
typedef int (*operation_t)(int,int);
int addInt(int n, int m) {
return n+m;
}
int subInt(int n, int m) {
return n-m;
}
int multipleInt(int n, int m) {
return n*m;
}
int main ()
{
const operation_t function_list[3] = {&addInt, &subInt, &multipleInt};
int i;
for(i = 0; i < 3; i++)
{
printf("inputs: 2 and 3 result: %d\n", function_list[i](2,3));
}
return 0;
}
The output:
Note that, as it's an array the indexes are 0, 1, 2.
To add an own ID you can create a stuct with the function pointer and an int ID.
typedef struct operation
{
int (*operation_p)(int,int);
int id;
} math_operation_t;
You can even build a linked list, and add functions dynamically if you define a third member variable, which should be the pointer to the next element.
i have a huge problem allocating memory in C
i have this struct
typedef struct{
int x;
int y;
}T;
i want to create a function that dynamically adds a structs to a pointer.
something like:
int main()
{
T* t;
f(&t);
free(t);
}
up to this point i think everything is ok, now the function is where i get lost
void f(T** t)
{
T t1;
T t2;
T t3;
//first i malloc
*t=malloc(sizeof(T)*T_MAX_SIZE);//i want another function to make the array bigger, but this is not as important as the problem
t1.x=11;
t1.y=12;
t2.x=21;
t2.y=22;
t3.x=31;
t3.y=32;
//now i want to copy the values from t1,t2,t3 to t[0],t[1],t[2]
memcpy(&(*t[0]),&t1,sizeof(T));
memcpy(&(*t[1]),&t2,sizeof(T));
memcpy(&(*t[2]),&t3,sizeof(T));
}
i do not know the correct way of copying these structs.
the point of doing this is to use t out of the function
(in the main)
many thanks :D
Your memcpy calls are incorrect.
In the expression &(*t[0]), the array index has top precedence, followed by the pointer indirection. So with explicit parenthesis it looks like &(*(t[0])).
So it first tries to array subscript t, which is the address of t in main. In the case of t[0] it still works, but t[1] references something past that variable, invoking undefined behavior. You want the array index of what t points to, which is (*t)[i].
So the memcpy calls should be:
memcpy(&((*t)[0]),&t1,sizeof(T));
memcpy(&((*t)[1]),&t2,sizeof(T));
memcpy(&((*t)[2]),&t3,sizeof(T));
You don't need any copy functions to assign one structure to another - you simply equate them. So if you have
T var1 = {1, 2};
T var2 = var1;
the whole of var1 is copied to var2. Amending your (simplified) program:
#include <stdio.h>
#include <stdlib.h>
#define T_MAX_SIZE 10
typedef struct{
int x;
int y;
}T;
void f(T** t)
{
T t1;
*t=malloc(sizeof(T)*T_MAX_SIZE);
t1.x=11;
t1.y=12;
(*t)[0] = t1;
}
int main(void) {
T* t;
f(&t);
printf ("Result %d %d\n", t[0].x, t[0].y);
free(t);
return 0;
}
Program output:
Result 11 12
I've just started to work with C, and never had to deal with pointers in previous languages I used, so I was wondering what method is better if just modifying a string.
pointerstring vs normal.
Also if you want to provide more information about when to use pointers that would be great. I was shocked when I found out that the function "normal" would even modify the string passed, and update in the main function without a return value.
#include <stdio.h>
void pointerstring(char *s);
void normal(char s[]);
int main() {
char string[20];
pointerstring(string);
printf("\nPointer: %s\n",string);
normal(string);
printf("Normal: %s\n",string);
}
void pointerstring(char *s) {
sprintf(s,"Hello");
}
void normal(char s[]) {
sprintf(s,"World");
}
Output:
Pointer: Hello
Normal: World
In a function declaration, char [] and char * are equivalent. Function parameters with outer-level array type are transformed to the equivalent pointer type; this affects calling code and the function body itself.
Because of this, it's better to use the char * syntax as otherwise you could be confused and attempt e.g. to take the sizeof of an outer-level fixed-length array type parameter:
void foo(char s[10]) {
printf("%z\n", sizeof(s)); // prints 4 (or 8), not 10
}
When you pass a parameter declared as a pointer to a function (and the pointer parameter is not declared const), you are explicitly giving the function permission to modify the object or array the pointer points to.
One of the problems in C is that arrays are second-class citizens. In almost all useful circumstances, among them when passing them to a function, arrays decay to pointers (thereby losing their size information).
Therefore, it makes no difference whether you take an array as T* arg or T arg[] — the latter is a mere synonym for the former. Both are pointers to the first character of the string variable defined in main(), so both have access to the original data and can modify it.
Note: C always passes arguments per copy. This is also true in this case. However, when you pass a pointer (or an array decaying to a pointer), what is copied is the address, so that the object referred to is accessible through two different copies of its address.
With pointer Vs Without pointer
1) We can directly pass a local variable reference(address) to the new function to process and update the values, instead of sending the values to the function and returning the values from the function.
With pointers
...
int a = 10;
func(&a);
...
void func(int *x);
{
//do something with the value *x(10)
*x = 5;
}
Without pointers
...
int a = 10;
a = func(a);
...
int func(int x);
{
//do something with the value x(10)
x = 5;
return x;
}
2) Global or static variable has life time scope and local variable has scope only to a function. If we want to create a user defined scope variable means pointer is requried. That means if we want to create a variable which should have scope in some n number of functions means, create a dynamic memory for that variable in first function and pass it to all the function, finally free the memory in nth function.
3) If we want to keep member function also in sturucture along with member variables then we can go for function pointers.
struct data;
struct data
{
int no1, no2, ans;
void (*pfAdd)(struct data*);
void (*pfSub)(struct data*);
void (*pfMul)(struct data*);
void (*pfDiv)(struct data*);
};
void add(struct data* x)
{
x.ans = x.no1, x.no2;
}
...
struct data a;
a.no1 = 10;
a.no1 = 5;
a.pfAdd = add;
...
a.pfAdd(&a);
printf("Addition is %d\n", a.ans);
...
4) Consider a structure data which size s is very big. If we want to send a variable of this structure to another function better to send as reference. Because this will reduce the activation record(in stack) size created for the new function.
With Pointers - It will requires only 4bytes (in 32 bit m/c) or 8 bytes (in 64 bit m/c) in activation record(in stack) of function func
...
struct data a;
func(&a);
...
Without Pointers - It will requires s bytes in activation record(in stack) of function func. Conside the s is sizeof(struct data) which is very big value.
...
struct data a;
func(a);
...
5) We can change a value of a constant variable with pointers.
...
const int a = 10;
int *p = NULL;
p = (int *)&a;
*p = 5;
printf("%d", a); //This will print 5
...
in addition to the other answers, my comment about "string"-manipulating functions (string = zero terminated char array): always return the string parameter as a return value.
So you can use the function procedural or functional, like in printf("Dear %s, ", normal(buf));
I create a type and try to change the int value in it.
But it keeps printing 240.
I don't know why, can anyone help me?
Here is my code:
typedef struct{
int i;
}MyType;
do(MyType mt, int ii){
mt.i = ii;
}
int main(int argc, char ** argv){
MyType mt;
do(mt, 5);
print("%d\n", mt.i);
}
Passing mt by value to function do(). Any changes made will be local to the function. Pass the address of mt:
void do_func(MtType* mt, int ii){
mt->i = ii;
}
MyType mt;
do_func(&mt, 5);
So first, your do function has some problems. You have failed to specify a return type, so int is assumed (pre-C99), but I see no reason to not just specify it. Second, do is a reserved keyword in C.
You are passing your struct by value, so a copy is made, passed to your do function, and that is modified. Everything is passed by value in C, period. Your mt variable declared in main is never touched.
Take a MyType* in your code if you need to modify one or more of its member variables, take a MyType** if you need to allocate memory for the structure itself (i.e., initialize a pointer).
// pass a pointer to the function to allow
// for changes to the member variables to be
// visible to callers of your code.
void init_mytype(MyType *mt, int ii){
if(mt)
mt->i = ii;
}
MyType mt;
init_mytype(&mt, 1);
// pass a pointer to pointer to initialize memory
// for the structure and return a valid pointer.
// remember, everything is passed by value (copy)
void init_mytype(MyType **mt, int ii) {
if(mt) {
*mt = malloc(sizeof(MyType));
if(*mt)
(*mt)->i = ii;
}
}
MyType *pmt;
init_mytype(&pmt, 1);