Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test this C function

Tags:

c

pointers

I got a weird question to do as an exercise :

Write a function which take a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of a pointer of an int as a parameter and assign a value to it.

I think the function I wrote is right (please correct if it's not) but how can I test it ?

void function(int *********anInt)
{
    *********anInt = 5;
}

I tried :

int main(void) {
    int *********nbr = malloc(sizeof(int));
    function(nbr);
    printf("%d", *********nbr);
}

But I get a segfault, I just learned about malloc and pointers so I don't fully understand it.

like image 535
ItsASecret Avatar asked Jul 18 '13 15:07

ItsASecret


1 Answers

Of course, you can test it, although it looks weird.

#include <stdio.h>

void function(int *********anInt)
{
    *********anInt = 5;
}

int main()
{
    int n = 0;
    int *p1 = &n;
    int **p2 = &p1;
    int ***p3 = &p2;
    int ****p4 = &p3;
    int *****p5 = &p4;
    int ******p6 = &p5;
    int *******p7 = &p6;
    int ********p8 = &p7;
    function(&p8);
    printf("%d\n", n);
    return 0;
}
like image 107
md5 Avatar answered Oct 18 '22 23:10

md5