我编写了以下 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);
}
输入样本:
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
问题:
1)为什么一个字符串根本不作为输入?
2) 为什么显示的字符串是这样乱序的?
如果我使用 gets() 或 fgets() 代替 scanf(),问题是一样的。
最佳答案
arr[i] 已经是一个指针,你不需要 &
关于c - 从 C 中的用户那里获取的字符串正在被加扰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5360148/