How to get the information from a pointer [duplicate] - c

This question already has answers here:
Returning Arrays/Pointers from a function
(7 answers)
Closed 9 years ago.
Here is my code:
int *myFunction()
{
int A[3] = {1,2,3};
return A; //this will return the pointer to the first element in the array A
}
int main (void)
{
int A[3];
A = myfunction(); //A gets the return value of myFunction
for(int j=0; j==2; j++)
{
B[j] = 2* A[j]; //doubles each value in the array
}
printf("%d",B);
return 0;
}
But this does not work because the A that is returned is not the actual vector. How do I get the actual vector {1,2,3} in the main function?

The function myFunction allocates A, but this allocation only exists within the scope of the function. When the function returns the memory holding A is destroyed. This means that the function is returning a pointer to memory that has not been un-allocated.
The problem is that the variable A does not persist outside the function. You could use a global variable or pass a pointer to the buffer into myFunction
Global variable method:
static int A[3];
int* myFunction()
{
A[0] = 1; A[1] = 2; //etc
return A;
}
In this example, because A is a global, the memory pointed to by A persists throught your program's entire life time. Therefore it is safe to return a pointer to it...
As a side note, global variables should probably not be used in this way... it's a little clunky. The use of the static keyword means that A will not be accessible outside of this module (C file).
Pointer method:
void myFunction(a[3])
{
a[0] = 1; a[1] = 2; //etc
}
int main()
{
myA[3];
myFunction(myA);
// and continue to print array...
}
In this example the main() function allocates myA. This variable exists whilst the function is executing (it's an automatic variable). A pointer to the array is passed into the function, which fills the array. Therefore the main() function can get information from myFunction().
Another way to make the variable myA persist would be to allocate it on the heap. To do this you would do something like int *myA = malloc(sizeof(int) * NUMBER_OF_INTS_IN_ARRAY. This memory will then persist until you specifically desctroy it using free() or you program ends.

int A[3] = {1,2,3}; is being created on the stack, this is, it is a local array and it's memory can be used again after myFunction executes. You have to either make int A[3] static within myFunction or by placing it outside of all functions. Another option would be to create int A[3] within main and pass the address of A to myFunction so myFunction can directly modify the contents of A.

As is, your code isn't close to working anyway... your for loop is broken, you have undefined variables in main, you have function name mismatches, and your print isn't going to do what you want anyway...
The big problem as that you've got undefined behavior going on, you can't access A[] outside of the function where it was locally defined. The easiest way to rectify that is to use dynamic memory, malloc() some memory for A in your myFunction then use the values in main and free() the memory when you're done.
Here's the example fixing your other syntax issues:
int *myFunction()
{
int *A;
A = malloc(3 * sizeof(int));
A[0] = 1;
A[1] = 2;
A[2] = 3;
return A;
}
int main (void)
{
int *A = myFunction(); //A gets the return value of myFunction
int B[3] = {0, 0, 0};
int j;
for(j=0; j<3; j++)
{
B[j] = 2* A[j]; //doubles each value in the array
}
free(A);
printf("%d",B[0]);
return 0;
}

Pass the array to be filled as argument to the initisliser function along with its size:
size_t myFunction(int * A, size_t s)
{
int A_tmp[3] = {1,2,3};
size_t i = 0;
for (; i < s && i < sizeof(A_tmp)/sizeof(A_tmp[0]); ++i)
{
A[i] = A_tmp[i];
}
return i;
}
Then call it like so:
int main()
{
int myA[3];
size_t s = sizeof(myA)/sizeof(myA[0]);
size_t n = myFunction(myA, s);
if (n < s)
fprintf(stderr, "Caution: Only the first %zu of %zu elements of A were initialised.\n", n, s);
// and continue to print array...
}

#include <stdio.h>
int (*myFunction(void))[3]
{
static int A[3] = {1,2,3};
return &A;
}
int main (void){
int (*A)[3], B[3];
A = myFunction();
for(int j=0; j<=2; j++)
{
B[j] = 2 * (*A)[j];
}
for(int j=0; j<3;++j)
printf("%d ", B[j]);
return 0;
}

Related

Uninitialized variable accessed error in c [duplicate]

May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
The output of the piece of code above:
65
4202656
What am I doing wrong? What does the "4202656" mean?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.
In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.
To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
You can't access a local variable once it goes out of scope. This is what it means to be a local variable.
When you are accessing the array in the replaceNumberAndPrint function the result is undefined. The fact it appears to work first time is just a fortunate coincidence. Probably the memory location you are pointing to is unallocated on the stack and is still correctly set for the first call, but the call to printf then overwrites this by pushing values onto the stack during its operation which is why the second call to printf displays something different.
You need to store the array data on the heap and pass a pointer, or in a variable that remains in scope (e.g. a global or something scoped within the main function).
Try something like that. The way you do it "kills" myArray cause if it locally defined.
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
free(array);
}
int * getArray() {
int * myArray = malloc(sizeof(int) * 3);
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
//{4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
More : http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
Edit: As Comments correctly pointed out: A better way to do it would be that :
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
if(!array)
return;
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
}
int * createArray() {
int * myArray = malloc(sizeof(int) * 3);
if(!myArray)
return 0;
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
return myArray;
}
int main() {
int * array = createArray();
if(array)
{
replaceNumberAndPrint(array);
free(array);
}
return 0;
}
myArray goes out of scope as soon as you leave getArray. You need to allocate space for it on the heap instead.
Your code invokes Undefined Behaviour because myArray goes out of scope as soon as getArray() returns and any attempt to use (dereference) the dangling pointer is UB.
Local variables go out of scope upon return, so you can't return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc or new. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don't know what static means, read this question & answer.
Right way to do this is as follows:
struct Arr {
int array[3];
};
Arr get_array() {
Arr a;
a.array[0] = 4;
a.array[1] = 65;
a.array[2] = 23;
return a;
}
int main(int argc, char **argv) {
Arr a = get_array();
for(size_t i=0; i<3; i++)
printf("%d\n", a.array[i]);
return 0;
}
To understand why you need to do this, you need to know how sizeof(array) works. C (and thus c++) tries hard to avoid copying the array, and you need the struct to go past that. Why copying is needed is because of scopes -- the get_array() function's scope disappears and every value still needed from that scope will need to be copied to calling scope.
C++ solution:
"May I have any access to a local variable in a different function? If so, how?"
The answer is no, not after the function has ended. Local variables are destroyed at that point.
In C++ the way to deal with returning arrays is to manage them in a container like a std::array (fixed size) or a std::vector (dynamic size).
Eg:
void replaceNumberAndPrint(const std::array<int, 3>& array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n", array[2]);
}
std::array<int, 3> getArray() {
std::array<int, 3> myArray = {4, 65, 23};
return myArray;
}
In the second function the returned value is optimized by the compiler so you don't pay the price of actually copying the array.
In this code you have used pointer to local objects but when a function returns all local variables goes out of scope. If you will allocate memory (using malloc() function for allocation) then no data will be lost or overwrite.
int* getArray(int size) {
int *myArray = (int*)malloc(size*sizeof(int));
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}
int main() {
int i;
int *vector = getArray(3);
for(i=0;i<3;i++)
{
printf("%i\n",vector[i]);
}
getch();
return 0;
}
This code will print all the array elements and no overwritten will be happened.
Static ..or.. Global within your .c will do the trick ;)
However the entire time the program will occupy those 3 bytes BUT you avoid doing malloc on simple things like this (malloc recommended for big arrays)
On the other hand if the outside function modify the pointer, then the internal 'myArray' will be modified cause it points to it, that's it
int myArray[3];
int * getArray() {
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}

