C 中从用户处获取的字符串正在被扰乱
我编写了以下 C 代码来获取用户的字符串列表。但存储的字符串给出了奇怪的值。
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char* arr[],int n)
{
int i=0;
char line[MAX_STRING_LENGTH];
for(i=0;i<n;i++){
arr[i]=malloc(MAX_STRING_LENGTH);
printf("Enter another string : ");
scanf("%s",&arr[i]);
//fgets(&arr[i],MAX_STRING_LENGTH,stdin);
}
printf("Strings read in correctly.... \n");
printf("Displaying out all the strings: \n");
for(i=0;i<n;i++){
printf("%s\n",&arr[i]);
}
}
void testStringInputs()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char* strings[n];
readInStrings(strings,n);
}
输入样本:
输入条目数:3
输入另一个字符串:Alladin
输入另一个字符串:Barack Obama
输入另一个字符串:字符串正确读取....
显示所有字符串:
阿拉巴拉奥巴马
巴拉奥巴马
奥巴马
问题: 1) 为什么一个字符串根本不被作为输入?
2)为什么显示的字符串是这样乱的?
如果我使用 gets() 或 fgets() 代替 scanf() ,问题是相同的。
I have written the following C code to get in a list of strings from the user. But the stored strings are giving out weird values.
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char* arr[],int n)
{
int i=0;
char line[MAX_STRING_LENGTH];
for(i=0;i<n;i++){
arr[i]=malloc(MAX_STRING_LENGTH);
printf("Enter another string : ");
scanf("%s",&arr[i]);
//fgets(&arr[i],MAX_STRING_LENGTH,stdin);
}
printf("Strings read in correctly.... \n");
printf("Displaying out all the strings: \n");
for(i=0;i<n;i++){
printf("%s\n",&arr[i]);
}
}
void testStringInputs()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char* strings[n];
readInStrings(strings,n);
}
Input Sample:
Enter the number of entries : 3
Enter another string : Alladin
Enter another string : Barack Obama
Enter another string : Strings read in correctly....
Displaying out all the strings:
AllaBaraObama
BaraObama
Obama
Problems:
1) Why is one string not taken in as input at all?
2) Why are the displayed strings scrambled like that?
The problem is the same if I use gets() or fgets() in place of scanf().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
arr[i] 已经是一个指针,你不需要 &
arr[i] is already a pointer, you don't need the &
删除 & (正如第一个回答者指出的)在
scanf("%s",&arr[i]);
和printf("%s\n",&arr[i] );
帮我解决了这个问题。另外,请注意,如果您在编译时发出最高警告,您的编译器会立即告诉您 &被放错地方了。Removing the & (as the first answerer noted) in
scanf("%s",&arr[i]);
and inprintf("%s\n",&arr[i]);
did the trick for me. Also, note if you compiled with warnings at their highest, your compiler would have told you right away that the & was misplaced.最好使用数组数组(二维)而不是指针数组。
我很难纠正你的代码。所以我将代码更改为这样
Its better to use an array of arrays(two dimensional) instead of array of pointers.
I had a tough time correcting your code. So I changed the code to this