Thread: User defined functions

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    11

    User defined functions

    Hey! I am super new to C programming- just started it. I have a task:

    "Write a program which calculates length of a string entered by user, up to 10symbols, calculation and user input should be done in separate functions"

    Code:
    #include <stdio.h>
    #define E 10
    int input();
    int len (char *str);
    
    
    int main () {
        char str[E];
        printf("Write something!\n");
            input();
            len(str);
        return 0;
    }
    
    
    int input(){
        char str[E];
            scanf("%s", str);
        return (str);
    }
    int len (char *str){
        int i;
            for(i = 0; str[i] != '\0'; ++i);
            printf("Length of string is |%d|", i);
        return 0;
    }
    I am having problems with input() function. Yes, I know that it should not return(str), but I really cant understand this this- what/how I'm supposed to return from input() so that len() can do his stuff...

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You should pass the char array from main into the input function, rather than define a new one. (You should also be careful with your scanf so that you don't overrun your char array, and make sure your char array has an extra space for the terminating null character.)

  3. #3
    Registered User
    Join Date
    Nov 2018
    Posts
    11
    I see your point. But then- what input function should return. I am really confused about what functions should/should not return.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    If there are requirements for the assignment, then you should follow those assignments. Often times, input functions will return success/failure, although in this case you're checking validity separately so you may not bother returning anything.

  5. #5
    Registered User
    Join Date
    Nov 2018
    Location
    Amberg in upper palatinate, Bavaria
    Posts
    66
    Hi Raismans!

    First try to give the adress of str[E] to the function input.
    By strings, you don't need "&" like by arrays of int or float etc.
    You can take void for your first steps in c.
    input will give scanf the adress of the first member of the string,
    Better is you take an other name as len, like in my example below,
    c is a language how is case sensitive

    As return-value take by the function how calculate the length of the string simple i.


    See and try this example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdio.h>
    
    #define E 10
    
    void INPUT(char test_string[]);
    int LEN(char *str);
    
    int main ()
    {
     char str[E];
     int length_of_string = 0;
    
     printf("Write something!\n");
     INPUT(str);
    
     length_of_string = LEN(str);
    
     printf("Length of string is |%d|", length_of_string);
        return 0;
    }
    
    
    void INPUT(char test_string[])
    {
     scanf("%s", test_string);
    
    }
    int LEN(char *str)
    {
     int i;
     for(i = 0; str[i] != '\0'; i++)
       ;
    
     return i;
    }

    Practice makes perfect

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by rusyoldguy
    Better is you take an other name as len, like in my example below,
    c is a language how is case sensitive
    It is true that input and len are not very good function names as they sound like variable names, but your example is even worse: you effectively retained the names, but made them fully uppercase, yet conventionally, fully uppercase names are used for macros and constants, not for functions.
    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

  7. #7
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Quote Originally Posted by Raismans View Post
    "Write a program which calculates length of a string entered by user, up to 10symbols, calculation and user input should be done in separate functions"

    Code:
    int input(){
        char str[E];
            scanf("%s", str);
        return (str);
    }
    You are returning a string but the function has the return type int.

    "calculation and user input should be done in separate functions"
    Maybe so . . . One more option.

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    
    #define MAX 100
    
    
    char *eingabe(void);
    void laenge(char *str);
    
    
    int main(void)
    {
        char *text;
        text = eingabe();
        laenge(text);
        
        return(0);
    }
    
    
    char *eingabe(void)
    {
        char text[MAX];
        char *str;
        
        printf("\nText eingeben: ", str);
        fgets(text, MAX, stdin);   
            
        return strtok(text, "\n");
    }
    
    
    void laenge(char *str)
    {
        int j;
        char text[MAX];
        
        strcpy(text, str);
        j = strlen(text);
        printf("\nLaenge des Textes %d Zeichen.\n", j);
    }

  8. #8
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by Kernelpanic View Post
    Code:
    char *eingabe(void)
    {
        char text[MAX];
        char *str;
        
        printf("\nText eingeben: ", str);
        fgets(text, MAX, stdin);   
            
        return strtok(text, "\n");
    }
    Undefined Behavior! You return a pointer to 'text', but 'text' is a local variable inside the function 'eingabe'.
    At the time the function returns, the variable (and its space in memory) become invalid.
    So the pointer points to a invalid memory.

    The example from rusyoldguy avoid this.
    His/Here main function define the variable so that it is valid aslong the main function live and give a pointer to the function.
    Last edited by WoodSTokk; 11-07-2018 at 01:19 PM.
    Other have classes, we are class

  9. #9
    Registered User
    Join Date
    Nov 2018
    Posts
    11
    Thank you all so much for your help, I start to understand this "C" thing a bit better. I had another task: Write a program which concatenates two strings entered by user, printsconcatenated string, waits for 3rd string and concatenates with previous two Seems very easy, but I had to use mallock/reallock/free for this. I used pointers for input_function like this.
    Code:
    void input(char **in){
        *in = (char*)malloc(256);
        printf("Ievadiet string! |MAX 255 SIMBOLI|\n");
        scanf("%255s", in);
    to allocate memory for input (up to 255 characters). It is not working and problem is with malloc().
    However, when I delete 2nd line (malloc) and write it in the main fuction it works as it should.

    Any ideas? I have seen some people using malloc() in their functions..

  10. #10
    Registered User
    Join Date
    Apr 2017
    Location
    Quetzaltenango
    Posts
    82
    scanf("%255s", *in);

  11. #11
    Registered User
    Join Date
    Nov 2018
    Posts
    11
    Quote Originally Posted by christophergray View Post
    scanf("%255s", *in);
    Still gives memory error.

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by Raismans View Post
    Thank you all so much for your help, I start to understand this "C" thing a bit better. I had another task: Write a program which concatenates two strings entered by user, printsconcatenated string, waits for 3rd string and concatenates with previous two Seems very easy, but I had to use mallock/reallock/free for this. I used pointers for input_function like this.
    Code:
    void input(char **in){
        *in = (char*)malloc(256);
        printf("Ievadiet string! |MAX 255 SIMBOLI|\n");
        scanf("%255s", in);
    to allocate memory for input (up to 255 characters). It is not working and problem is with malloc().
    However, when I delete 2nd line (malloc) and write it in the main fuction it works as it should.

    Any ideas? I have seen some people using malloc() in their functions..
    How are you declaring your variable in main? It should be a pointer-to-char, and you should pass in its address to your input function.

  14. #14
    Registered User
    Join Date
    Nov 2018
    Posts
    11
    Code:
    int main(){
    char *s1, *s2, *s3;
            input(s1);
            ... }
    Code:
    ...
    void input(char **in){
        *in = (char*)malloc(256);
        printf("Ievadiet string! |MAX 255 SIMBOLI|\n");
        scanf("%255s", *in);
    }

  15. #15
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by Raismans View Post
    Code:
    int main(){
    char *s1, *s2, *s3;
            input(s1);
            ... }
    Code:
    ...
    void input(char **in){
        *in = (char*)malloc(256);
        printf("Ievadiet string! |MAX 255 SIMBOLI|\n");
        scanf("%255s", *in);
    }
    Yeah, that's not it. You need a pointer-to-a-pointer for the syntax to work, and for what you are trying to do to actually succeed, you need to pass in the address of a variable. So your declaration is good, but you need to pass &s1 (and your compiler has been jumping up and down trying to tell you this the whole time).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. User-defined functions
    By naya22 in forum C++ Programming
    Replies: 6
    Last Post: 04-10-2007, 11:25 AM
  2. User defined functions
    By alexpos in forum C Programming
    Replies: 2
    Last Post: 10-23-2005, 02:53 PM
  3. New to user defined functions
    By Extropian in forum C Programming
    Replies: 4
    Last Post: 08-15-2005, 10:45 PM
  4. user-defined functions
    By MyntiFresh in forum C++ Programming
    Replies: 22
    Last Post: 07-10-2005, 01:11 PM
  5. Help! User defined functions
    By AdrenalinFlow in forum C Programming
    Replies: 3
    Last Post: 02-22-2003, 07:36 PM

Tags for this Thread