socket programming in c, sending list of items [duplicate]

May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
The output of the piece of code above:
65
4202656
What am I doing wrong? What does the "4202656" mean?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.
In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.
To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
You can't access a local variable once it goes out of scope. This is what it means to be a local variable.
When you are accessing the array in the replaceNumberAndPrint function the result is undefined. The fact it appears to work first time is just a fortunate coincidence. Probably the memory location you are pointing to is unallocated on the stack and is still correctly set for the first call, but the call to printf then overwrites this by pushing values onto the stack during its operation which is why the second call to printf displays something different.
You need to store the array data on the heap and pass a pointer, or in a variable that remains in scope (e.g. a global or something scoped within the main function).
Try something like that. The way you do it "kills" myArray cause if it locally defined.
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
free(array);
}
int * getArray() {
int * myArray = malloc(sizeof(int) * 3);
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
//{4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
More : http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
Edit: As Comments correctly pointed out: A better way to do it would be that :
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
if(!array)
return;
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
}
int * createArray() {
int * myArray = malloc(sizeof(int) * 3);
if(!myArray)
return 0;
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
return myArray;
}
int main() {
int * array = createArray();
if(array)
{
replaceNumberAndPrint(array);
free(array);
}
return 0;
}
myArray goes out of scope as soon as you leave getArray. You need to allocate space for it on the heap instead.
Your code invokes Undefined Behaviour because myArray goes out of scope as soon as getArray() returns and any attempt to use (dereference) the dangling pointer is UB.
Local variables go out of scope upon return, so you can't return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc or new. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don't know what static means, read this question & answer.
Right way to do this is as follows:
struct Arr {
int array[3];
};
Arr get_array() {
Arr a;
a.array[0] = 4;
a.array[1] = 65;
a.array[2] = 23;
return a;
}
int main(int argc, char **argv) {
Arr a = get_array();
for(size_t i=0; i<3; i++)
printf("%d\n", a.array[i]);
return 0;
}
To understand why you need to do this, you need to know how sizeof(array) works. C (and thus c++) tries hard to avoid copying the array, and you need the struct to go past that. Why copying is needed is because of scopes -- the get_array() function's scope disappears and every value still needed from that scope will need to be copied to calling scope.
C++ solution:
"May I have any access to a local variable in a different function? If so, how?"
The answer is no, not after the function has ended. Local variables are destroyed at that point.
In C++ the way to deal with returning arrays is to manage them in a container like a std::array (fixed size) or a std::vector (dynamic size).
Eg:
void replaceNumberAndPrint(const std::array<int, 3>& array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n", array[2]);
}
std::array<int, 3> getArray() {
std::array<int, 3> myArray = {4, 65, 23};
return myArray;
}
In the second function the returned value is optimized by the compiler so you don't pay the price of actually copying the array.
In this code you have used pointer to local objects but when a function returns all local variables goes out of scope. If you will allocate memory (using malloc() function for allocation) then no data will be lost or overwrite.
int* getArray(int size) {
int *myArray = (int*)malloc(size*sizeof(int));
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}
int main() {
int i;
int *vector = getArray(3);
for(i=0;i<3;i++)
{
printf("%i\n",vector[i]);
}
getch();
return 0;
}
This code will print all the array elements and no overwritten will be happened.
Static ..or.. Global within your .c will do the trick ;)
However the entire time the program will occupy those 3 bytes BUT you avoid doing malloc on simple things like this (malloc recommended for big arrays)
On the other hand if the outside function modify the pointer, then the internal 'myArray' will be modified cause it points to it, that's it
int myArray[3];
int * getArray() {
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}

