Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of %.*s in this program [closed]

Tags:

c

I have the following program:

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

int main()

{
    static char string[12];
    int length,c,d;
    printf("Enter a string :");
    gets(string);
    length=strlen(string);
    printf("\nLength of the string is %d",length);
    for(c=0;c<=length-2;c++)
    {
        d=c+1;
        printf("\t%.*s\n",d,string);
    }
    for(c=length;c>=0;c--)
    {
        d=c+1;
        printf("\t%.*s\n",d,string);
    }
} 

I am very much confused about the usage of %.*s in the printf statement. I know %s is used for displaying strings, but I am confused the usage of .* before s in this program. Also there is only one datatype (%s) mentioned inside the quotation marks in the printf statement, but there are two variables mentioned in the printf statement.

like image 802
Mahi Avatar asked Aug 11 '13 06:08

Mahi


1 Answers

It is a precision component, which specifies maximum number of bytes for string conversions. Asterisk (*), uses an integer argument, which specifies the value (for precision) to be used.

As an example, the following code:

#include <stdio.h>

int main(int argv, char **argc)
{
    char *s = "hello, world";
    printf("%.*s\n", 4, s);
    return 0;
}

gives output:

hell
like image 184
mohit Avatar answered Oct 01 '22 08:10

mohit