c - 从 C 中的用户那里获取的字符串正在被加扰

标签 c scanf cstring gets

我编写了以下 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/

相关文章:

为 Windows(在 Linux 中)编译带有 GLUT 头文件的 C 程序

c - 在 clang 中启用优化时是否定义了内置宏?

c - 使用 scanf() 输入字符串

c - 程序不返回扫描字符

c - 有什么技术可以用来测试一个字符串是否全是空格?

c - 用多个空格断开 C 中的字符串

c - 主函数的返回类型

c - 带分隔符的 fscanf 在 C 中无法正常工作

ios - NSString 字符串与 CString :encoding: - not copying the Cstring?

c++ - 为什么这个简单的 C++ C 风格字符串反转方法会抛出访问冲突异常?