C: storing a void pointer function in a char array with strcpy [duplicate]

May I have any access to a local variable in a different function? If so, how?
void replaceNumberAndPrint(int array[3]) {
printf("%i\n", array[1]);
printf("%i\n", array[1]);
}
int * getArray() {
int myArray[3] = {4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
The output of the piece of code above:
65
4202656
What am I doing wrong? What does the "4202656" mean?
Do I have to copy the whole array in the replaceNumberAndPrint() function to be able to access it more than the first time?
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.
In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.
To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.
One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.
You can't access a local variable once it goes out of scope. This is what it means to be a local variable.
When you are accessing the array in the replaceNumberAndPrint function the result is undefined. The fact it appears to work first time is just a fortunate coincidence. Probably the memory location you are pointing to is unallocated on the stack and is still correctly set for the first call, but the call to printf then overwrites this by pushing values onto the stack during its operation which is why the second call to printf displays something different.
You need to store the array data on the heap and pass a pointer, or in a variable that remains in scope (e.g. a global or something scoped within the main function).
Try something like that. The way you do it "kills" myArray cause if it locally defined.
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
free(array);
}
int * getArray() {
int * myArray = malloc(sizeof(int) * 3);
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
//{4, 65, 23};
return myArray;
}
int main() {
replaceNumberAndPrint(getArray());
}
More : http://www.cplusplus.com/reference/clibrary/cstdlib/malloc/
Edit: As Comments correctly pointed out: A better way to do it would be that :
#include <stdio.h>
#include <stdlib.h>
void replaceNumberAndPrint(int * array) {
if(!array)
return;
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n" , array[2]);
}
int * createArray() {
int * myArray = malloc(sizeof(int) * 3);
if(!myArray)
return 0;
myArray[0] = 4;
myArray[1] = 64;
myArray[2] = 23;
return myArray;
}
int main() {
int * array = createArray();
if(array)
{
replaceNumberAndPrint(array);
free(array);
}
return 0;
}
myArray goes out of scope as soon as you leave getArray. You need to allocate space for it on the heap instead.
Your code invokes Undefined Behaviour because myArray goes out of scope as soon as getArray() returns and any attempt to use (dereference) the dangling pointer is UB.
Local variables go out of scope upon return, so you can't return a pointer to a local variable.
You need to allocate it dynamically (on the heap), using malloc or new. Example:
int *create_array(void) {
int *array = malloc(3 * sizeof(int));
assert(array != NULL);
array[0] = 4;
array[1] = 65;
array[2] = 23;
return array;
}
void destroy_array(int *array) {
free(array);
}
int main(int argc, char **argv) {
int *array = create_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
destroy_array(array);
return 0;
}
Alternatively, you can declare the array as static, keeping in mind the semantics are different. Example:
int *get_array(void) {
static int array[] = { 4, 65, 23 };
return array;
}
int main(int argc, char **argv) {
int *array = get_array();
for (size_t i = 0; i < 3; ++i)
printf("%d\n", array[i]);
return 0;
}
If you don't know what static means, read this question & answer.
Right way to do this is as follows:
struct Arr {
int array[3];
};
Arr get_array() {
Arr a;
a.array[0] = 4;
a.array[1] = 65;
a.array[2] = 23;
return a;
}
int main(int argc, char **argv) {
Arr a = get_array();
for(size_t i=0; i<3; i++)
printf("%d\n", a.array[i]);
return 0;
}
To understand why you need to do this, you need to know how sizeof(array) works. C (and thus c++) tries hard to avoid copying the array, and you need the struct to go past that. Why copying is needed is because of scopes -- the get_array() function's scope disappears and every value still needed from that scope will need to be copied to calling scope.
C++ solution:
"May I have any access to a local variable in a different function? If so, how?"
The answer is no, not after the function has ended. Local variables are destroyed at that point.
In C++ the way to deal with returning arrays is to manage them in a container like a std::array (fixed size) or a std::vector (dynamic size).
Eg:
void replaceNumberAndPrint(const std::array<int, 3>& array) {
printf("%i\n", array[0]);
printf("%i\n", array[1]);
printf("%i\n", array[2]);
}
std::array<int, 3> getArray() {
std::array<int, 3> myArray = {4, 65, 23};
return myArray;
}
In the second function the returned value is optimized by the compiler so you don't pay the price of actually copying the array.
In this code you have used pointer to local objects but when a function returns all local variables goes out of scope. If you will allocate memory (using malloc() function for allocation) then no data will be lost or overwrite.
int* getArray(int size) {
int *myArray = (int*)malloc(size*sizeof(int));
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}
int main() {
int i;
int *vector = getArray(3);
for(i=0;i<3;i++)
{
printf("%i\n",vector[i]);
}
getch();
return 0;
}
This code will print all the array elements and no overwritten will be happened.
Static ..or.. Global within your .c will do the trick ;)
However the entire time the program will occupy those 3 bytes BUT you avoid doing malloc on simple things like this (malloc recommended for big arrays)
On the other hand if the outside function modify the pointer, then the internal 'myArray' will be modified cause it points to it, that's it
int myArray[3];
int * getArray() {
myArray[0] = 4;
myArray[1] = 65;
myArray[2] = 23;
return myArray;
}

