简体   繁体   中英

How do I pass a char(*)([long unsigned int]) as a parameter in C?

I have a variable type:

char (*p)[12] = calloc(n, sizeof(*p));

I need the variable to stay this way, but I am having trouble passing it as a parameter due to the function type giving me errors:

void myMethod(char *p) { ... }

What can I use in myMethod as the parameter to make this work?

What can I use in myMethod as the parameter to make this work

Possibly this:

void myMethod(char (*p)[12])

Use the same type for the parameter as you did for the variable:

void myMethod(char (*p)[12])
{
  // do something with p
}
...
char (*p)[12] = calloc(n, sizeof *p);
myMethod(p);

Remember that p is a pointer to a 12-element array of char , not a simple pointer to char . Thus, the type of p[i] will be char [12] (which in most cases will decay to char * ).

The typical C idiom is to pass a char* and a size_t (or unsigned int or whatever equivalent) parameter. Then the contract of the function is that it will respect the size_t argument as the length of the array/buffer.

If you must insist that the pointer be not changed, you use the const qualifier.

char (*p)[12] = ...

With the previous you have NOT defined an array of 12 elements, each one being a pointer to char BUT a pointer to an array with 12 char elements.

As explained in the following lines:

int *a[3];

Start at a . Look right, say array of size 3. Look left and say pointer. Look right and see nothing. Look left and say int. All together you say a is an array of size 3 pointers to int.

Adding parentheses is when it gets weird:

int (*a)[3];

The parentheses change the order just like in an expression. When you look right after a , you see the right parenthesis, which you cannot jump over until you look left. Hence, you would say a is a pointer to an array of 3 ints.

Check these links for better explanation:


Still if you want to pass the array to a function you can either copy it, or since it is an array pass a pointer to the first element (you can simply do it by using the name of the array):

myMethod( p ) <- how you call the function

I personally would prefer the latter case, since you're passing to the function a simple pointer and not an array by copy of all of its elements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM