I dont understand the appearent discrepency in the treatment of the variabe x, y, and z.
Why y isn't treated as x and z?

#include <stdio.h>
#include <string.h>

int main()
{
    char result[100] = "Philippe Dupont 30";
    char x[50];
    char y[50];
    int z;
    /*We use sscanf to give a value to the
    three variables x, y and z. the two first are strings 
    and don't need &.*/
    sscanf(result, "%s%s%d", x, y, &z);
    /*Printing the value of the variables works fine.*/
    printf("%s\n", x);
    printf("%s\n", y);
    printf("%d\n", z);

    /*But when I want to print a string in which the variables are, the variable y output
    is an address, not as for x and z*/
    printf("My first name is %s \n my last name is %d \n and I am %d years old\n", x, y, z);

    return 0;
}

/*OUTPUT:
Philippe
Dupont
30
My first name is Philippe
my last name is -478321712
and I am 30 years old

*/

Dani AI

Generated

This is a classic format-specifier / varargs mismatch. As pointed out, the second value was printed with an integer specifier instead of a string specifier. printf uses the format string to interpret the raw arguments; if the format does not match the actual types, the program has undefined behavior. That is why the separate prints for x and z looked fine but the combined printf showed a garbage number for y.

Practical fixes and hardening (build on 's correction and ’s original code):

  • Check sscanf return value to ensure all fields were parsed:

    int n = sscanf(result, "%49s %49s %d", x, y, &z);
    if (n != 3) { /* handle parse error */ }
  • Prevent buffer overflow by using width limits (buffers are 50 bytes in the example).

  • Enable compiler warnings to catch mismatched formats early:

    gcc -Wall -Wextra -Wformat -Werror -o prog prog.c
  • Prefer safer input flows for user data (use fgets for input, then parse).

Reason: mismatched format specifiers produce undefined behavior that can vary by platform and optimization. Fixing the specifier, adding bounds and checks, and turning on warnings makes the bug deterministic and prevents security issues.

Recommended Answers

All 2 Replies

In line 21, you are printing the string 'y' as an integer (%d). Change it to %s as follows

printf("My first name is %s \n my last name is %s \n and I am %d years old\n", x, y, z);

Stupid error %d instead of %s

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.