![]() |
|
#1
|
|||
|
|||
|
How to use malloc in C?
Hi,
I am a newbie in programming in C language. I wanted to use malloc function to make a data storage and use it to store some strings and then show them up. So I coded what you see below but it doesn't work properly. I doesn't accept strings and also when it tries to show the results all the data is displayed disorderly. Even using " a , b , c , d , e " as the input data won't result in showing " a , b , c , d , e " as output data. I hope someone can shed some light and let meknow how to correct the code. Also as far as I know we don't need to use "&" operator with printf(); function,but I had to use it or my code would result in crash. I don't know why this behaviour is emerged. That's strange for me :!: Thanks in advance. Best Regards, Zest. Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
char * pi;
int i,r;
puts("start");
pi = (char *) malloc(50 * sizeof(char));
for(i = 0; i < 5; i++)
{
r = scanf("%s",&pi[i]);
if(r != 1)
break;
}
i = 0;
while(i < 5)
{
printf("%s",&*(pi + i));
putchar('\n');
i++;
}
free(pi);
puts("Done!");
getch();
return 0;
}
|
|
|