0

My code is very simple just basic IO. Now when I use this code it works perfectly.

#include <stdio.h>

int main()
{
    int age = 0;
    char name[100]; //Unlike c++ We need to specify char limit instead of "Name", so name can't go above 99 char + 1 terinator
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Enter your name: ");
    scanf("%s", name);// dont need & for char
    printf("Your name is %s and your age is %d\n", name, age);
    return 0;
}

Now

#include <stdio.h>

int main()
{
    int age = 0;
    char name[100]; //Unlike c++ We need to specify char limit instead of "Name", so name can't go above 99 char + 1 terinator
    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Enter your name: ");
    scanf("%s", &name);// dont need & for char
    printf("Your name is %s and your age is %d\n", name, age);
    return 0;
}

when I make changes in line 10. and add &name. compiler throws this error. Why is that?

p2.c:10:17: error: format specifies type 'char *' but the argument has type 'char (*)[100]' [-Werror,-Wformat]
    scanf("%s", &name);// dont need & for char
           ~~   ^~~~~

I don't know much about C.

halfer
  • 19,824
  • 17
  • 99
  • 186
lookabove
  • 19
  • 1
  • Because in second code snippet ```%s``` need starting address of char array. So, ```name``` stores starting address of array. Where as in char ```%c``` needs address as well. In ```char ch;``` ```ch``` won't return address you need to use ```&ch```. – Sathvik Sep 12 '20 at 18:05
  • @Sathvik: `name` does not store an address - name is *converted* to an address as necessary. – John Bode Sep 12 '20 at 23:52

3 Answers3

3

Strings in C are simply sequences of characters. The %s format specifier thus expects a pointer to char such that it can write whatever scanf reads into the character sequence at the memory location pointed to by that pointer. In your case name is a character array and not a pointer, but in C you can often use arrays in contexts where pointers are expected, we say that the array decays to a pointer to its first member.

Peter
  • 2,919
  • 1
  • 16
  • 35
1

The scanf function takes a pointer of the variable whose value is to be set.

For other types like int, we use & operator which specifies the address of the variable whereas for char[] the variable name is converted to the pointer to the first element of the array so we don't need a &.

Deepak Patankar
  • 3,076
  • 3
  • 16
  • 35
0

Strings are arrays of chars. Arrays are passed by reference in C.

So when you pass array to the function you actually pass the pointer.

0___________
  • 60,014
  • 4
  • 34
  • 74