Leone Randazzo
Leone Randazzo

Reputation: 1

questions about a particular string within printf

I found this C language fragment:

printf("[%d] %.*s\n", cnt++, temp - field, field);

where temp and field are char * and cnt is an integer.

But I don't understand the use of %.*s in format string within printf.

Can-please-any of you help me ?

Upvotes: 0

Views: 64

Answers (3)

givanse
givanse

Reputation: 14953

There are two parts for this answer,

  1. That line is doing pointer arithmetic, a way to calculate the length of a string; based on a convention used in your application perhaps.

    char *string = "abcdef";  
    char *p1 = string + 3; // def      
    char *p2 = string + 4; // ef    
    
    printf("%s - %s = %d\n", p1, p2, (int) (p1 - p2));
    

    output

    0x400709 - 0x40070a = -1

    Note that p2 is a shorter string, but a bigger pointer.

  2. .number is used to specify the precision of integers or the length of a string.

    // number precision
    printf("%.2f\n", 100.12345); // 100.12
    
    char *string = "abcdef";
    
    // print the first 3 characters only
    printf("%.3s\n", string); // abc
    
    // print the first X characters
    int dynamicLength = 2;
    printf("%.*s\n", dynamicLength, string); // ab
    

    Note that by using .* what you are saying is:

    I won't know the precision until the program is running.

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33533

From some documentation:

.*: The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

So, in your case, field has the value and temp-field its precision.

These percentage-sign symbols, for future reference are called format specifiers. (In fact I found the answer to this question by googling just that.)

Upvotes: 1

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

You can use .* in printf to specify that the precision is to be given as an argument. In your case, that argument is temp - field, the difference between the two pointers.

Upvotes: 1

Related Questions