returning 2D array having error, need concept

I tried different methods but eventually got errors. Please give a solution and a brief explanation of the concept.
uint8_t **subBytes()
{
int i,j;
uint8_t r,c;
uint8_t t[4][4];
for(i=0;i<4;i++)
{
for (j=0;j<4;j++)
{
r = pt[p1][j] & 0xf0;
r = r >> 4;
c = pt[p1][j] & 0x0f;
t[i][j] = (uint8_t *) malloc(sizeof(uint8_t));
t[i][j] = sBox[r][c];
}
p1++;
}
return t;
}
int main()
{
uint8_t **temp;
temp = subBytes();
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%x ", temp[i][j]);
}
printf("\n");
}
}
This is my original code. Here, I used malloc, but then too it is not working.
the memory space alloced for your matrix is a LOCAL VARIABLE.
The scope of a LOCAL VARIABLE is only within that function.
When you returned it is discarded.
In your code it is uint8_t t[4][4].
t is discarded right after return t.
So you return nothing and may cause undefined behavior.
You should use malloc to alloc memory for your matrix not just declare it locally.
in code
uint8_t **t.
t = malloc(sizeof(uint8_t) * 16 ) //size of a 4x4 matrix
then use t as a two dimension array and return t.like
t[0][0] = 1;
don't forgot to free it after use it out side of the function.
free(t);
m is LOCAL VARIABLES. When add returns, m is DESTROYED!
You SHOULD NOT return the pointer or reference of local variables. Look the following code:
int foo() { return 1; }
int *bar() { int i = 1; return &i; }
When I call foo(), it returns 1.
When I call bar(), it try to return the local variables, i's address. But when bar() returns, the i variable is DESTROYED! So the return pointer become trash pointer. (Sorry, I don't know how to say that term in English;)
You should use like that:
void bar(int *ret) { *ret = 1; }
int i;
bar(&i); /* now i is 1 */
or
int *bar()
{
int *p = (int *)malloc(sizeof(int));
*p = 1;
return p;
}
int *pi = bar();
/* now *pi is 1 */
...
free(pi); /* You MUST free pi. If not, memory lack is coming~ */
(I recommend first one. the second one require free and it can be mistaken.)
When a variable is declared (statically allocated) within a function, it is placed on what is called the stack, which is only local to that function. When the program leaves that function's scope, the variable is no longer guaranteed to be preserved, and so the pointer you return to it is essentially useless.
You have three options to fix your error:
Don't do it
Simply declare the array in the same function as you use it, don't bother with trying to return a pointer from another function.
Pass a pointer to a variable local to main
A pointer to a variable local to main will be valid until main returns, so you could do this:
void subBytes(uint8_t t[4][4]){
//perform initialization of matrix on passed variable
}
int main(){
uint8_t temp[4][4];
subBytes(&temp);
//...
}
Dynamic Allocation
This will probably give you more errors than it will solve in this case, but if you are heartset on returning a pointer to a matrix, you could malloc() the memory for the array and then return it, but you would have to free() it afterwards.
In C, there are several ways to dynamically allocate a 2D array. The first is to create it as a single array, and operate on the indices to treat it as 2D.
//...
int *arr = (int *)malloc(rows*cols*sizeof(int));
for (int i = 0; i<rows; i++){
for (int j = 0; j<height; j++){
arr[i*height + j] = i*j; //whatever
}
}
return arr; // type is int *
//...
Note that in this method, you cannot use array[i][j] syntax, because the compiler doesn't know the width and height.
The second way is to treat it as an array of arrays, so store an array of pointers to other arrays.
//...
int **arr = (int **)malloc(rows*sizeof(int *));
for (int i = 0; i<rows; i++){
arr[i] = (int *)malloc(cols*sizeof(int));
}
arr[i][j] = 86; //whatever
return arr; //type is int **
//...
For further information, see: Pointer to Local Variable

