[英]printing string from the array
as you can see this while I run this it works perfectly till "The array is " but cant show the string that I enter正如您在我运行它时所看到的那样,它可以完美运行,直到“数组为”但无法显示我输入的字符串
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
int size;
char arr[size];
printf("input size of array ");
scanf("%d", &size);
printf("\ninput elements of array ");
for (int i = 0; i < size; i++)
{
scanf("%s", &arr[i]);
}
printf("\nThe array is ");
for (int i = 0; i < size; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}
There are multiple things wrong with this code.这段代码有很多问题。
int size;
char arr[size];
You are declaring a char
array arr
with size
elements, but size is not yet initialized yet and may be any value.您正在声明一个带有
size
元素的char
数组arr
,但 size 尚未初始化,可能是任何值。 Also note that "deciding the size of an array at runtime" is only valid in modern C (C99 onwards).另请注意,“在运行时确定数组的大小”仅在现代 C(C99 及更高版本)中有效。 You should first read
size
and only after the scanf
declare arr
.您应该首先阅读
size
并且仅在scanf
声明arr
之后阅读。
for (int i = 0; i < size; i++){
scanf("%s", &arr[i]);
}
You read a string ( %s
) with scanf
and try to store it in a char
( &arr[i]
points to the ith char in arr
).您使用
scanf
读取了一个字符串( %s
)并尝试将其存储在一个char
中( &arr[i]
指向arr
中的第 i 个字符)。 Every C string is atleast 1 character long (the terminating \0
character), you are trying to store multiple characters in a single char
.每个 C 字符串至少有 1 个字符长(终止
\0
字符),您试图将多个字符存储在一个char
中。 Instead use而是使用
scanf("%s", arr);
Note that scanf
is not safe.请注意,
scanf
并不安全。 Even if you enter more than size
characters, it will still try to store them in arr
.即使您输入超过
size
个字符,它仍会尝试将它们存储在arr
中。 That leads to undefined behaviour, because arr
is too small.这会导致未定义的行为,因为
arr
太小了。 Instead you can use fgets
, that lets you set the number of characters to read.相反,您可以使用
fgets
,它可以让您设置要读取的字符数。
for (int i = 0; i < size; i++){
printf("%s\n", arr[i]);
}
Here you are trying to print a String ( %s
), but you are passing a char
( arr[i]
is the ith char in arr
).在这里,您尝试打印一个字符串(
%s
),但您传递的是一个char
( arr[i]
是arr
中的第 i 个字符)。 Instead use而是使用
printf("%s\n", arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.