Pointer and malloc issue
Posted
by
Andy
on Stack Overflow
See other posts from Stack Overflow
or by Andy
Published on 2011-02-12T22:35:50Z
Indexed on
2011/02/12
23:25 UTC
Read the original article
Hit count: 186
I am fairly new to C and am getting stuck with arrays and pointers when they refer to strings. I can ask for input of 2 numbers (ints) and then return the one I want (first number or second number) without any issues. But when I request names and try to return them, the program crashes after I enter the first name and not sure why.
In theory I am looking to reserve memory for the first name, and then expand it to include a second name. Can anyone explain why this breaks?
Thanks!
#include <stdio.h>
#include <stdlib.h>
void main ()
{
int NumItems = 0;
NumItems += 1;
char* NameList = malloc(sizeof(char[10])*NumItems);
printf("Please enter name #1: \n");
scanf("%9s", NameList[0]);
fpurge(stdin);
NumItems += 1;
NameList = realloc(NameList,sizeof(char[10])*NumItems);
printf("Please enter name #2: \n");
scanf("%9s", NameList[1]);
fpurge(stdin);
printf("The first name is: %s",NameList[0]);
printf("The second name is: %s",NameList[1]);
return 0;
}
© Stack Overflow or respective owner