Thread: how to print an array made by malloc?

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    230

    how to print an array made by malloc?

    here is what i do:

    first i try to make an array named buf where i can store some words...using malloc!

    Code:
    char *buf;
    and then:

    Code:
    buf = (char *)malloc(5*sizeof(char));
    i hope this is right...

    then i want to store a name in each cell of the array.
    so

    Code:
    for(i=0; i<5; i++){
    scanf("%s", buf[i]);
    }
    and then,
    print it
    Code:
    for(i=0; i<5; i++){
    printf("%s", buf);
    }
    where is the mistake? thank you in advance....

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    buf[i] can only hold one character.

    If you want to create an array of strings you need

    char Array[10][30];

    That will create an array of 10 strings up to 30 characters each.

    You can read/display it as Array[i]

    printf (Array[i]);

    If you are going to do this through malloc you need to pre-calculate the size of the whole array, which in the example is 300.

  3. #3
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    ok thanks...i got it! although i want to ask something...

    is there anyway that i can have a 2-dimension array where i can store names...but with the second dimension not standard ? depending of the length of the name, malloc can' t automatically decide how many kbs to have?

  4. #4
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    An array of char* pointers.
    char *Array[10]

    Then each of those elements needs to be malloced to the size of string you want to save there. They can be different sizes.

  5. #5
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    Thank you!

  6. #6
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198

    Smile

    This works too:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
        char *buf;	// creates a pointer to type char
    	int i;
    
    	while( 1 )
    	{
    		puts( "Enter some word, but not too many!");
    
    		buf = (char *)malloc(50 *sizeof(char));	
    
    		if( buf == NULL )	// Test for error after malloc()
    		{
    			puts("Some kind of error");
    			return -1;
    		}
    
    		gets(buf);	// put a string into allocated space
    	
    		puts(buf);	// output string to screen
    	}
    	
        return 0;
    }
    I kept this to the bare minimum to match your initial task. As you step through this,
    note that the string pointed out will be lost. So if you want to capture it, create a two dimensional array of type char.

  7. #7
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    why do you choose gets, puts instead of using scanf, printf which seem to be more classic functions? just asking...

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Char*Pntr View Post
    This works too:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
        char *buf;	// creates a pointer to type char
    	int i;
    
    	while( 1 )
    	{
    		puts( "Enter some word, but not too many!");
    
    		buf = (char *)malloc(50 *sizeof(char));	
    
    		if( buf == NULL )	// Test for error after malloc()
    		{
    			puts("Some kind of error");
    			return -1;
    		}
    
    		gets(buf);	// put a string into allocated space
    	
    		puts(buf);	// output string to screen
    	}
    	
        return 0;
    }
    I kept this to the bare minimum to match your initial task. As you step through this,
    note that the string pointed out will be lost. So if you want to capture it, create a two dimensional array of type char.
    While I realize this is only an exercise of no real value. You should note that it will leak memory unless you dispose of buf at the end of each pass through the loop.

    You should add free(buf); right after the puts(buf) statement.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by brack
    why do you choose gets, puts instead of using scanf, printf which seem to be more classic functions? just asking...
    gets and puts are about as "classic" as scanf and printf, in my opinion. However, gets should almost always be avoided as it cannot be used correctly to avoid a buffer overflow.

    Actually, Char*Pntr's example does not need dynamic memory allocation at all. For example:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        while (1)
        {
            char buf[50];
    
            puts("Enter some word, but not too many!");
            if (fgets(buf, sizeof(buf), stdin))
            {
                /* Remove the trailing newline, if it is present. */
                char *p = strchr(buf, '\n');
                if (p)
                {
                    *p = '\0';
                }
                else
                {
                    /* Remove whatever is left in the input buffer. */
                    int c;
                    while ((c = fgetc(stdin)) != EOF && c != '\n');
                }
    
                puts(buf);
            }
            else
            {
                break; /* EOF (typically) */
            }
        }
    
        return 0;
    }
    Last edited by laserlight; 09-03-2010 at 04:05 AM. Reason: Ah, brack already explained the need for dynamic memory allocation in post #3.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    the reason why i said that scanf and printf are "classic" is because they can be used every time whereas the other two can' t....
    anyway i believe that it depends of what you learn first...for example if you learn gets, puts first they are more "classic" for you...as you said...
    however there are some εxemptions!!!
    Last edited by brack; 09-03-2010 at 04:29 AM.

  11. #11
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198

    Red face

    Quote Originally Posted by CommonTater View Post
    While I realize this is only an exercise of no real value.
    That's why I didn't bring up the issue of a memory leak. That's also the reason I did not bring up the issue of using malloc() in the first place. [edit] :-)

    (Edit #2)

    laserlight:

    Last edited by laserlight; Today at 03:05 AM. Reason: Ah, brack already explained the need for dynamic memory allocation in post #3.

    I just noticed your edit, it's hard to see. I'm glad that you noticed (after posting) that it was not my idea to use malloc(). Now I'll have to torture you
    with 2 smiley faces. :-) :-)
    Last edited by Char*Pntr; 09-03-2010 at 02:42 PM. Reason: I forgot to smile :-)

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Char*Pntr
    That's why I didn't bring up the issue of a memory leak.
    The issue is with your example, not what brack posted. "An exercise of no real value" is a poor excuse for a poor example. Even if it was a problem in brack's code, it should still be brought up, especially when the question is about dynamic memory allocation.

    EDIT:
    Quote Originally Posted by Char*Pntr
    I'm glad that you noticed (after posting) that it was not my idea to use malloc().
    It was obvious since post #1 that it was not your idea to use malloc(). I wanted to ask brack to elaborate on why he/she was trying to use malloc, then I noticed that he/she already answered my question.
    Last edited by laserlight; 09-03-2010 at 02:47 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by brack View Post
    the reason why i said that scanf and printf are "classic" is because they can be used every time whereas the other two can' t....
    anyway i believe that it depends of what you learn first...for example if you learn gets, puts first they are more "classic" for you...as you said...
    however there are some εxemptions!!!
    As stated earlier, do not use gets. Do not even bother learning it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 08-16-2010, 10:00 AM
  2. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  3. Dynamic array - malloc
    By erasm in forum C Programming
    Replies: 4
    Last Post: 10-04-2009, 04:10 PM
  4. Towr of Hanoi move the disc
    By WatchTower in forum C Programming
    Replies: 9
    Last Post: 07-17-2009, 03:48 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM