Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char arrays and scanf function in C

Tags:

arrays

c

scanf

I expected to get errors in following code, but I did not. I did not use & sign. Also I am editing array of chars.

#include <stdio.h>

int main()
{
     char  name[10] ="yasser";
     printf("%s\n",name);

     // there is no error , 
     // trying to edit array of chars, 
     // also did not use & sign.  
     scanf("%s",name); 

     // did not use strcpy function also.
     printf("%s\n",name);           

     return 0;
}
like image 671
BratBart Avatar asked Jan 26 '16 22:01

BratBart


People also ask

What is scanf function in C?

In the C programming language, scanf is a function that reads formatted data from stdin (i.e, the standard input stream, which is usually the keyboard, unless redirected) and then writes the results into the arguments given.

What is a character array in C?

In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings. C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).

What is the scanf for char?

This is the code: char ch; printf("Enter one char"); scanf("%c", &ch); printf("%c\n",ch);

What is the difference between character array and string in C?

String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char. Strings are immutable. Character Arrays are mutable.


1 Answers

I expected to get errors in following code, but I did not.I did not use & sign.

scanf("%s",name);

That's totally ok as name is already the address of the character array.

like image 139
artm Avatar answered Sep 21 '22 11:09

artm