Why am I getting warnings about this sample code? What is right?

I am learning C and reading scanf from this tutorial , where the following code block is included:

 #include <stdio.h> int main() { char str1[20], str2[30]; printf("Enter name: "); scanf("%s", &str1); printf("Enter your website name: "); scanf("%s", &str2); printf("Entered Name: %s\n", str1); printf("Entered Website:%s", str2); return(0); } 

However, I get warnings that:

 "Format specifies type 'char *' but the argument has type 'char (*)[20]' 

Is the textbook wrong?

+6
source share
3 answers

This should work for you:

 #include <stdio.h> int main() { char str1[20], str2[30]; printf("Enter name: "); scanf("%19s", str1); //^^ ^ Removed address operator //So only the right amount of characters gets read printf("Enter your website name: "); scanf(" %29s", str2); //^ Added space to catch line breaks from the buffer printf("Entered Name: %s\n", str1); printf("Entered Website:%s", str2); return(0); } 
+13
source

There is an error in the sample tutorial.

Edit:

 scanf("%s", &str1); 

to

 scanf("%s", str1); 

s A conversion specifier requires a char pointer, but you are passing a pointer to an array.

+7
source

Lines

 scanf("%s", &str1); 

and

 scanf("%s", &str2); 

really wrong (at least both contain a typo). They should be written as

 scanf("%s", str1); // no & operator 

and

 scanf("%s", str2); // ditto 

Arrays and array expressions are special in C. Unless it is a sizeof operand of either unary & operators or a string literal used to initialize another array in a declaration, an expression of the type "N is an array of T elements" will be converted (decay) to an expression of type " pointer to T ", and the value of the expression will be the address of the first element of the array.

The str1 expression is of type "20-element char array". If str1 appears in a context where it is not an operand of the sizeof or unary & operators, it will be converted to an expression of type "pointer to char ", and the value of the expression will be the same as &str1[0] ; therefore, you do not need to use & to read strings, as an array expression will be treated as a pointer. However, when it is the operand of the unary operator & , the conversion rule is not applied, and the expression type &str1 is a "pointer to a 20-element char array" ( char (*)[20] ). Hence your warning.

The str1 and &str1 will be the same (the address of the first array of elements matches the address of the array), but the types of expressions are different and have a type value. A pointer to a char will be handled differently than a pointer to a char array.

90% of C books and textbooks are shit; be very skeptical of any C reference that is not the actual standard. Harbison and Steele C: The Reference Guide (currently the 5th edition) has been my link to the link since the late 80s, but even it has minor errors.

+3
source

Source: https://habr.com/ru/post/980614/


All Articles