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 s开发者_StackOverflowtring : 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().
arr[i] is already a pointer, you don't need the &
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.
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
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char (*arr)[MAX_STRING_LENGTH],int n)
{
int i;
for(i = 0 ; i< n+1; ++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+1;i++){
printf("%s",arr[i]);
}
}
int main()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char strings[n][MAX_STRING_LENGTH];
readInStrings(strings,n);
return 0;
}
精彩评论