'Why does giving '&' for a string in scanf() give no error?
char text[10];
printf("Enter text[Max characters= 9]: ");
scanf("%[^\n]s",&text);
I wrote this by mistake and kept working with it, later on I noticed the mistake in scanf but my question is why was there no error? 3rd line means save the string at the address of address of first element of the array, correct?
Solution 1:[1]
Your a.c source code
#include <stdio.h>
int main()
{
char text[10];
printf("%p\n", text);
printf("%p\n", &text);
printf("Enter text[Max characters= 9]: ");
scanf("%[^\n]s",&text);
printf("%p\n", text);
printf("%p\n", &text);
return 0;
}
As you can see on the following logs
bash-5.1$ gcc a.c -o a
bash-5.1$ ./a
0x7fff602b2166
0x7fff602b2166
Enter text[Max characters= 9]: afaefa
0x7fff602b2166
0x7fff602b2166
Text and &text points to the same address. &text on a scanf doesn't break your code but its redundant.
But if you compile with -Wall flag
bash-5.1$ gcc a.c -o a -Wall
a.c: In function ‘main’:
a.c:8:15: warning: format ‘%[^
’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat=]
8 | scanf("%[^\n]s",&text);
| ~~~^~ ~~~~~
| | |
| | char (*)[10]
| char *
Solution 2:[2]
The raw_input function returns a string.
What you could do is split() the string and map the a function over it:
In [1]: test = 'True False True False False'
In [2]: test.split()
Out[2]: ['True', 'False', 'True', 'False', 'False']
In [3]: map(lambda x: x in ['True', '1'], test.split())
Out[3]: [True, False, True, False, False]
The list in the lambda expression should contain all the values you want to recognize als True. It would be slightly better to use a function in map, so you can raise an exception when you find something that isn't unambiguously True or False.
Note that this only works well for a list of true/false values. For a nested and bracketed list, using ast.literal_eval as unutbu suggests is clearly the better solution:
In [1]: import ast
In [2]: ast.literal_eval('[[True], [False], [True]]')
Out[2]: [[True], [False], [True]]
But this will require you to use complete Python syntax. If you want to use 0 and 1 instead of True and False, remember to use the bool dtype:
In [5]: a = ast.literal_eval('[[1, 0, 1], [0, 1, 0], [0,0,1]]')
In [6]: np.array(a, dtype=bool)
Out[6]:
array([[ True, False, True],
[False, True, False],
[False, False, True]], dtype=bool)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabriel Pellegrino |
| Solution 2 |