Function Pointer Array in C

I want to make a function pointer array and be able to call them in a for-loop. How can I achieve this? I have tried:
void (**a) (int);
a[0] = &my_func1;
a[1] = &my_func2;
a[2] = &my_func3;
for ( i = 0; i < 3; i++){
a[0]();
(*a[0])(); // Neither does work
}
But I am missing some syntax I guess:
error: too few arguments to function ‘*(a + (long unsigned int)((long unsigned int)i * 8ul))’
The function you declare is expected to take an int as a parameter:
a[0](1);
Also note that you declare a pointer to pointer for the functions, but you don't allocate any memory for them (I assume this is only in the example) Otherwise it should probably be:
void (*a[3]) (int);
You are declaring that a is a pointer to a pointer to (or an array of pointers to) a function that takes an int as a parameter - so you need to pass an int when you call the functions, e.g. a[0](42);.
I guess the below code is what you need.
typedef void * func_pointer(int);
func_pointer fparr[10];
for(int i = 0; i<10; i++)
{
fparr[i](arg); //pass the integer argument here
}
1) Where have you allocated or defined array to store function addresses?
2) in loop you are always calling (*a[0])();,There should be loop counter
You forgot to give an argument to your function.
void (**a) (int); // here it takes an int argument
a[0] = &my_func1;
a[1] = &my_func2;
a[2] = &my_func3;
for ( i = 0; i < 3; i++){
a[0](); // here you do not give an argument
}
But be careful, you do not allocate memory to your a array, and it fails with a nice segmentation fault error.
void my_func1(int i) {
;
}
void my_func2(int i) {
;
}
void my_func3(int i) {
;
}
int main() {
void (**a) (int);
a = malloc(3*sizeof(void*)); // allocate array !
a[0] = &my_func1;
a[1] = &my_func2;
a[2] = &my_func3;
for (int i = 0; i < 3; i++){
a[i](1); // respect your own function signature
}
free(a); // it's always a good habit to free the memory you take
return 0;
}
You can typedef void (*pfun)(int); and then pfun a[3]; is the array you want.
The following code may work for you:
typedef void (*pfun)(int);
int main() {
pfun a[3];
a[0] = myfunc1; // or &myfunc1 whatever you like
a[1] = myfunc2;
a[2] = myfunc3;
}
You can define your function-array with the needed size and initialize it with your functions like:
void my_func1(int x){}
void my_func2(int x){}
void my_func3(int x){}
void (*a[])(int)={my_func1,my_func2,my_func3};
int i;
for(i=0;i<sizeof a/sizeof*a;++i)
a[i](i);
The address-operator '&' before any function-name is redundant.

Resources