Exetools  

Go Back   Exetools > General > General Discussion

Notices

 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
  #1  
Old 08-24-2006, 13:48
Zest
 
Posts: n/a
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;

}
Reply With Quote
 


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



All times are GMT +8. The time now is 14:00.


Always Your Best Friend: Aaron, JMI, ahmadmansoor, ZeNiX, chessgod101
( Since 1998 )