Appley
Appley

Reputation: 23

The format specified for uint64_t is giving an error

When I try to compile this code I get the errors saying error: format ‘%lu’ expects argument of type ‘long unsigned int *’, but argument 2 has type ‘uint64_t **’ {aka ‘long unsigned int **’} and error: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘uint64_t *’ {aka ‘long unsigned int *’}

So how am I supposed to format testInteger to take uint64?

  #include <stdint.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(void) {
    
        uint64_t* testInteger = malloc(sizeof(uint64_t));
    
        scanf("%lu", &testInteger);  
        printf("%lu", testInteger);
        free(testInteger);
    }

Upvotes: 1

Views: 1522

Answers (3)

chux
chux

Reputation: 153303

With uint64_t* testInteger = ... scanf("%lu", &testInteger);, "%lu" does not match a uint64_t**, but a unsigned long *.

how am I supposed to format testInteger to take uint64?

To read a uint64_t (not uint64), use "%" SCNu64 from <inttypes.h> and uint64_t *.
To write a uint64_t (not uint64), use "%" PRIu64 from <inttypes.h> and uint64_t.

#include <inttypes.h>
...

uint64_t* testInteger = malloc(sizeof *testInteger);
if (testInteger != NULL) {
  if (scanf("%" SCNu64, testInteger) == 1) {//No & here,testInteger is a pointer 
    printf("%" PRIu64 "\n", *testInteger);  // Use a * here
  }
}

It is a good idea to test for the success of malloc() and scanf().

Upvotes: 3

Jonathon S.
Jonathon S.

Reputation: 1980

Variable testInteger is a pointer. In the first, instance &testInteger is realized as a pointer to a pointer since the pointer address is being referenced by &. In the second case, a pointer is being used directly. Function printf expects an integer value and function scanf expects a pointer where %lu is used. For scanf just use testInteger directly and for printf use *testInteger which will use the value stored rather than the pointer itself.

Upvotes: 1

Dzemo997
Dzemo997

Reputation: 336

scanf as argument receive pointer, since testInteger is already pointer your &testInteger will pass pointer on pointer and that is invalid. You should only pass testInteger to scanf, not &testInteger. And in the print testInteger should be dereferenced. Your code should be:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {

  uint64_t* testInteger = malloc(sizeof(uint64_t));

  scanf("%lu", testInteger);
  printf("%lu", *testInteger);
  free(testInteger);
}

Upvotes: 1

Related Questions