1

I am having a little trouble coding in c. I am new to the language, I know java significantly better, and strings in c give me the biggest headache.

When I implement this code...

int num, n, i, j;
printf("How many students will you enter (min. 5)\n");
scanf("%d",&num);

char *fn = (char*)malloc(num * sizeof(char *));
char *ln = (char*)malloc(num * sizeof(char *));

for (n=0; n<num; n++)
{
    *(fn+n) = (char *)malloc(20 * sizeof(char));
    *(ln+n) = (char *)malloc(20 * sizeof(char));
}

printf("Enter students (firstName lastName score)\n");
for(i=0; i<num; i++)
{
    scanf("%s %s", &fn[i], &ln[i]);
}
for (i=0; i<num; i++)
{
    printf("%s %s\n", &fn[i], &ln[i]);
}
printf("You did it!");

it prints the first letter of each first and last name, then the entire name of the last person I enter. For example,

Jane Doe
Greg Smith

as the user input would output

JGreg DSmith
Greg Smith

Thank you so much for any help!

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
Abby
  • 11
  • 1

1 Answers1

0

Try this...

char **fn = (char*)malloc(num * sizeof(char *));
char **ln = (char*)malloc(num * sizeof(char *));

at the time of declaration

char *fn = (char*)malloc(num * sizeof(char *));
char *ln = (char*)malloc(num * sizeof(char *));

char *fn; declares a pointer to character, which can hold a string, but not a array string.

check it out.