Home > Mobile >  How do i use pointer as parameter
How do i use pointer as parameter

Time:10-26

I write something to get famliar with pointer.

    void print_line(int64_t number, char *string)
{
    (void)number;
    (void)string;

    printf("%d %s \n", number, *string);
    return;
}

int main()
{
    print_line(42, "Hello World!");
    return 0;
}

I expect the outcome to be 42 and "Hello World!". However it is 42 (null). I assume that i used pointer in a wrong way. Where was my mistake? Why is the address empty?

Thanks a lot!

CodePudding user response:

The first parameter has the type int64_t

void print_line(int64_t number, char *string)

On the other hand, the conversion specifier %d serves to output numbers of the type int. So by this reason this call

printf("%d %s \n", number, *string);

is already incorrect and invokes undefined behavior because a wrong conversion specifier is used with an object of the type int64_t.

You could use the conversion specifier %d in the call of printf if the first parameter of your function had the type int or unsigned int and in the last case if the value of the type unsigned int is representable in the type int.

Moreover the conversion specifier %s expects a pointer of the type char * while you passed the expression *string that has the type char.

What you need is to include the header <inttypes.h>

#include <inttypes.h>

and change the call of printf like

printf( "%" PRId64 " %s\n", number, string );

Here is a demonstration program.

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

void print_line( int64_t number, const char *string )
{
    printf( "%" PRId64 " %s\n", number, string );
}

int main(void) 
{
    print_line( 42, "Hello World!" );
        
    return 0;
}

The program output is

42 Hello World!

CodePudding user response:

printf %s expects a pointer to the first character of a string. That's what string is.

printf("%d %s\n", number, *string);

should be

printf("%d %s\n", number, string);

Make sure to enable your compiler's warnings (e.g. -Wall -Wextra -pendatic using gcc and glang).

  • Related