Can you return the type of a pointer to a pointer in a function?
I know that you can return a pointer type from a function. ex. void *foo()
Can you return the type of a pointer to a pointer in a function? ex.void **foo2()
Here's more information on my question:
I am trying to assign ptr-to-ptr, tmp2 to block [i] [j] and then return tmp2. blocks [i] [j] are also ptr-to-ptr.
I'm confused to manipulate ptr with ptr-to-ptr: I'm not sure what return ((tmp2+i)+j);
is causing the segmentation fault in the string printf("2---%d\n", **tmpPtr2);
. For debugging purposes, I'm trying to print: printf("%d\n", *( (*(tmp2+i)) +j) );
However, this throws a new segmentation fault.
#include <stdio.h>
#include <stdlib.h>
int **blocks, **tmp2;
int n = 10;
int **findBlock2(int b){
int i, j ;
for (i=0; i<n; i++){
for (j=0; j<n; j++){
if (blocks[i][j]==b){
printf("%d\n", blocks[i][j]);
//Segmentation fault
printf("%d\n", *((*(tmp2+i))+j) );
return ((tmp2+i)+j);
}
}
}
return NULL;
}
int main(int argc, const char * argv[]) {
int i, j;
int **tmpPtr2;
//allocate memory space and assign a block to each index
blocks=malloc(n * sizeof *blocks);
for (i=0; i<n; i++) {
blocks[i]=malloc(n * sizeof(*blocks[i]));
blocks[i][0]=i;
}
if ((tmpPtr2=findBlock2(4))==NULL) return -1;
//Segmentation Fault
printf("2---%d\n", **tmpPtr2);
return 0;
}
Update to answer my question:
(1) Adding t tmp2=blocks;
to the beginning of findBlock2 () removed both segfaults.
(2) return ((tmp2+i)+j);
shows how to manipulate a ptr-to-ptr pointing to a ptr-to-ptr or 2D array
(3) printf("%d\n", *( (*(tmp2+i)) +j) );
shows how to do it (2) and act it out.
Hope it helps others.
source to share
Yes, just like with any pointer variables.
#include <stdio.h>
#include <stdlib.h>
int ** function(){
int ** matrix = malloc(sizeof(int*));
*matrix = malloc(sizeof(int));
matrix[0][0] = 5;
return matrix;
}
int main()
{
int **matrix = function();
printf("%d",matrix[0][0]);
free(matrix[0]);
free(matrix);
return 0;
}
Adding to another part. In your function, findBlock2
apart from accessing the invalid reference that was already specified, it seems that your goal is to return a reference to the block that the statement is executing if
. If so, it is sufficient to point to a pointer to int*
.
int *findBlock2( int b )
/////////////////
return ( *(blocks+i)+j );
source to share
You probably want a 2D array in a not slow, fragmented lookup table. In this case, follow these steps:
#include <stdlib.h>
void* alloc_2D (size_t x, size_t y)
{
return malloc (sizeof (int[x][y]));
}
int main (void)
{
const size_t X = 5;
const size_t Y = 3;
int (*arr_2D)[Y] = alloc_2D(X, Y);
// X dimension was omitted in declaration to make array syntax more intuititve:
arr_2D[i][j] = something;
...
free(arr_2D);
}
source to share