2

While inputting the strings I am getting warnings like

error: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[10]'

In application

#include<stdio.h>
int main(void)
{
    char a[100][10];
    int s,i,k=0;
    scanf("%d",&s);
    for(i=0;i<s;i++)
    {
        scanf("%s",&a[i]);
    }
}
1
  • Remember this : Whenever you scan a %s via scanf, don't use the & with the variable name. Commented Jul 26, 2015 at 6:00

3 Answers 3

5
scanf("%s",&a[i]);
           ^ This will pass address of `a[i]` thus giving error.

As %s specifier expects a pointer to the first character in a character array. And using & with a[i] will evaluate char (*)[10].

Instead this should be done -

scanf("%9s", a[i]);
Sign up to request clarification or add additional context in comments.

3 Comments

can we use %s instead of %9s because i don't want extra spaces between strings when printing them.
@nani Yes you can use %s no problem in that.
@nani but what do you mean by extra space because %9s will store just first 9 characters in array not more than that. So using %s will not harm you anyway .
1

Yes because there is an difference between array and pointer to an array. You may use char *a[100]; as a pointer to array of 100 elements and use malloc/calloc every time to allocate space dynamically. The program would look like:

#include<stdio.h> 
#include<stdlib.h>         
int main(void)
{
    char *a[100];
    int s,i,k=0;
    scanf("%d",&s);
    for(i=0;i<s;i++)
    {
        a[i] = (char *) malloc (sizeof(char)*10);
        scanf("%s",a[i]);
        printf("%s",a[i]);
    }
}       

1 Comment

You can also use the 2D array in the question, which means this answer isn't all that much help — it provides an alternative mechanism, rather than fixing the preferred (and perfectly reasonable) mechanism used in the question.
0

code: scanf("%s",&a[i]);

&a[i] point char **, because a is 2D char array.

code instead : scanf("%s",a[i]); will get right result

1 Comment

&a[i] is a char(*)[10], not a char**

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.