Pointer to function with string

This is a discussion on Pointer to function with string within the C Programming forums, part of the General Programming Boards category; Code: This is my first time trying to use a pointer to a function. I wrote this code and from ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    2

    Pointer to function with string

    Code:
    This is my first time trying to use a pointer to a function. I wrote this code and from what I understand it should work but it doesn't. Could someone please help me out.
    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char (*s1)(char* (*ptr)(void));
    char set_text(void);
    
    int main() 
    {
    char *s2;
    s1(set_text); 
    printf("%s\n", s2);
    return 0;
    }
    
    
    char set_text(void) {
    char text[] = "Hello World!";
    char *tmp;
    
    
    tmp = (char*)malloc((strlen(text) + 1) * sizeof(char));
    
    
    strcpy(tmp, text);
    return tmp;
    }
    
    

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No. You want:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    char *foo( void )
    {
        char *c = malloc( 12 );
    
        if( c )
        {
            strcpy( c, "hello world" );
        }
    
        return c;
    }
    
    int main( void )
    {
        char *c;
        char *(*fun)( void ); /* function pointer */
        fun = foo; /* assign function to the pointer */
        c = fun();
        
        if( c )
        {
            printf( "%s\n", c );
            free( c );
        }
    
        return 0;
    }
    fun is a pointer to a function that returns a character pointer and takes no arguments.

    edit - dupe thread: I am having a hard time making this work. Could someone give me some advice please?


    Quzah.
    Last edited by quzah; 10-10-2011 at 07:43 PM.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. string pointer passed to a function help
    By BrandNew in forum C Programming
    Replies: 7
    Last Post: 03-07-2011, 11:08 AM
  2. Replies: 7
    Last Post: 07-04-2007, 01:46 PM
  3. string(pointer to function)
    By Darkinyuasha1 in forum C Programming
    Replies: 11
    Last Post: 11-30-2006, 02:07 PM
  4. Replies: 8
    Last Post: 03-31-2006, 08:15 AM
  5. Passing string along function. Pointer.
    By Cheeze-It in forum C++ Programming
    Replies: 4
    Last Post: 06-23-2002, 08:23 PM

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