Search code examples
cscanfcstringgets

Strings taken from user in C are being scrambled


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().


Solution

  • Removing the & (as the first answerer noted) in scanf("%s",&arr[i]); and in printf("%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.