Scanf and p conversion specifier

The C11 spec says that the type of the argument %p

should be void **

in the case of a function scanf()

, but I can't figure out how to enter the address and store it in void **

. Infact, if I try to do:

void **p;
scanf("%p", p);

      

I am getting segmentation error.

PS Specification C11:

The corresponding argument must be a pointer to a pointer to void

+3


source to share


4 answers


NOTE. There was no mention of the standard in the original post c11

.

Ok, according to the spec document c99

, chapter 7.19.6. 1 2, paragraph 8 12,

p

Corresponds to an implementation-defined set of sequences, which must be the same as the set of sequences that can be obtained by converting the% p function fprintf. The corresponding argument must be a pointer to a pointer to void. The input element is converted to a pointer value in a specific way. If the input element is a value converted earlier during the execution of the same program, the pointer, the result of which will be compared equal to this value; otherwise, the conversion behavior of% p is undefined.

So it is not void **

, rather void *

.



Further . The segmentation fault is caused by the use of an uninitialized pointer p

in scanf()

. You didn't allocate memory p

before using [pass it scanf()

as an argument].

Like others have suggested, you can use something like

void *p;
scanf("%p", &p);

      

here the specific address &p

actually matters pointer to a pointer to void

.

+1


source


void **p;
scanf("%p", p);

      

doesn't work for the same reason as

int *i;
scanf("%i", i);

      

doesn't work - you are writing an uninitialized pointer (or telling scanf

to write at least one).



It works:

int i;
scanf("%i", &i);

      

so:

void *p;
scanf("%p", &p);

      

+6


source


You haven't initialized p

. Try:

void *p;
scanf("%p", &p);

      

This assumes an address p

that is valid.

+1


source


The standard says it %p

must have a type argument void *

. You need to declare p

as void *

and then

scanf("%p", &p);    

      

The reason you get a segfault is because in void **p

, p

doesn't point anywhere.

0


source







All Articles