Pointer question?

This is a discussion on Pointer question? within the C Programming forums, part of the General Programming Boards category; I want to display the string copied in sh(). Code: #include <stdio.h> #include <stdlib.h> #include <string.h> int sh(char * s) ...

  1. #1
    Samuel shiju's Avatar
    Join Date
    Dec 2003
    Posts
    41

    Pointer question?

    I want to display the string copied in sh().
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int sh(char * s)
    {
    	s = malloc(20);
    	strcpy(s,"Hello World");
    	return 0;
    }
    
    int  main()
    {
            char *s=NULL;
            sh(s);
            printf("%s",s); /* Print Hello world*/
            return 0;
    }
    But its printing (null).
    What's Wrong?

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,264
    Do do it like that, you would need to pass a pointer to a pointer.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int sh(char ** s)
    {
    	*s = malloc(20);
    	strcpy(*s,"Hello World");
    	return 0;
    }
    
    int  main()
    {
            char *s=NULL;
            sh(&s);
            printf("%s",s); /* Print Hello world*/
            return 0;
    }

  3. #3
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    try this ...
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int sh(char * s)
    {
    	s = malloc(20);
    	strcpy(*s,"Hello World");
    	return 0;
    }
    
    int  main()
    {
            char *s=NULL;
            sh(s);
            printf("%s",s); /* Print Hello world*/
            return 0;
    }

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >try this ...
    Please don't suggest blatantly incorrect solutions.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 05:23 AM
  2. Easy pointer question
    By Edo in forum C++ Programming
    Replies: 3
    Last Post: 01-19-2009, 10:54 AM
  3. char pointer to pointer question
    By Salt Shaker in forum C Programming
    Replies: 3
    Last Post: 01-10-2009, 11:59 AM
  4. Pointer question
    By rakan in forum C++ Programming
    Replies: 2
    Last Post: 11-19-2006, 02:23 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21