Handing array over to function. Correct use of pointers? - c

I have an array/pointer related problem.
I created an int array myArray of size 3. Using a function I want to fill this array.
So I'm calling this function giving her the adress &myArray of the array.
Is the syntax correct for the function declaration`? I'm handing over the pointer to the array, so the function can fill the array elements one by one.
But somehow my array is not filled with the correct values.
In Java I could just give an array to a method and have an array returned.
Any help is appreciated! Thanks!
#include <stdio.h>
int myArray[3];
void getSmth(int *anArray[]);
int main(void)
{
getSmth(&myArray);
}
void getSmth(int *anArray[])
{
for(i=0...)
{
*anArray[i] = tmpVal[i];
}
}

Remove one level of indirection:
#include <stdio.h>
int myArray[3];
void getSmth(int anArray[]);
int main(void)
{
getSmth(myArray);
}
void getSmth(int anArray[])
{
for(i=0...)
{
anArray[i] = tmpVal[i];
}
}
Also, as others have suggested, it would be a good idea to pass the size of the array into getSmth().

No, the syntax is not correct. You have an extra *, making the argument into an array of pointers.
In general, it's better to use:
void getSmth(int *array, size_t length);
since then the function can work on data from more sources, and the length becomes available which is very handy for iterating over the data as you seem to want to be doing.
You'd then call it like so:
int main(void)
{
int a[12], b[53];
getSmth(a, sizeof a / sizeof a[0]);
getSmth(b, sizeof b / sizeof b[0]);
}
Note the use of sizeof to compute (at compile-time) the number of elements. This is better than repeating the numbers from the definitions of the variables.

Right now, your function accepts an int *anArray[] parameter, which is an array of pointers to int. Remove the unneccessary * and your function signature should look simply like this:
void getSmth(int anArray[]); // array of int
or
void getSmth(int *anArray); // pointer to first array element of type int

You should use either int anArray[] or int *anArray (which is effectively the same, because array decays to pointer). You should also make sure that the function knows how big your array is either by agreement or passing it as a parameter for it can not use sizeof for the purpose.

Related

cast 2d char array to 2d int array

I have the following 2d array of unsigned chars to store an image as values from 0 to 255:
unsigned char img[MAX_DIM][MAX_DIM];
And I have a function that takes a 2d int array as parameter:
void transpose(int m[][MAX_DIM], int h, int w);
How can I pass the char array to that function? I tried something like this but it doesn't work:
transpose((int (*)[MAX_DIM])img, h, w);
You could make a type-generic interface and implement two different transpose functions, one for 8 bit data and one for 32 bit data. Example:
#include <stdint.h>
#include <stdio.h>
void transpose_32 (size_t h, size_t w, uint32_t m[h][w]){ puts(__func__); }
void transpose_8 (size_t h, size_t w, uint8_t m[h][w]){ puts(__func__); }
#define transpose(m,h,w) _Generic(**(m), uint8_t: transpose_8, uint32_t: transpose_32)(h,w,m)
int main(void)
{
const size_t MAX_DIM = 10;
uint8_t img1[MAX_DIM][MAX_DIM];
uint32_t img2[MAX_DIM][MAX_DIM];
transpose(img1, MAX_DIM, MAX_DIM);
transpose(img2, MAX_DIM, MAX_DIM);
return 0;
}
I would like to point out a few things that might help you.
First, if you want to pass an array as a function parameter, don't specify the size in brackets because there is no need to. In fact, think it is wrong.
Second, when you want to typecast something to int as I guess you are trying at your third line of code, the expression is :
(int)charArray[] ;
and not
int charArray(*) [SIZE]
Third and most important, you cant typecast something that is non-arithmetic (char) to something that is (int). But what you can do is use the atoi function that converts an argument to int.
int atoi(const char *str);
Also, next time you want to pass an array to a function, you should prefer to reference it and pass the address of the array as a parameter and not the array with the content itself, because there is no way to return the whole array converted from the transpose function, even if you manage to process it the way you want.
I hope I helped even a little, but if your problem is not resolved, try posting the statement of your problem in order for us to be more able to help you.

How to return pointers to arrays from functions?

I want a function to return a pointer to an array of size 10. What is the prototype for such a function?
I have tried 3 different prototypes and it doesn't work:
int(*)[10] returnPtrArray(int (*arr)[10])
{
return arr;
}
//The return type doesn't seem to work
int(*)[10] returnPtrArray(int[][10]);
int (returnPtrArray(int[][10])(*)[10];
int(*)(returnPtrArray(int[][10])[10];
//none of these prototypes seem to work
//calling
int main()
{
int a[5][10];
int (*ptr)[10] = returnPtrArray(&a);
//How do I make this work?
}
The correct definition of the function would be:
int (*returnPtrArray(int (*arr)[10]))[10]
{
return arr;
}
Breaking this down: returnPtrArray is a function:
returnPtrArray()
That takes a pointer to an array of 10 int:
returnPtrArray(int (*arr)[10])
And returns a pointer:
*returnPtrArray(int (*arr)[10])
To an array of size 10:
(*returnPtrArray(int (*arr)[10]))[10]
Of int:
int (*returnPtrArray(int (*arr)[10]))[10]
And you would call it like this:
int a[5][10];
int (*ptr)[10] = returnPtrArray(a);
Try this prototype:
int (*returnPtrArray(int (*arr)[10]))[10];
which is method named returnPtrArray, and takes as a parameter a pointer to an array of 10 integers.
It returns a pointer to an array of 10 integers.
Check it out in the Live demo, where I removed the & from the parameter in the method call, since it would be wrong.
This answer was based on the more analytic post Declare a C/C++ function returning pointer to array of integer pointers.
Pointers don't have knowledge of what they point to, beyond type. If you need to pass an array, you need to pass in a pointer along with the length of the array in a separate parameter (or use a list implementation like std::vector).

C - function (Assume that a and n are parameters where a is an array of int values and n is the length of the array.)

I'm new to programming and I don't really understand this question. Can some of you give me examples of what it means. How do I write a function where a is int values and n is the length?
I'm confused...
I'm not sure what your question is, as you haven't provided much information. However, a function in C is defined like this:
return_type function_name( parameter list ) {
body of the function
}
So, for this situation, we could say:
void arrayFunction( int a[], int n){
//do whatever you need to do with the function here
}
This may help you some.
Suppose you have an array of ints, as follows:
int arr[] = {2,3,4,5,6};
You can see that there are 5 elements inside above array arr. You can count them.
But it happens that when you pass the above arr to function, that function has no idea about how many elements arr contains. See below (incorrect) code snippet:
#include <stdio.h>
void display(int arr[]){
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr);
return 0;
}
The function named 'display()' has no idea about how many elements arr has
Therefore you you need to pass the extra argument (the extra argument called 'n') to tell that called function about the number of elements inside arr. You need to tell this separately - the length of arr.
Now this becomes - as you said in your question - arr is int values and n is the length
Below is the correct code:
#include <stdio.h>
void display(int a[], int n){
//Now display knows about lenth of elemnts in array 'a'
// Length is 5 in this case
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr, 5);
return 0;
}
Now, the function named 'display()' knows the length of array of int. This is the way you write code where you specify your array and its length.
More formally, this is because while passing array, it decays to a pointer and so the need arises to pass its length also alongwith it.

Function parameter as array with declared size

I frequently use the following convention to inform client code that a function requires an argument of an array with defined size:
/* File foo.h */
int foo (int arg[10]);
The message I want to give to client code is that they must provide an array of type int with 10 positions.
I am aware that it is not very usual, so I came here to ask: Am I missing any side effect of this convention ? Is it anyhow harmful?
Thank!
If you want to insist on getting an array of size 10, you can use:
int foo (int (*arg)[10]);
The ill-side effects of this are:
In the function, you have to use:
(*arg)[index]
instead of just
arg[index]
The calling function must use:
int array[10];
foo(&array);
instead of
int array[10];
foo(array);
You cannot use an array that has more than 10 elements.
int array[20];
foo(&array); // Not OK.
You cannot use a malloced array.
int* array = malloc(sizeof(int)*10);
foo(array); // Not OK.
Now pick the solution that is least harmful.
struct arrayContainerTen{
int data[10];
}
void aFunction(struct arrayContainerTen *pAnArray)
{
size_t size = sizeof(pAnArray->data);
}
main()
{
arrayContainerTen anArray;
aFunction(&anArray);
}
There's no harm in writing it like this. But just be aware that the compiler will not enforce the requirement. A declaration like that is treated by the compiler as if you'd written.
int foo(int *arg);

Passing 2D Array of Pointers in C

For my program I need to pass a 2D array of pointers to a function in a separate file. I've written a similarly-syntaxed file below:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int state;
int design;
} card_t;
card_t *cardSet[5][5];
void setFirst(card_t *cards[][]) { // <- Error: Array has incomplete element type
cards[0][0]->state = 1;
}
int main() {
setFirst(cardSet); // <- Error: Type of formal parameter 1 is incomplete
return 0;
}
When I change the code to all 1D arrays it compiles fine, but for a 2D array I get the errors shown above. What is the difference between the two cases?
Thanks!
Cameron
if you pass an array to a function, you have to specify the size of the inner array, in your case, instead of void setFirst(card_t *cards[][]), you should specify void setFirst(card_t *cards[][5]).
Why do you need to specify it and not the size of the first dimension?
Since cards is an array of array of card_t pointers, if you want to get to cards[1][0], the compiler will need to know how much to add to the pointer cards - cards is declared: card_t *cards[5][4] it will need to add 4 * sizeof(*card_t) to get to cards[1][0], but if cards is declared: card_t *cards[5][5] it will need to add 5 * sizeof(*card_t) to get to cards[1][0].
As has been mentioned, to pass a 2d array to a function, you need to have every dimension but the first declared.
However, you can also just pass the pointer, as follows. Note that you should always (unless the array dimension is completely fixed and the function that operates on the array only operates within the array's dimension) pass the length of each array, too.
void setFirst(card_t ***cards, size_t n, size_t m) {
if (n > 0 && m > 0) {
cards[0][0]->state = 1;
}
}
Because referencing an array via code[0][0] is the same as *(*(code+0)+0*m), you can pass two pointers instead of array dimensions.
Only the first index is optional. You should definitely mention the second index, because a two dimensional array decays to a pointer to 1d array.
void setFirst(card_t *cards[][5]) {
// ^ Newly added
// ..
}
Also make sure that the pointers are pointing to valid memory locations. Else dereferencing leads to segmentation faults. BTW, is there any reason to have a two dimensional array with pointers. I think you are just complicating the program.
To achieve something similar to what you are trying C99 has variable length arrays. These come particularly handy in function definitions:
void setFirst(size_t n, size_t m, card_t *cards[n][m]) {
...
}
Observe that you have to have the size parameters known at the moment of the array declaration, so you'd have to put them in front.

Resources