Jarrod L
Jarrod L

Reputation: 293

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?

Upvotes: 0

Views: 764

Answers (4)

John Bode
John Bode

Reputation: 123488

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 *).

Upvotes: 2

Matteo
Matteo

Reputation: 8132

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

Upvotes: -2

cnicutar
cnicutar

Reputation: 182649

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

Possibly this:

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

Upvotes: 4

user268396
user268396

Reputation: 11986

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.

Upvotes: 0

Related Questions