Thread: help with function

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2015
    Posts
    1

    help with function

    Hello guys,
    I would like to ask you if anybody knows how to fix or upgrade my function "set". My teacher wrote me that I have to allocate the function inside not in main. And second thing is how to change that the pointers to pointers in function would be simplified.
    Thanks for help

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define BUFFER_SIZE 128
    
    int set(char *in, char **out);
    
    int main(int argc, char **argv)
    {
      char inStr[BUFFER_SIZE] = { 0 };
      char *outStr = NULL;
      int changed = 0;
      printf("Exercise 10.1\n");
    
      printf("Enter string:");
      if (!fgets(inStr, BUFFER_SIZE, stdin)) {  //enter string
    
        printf("Error load string...\n");
        exit(EXIT_FAILURE);
      }
      int lenght = strlen(inStr);   //include '\n' char as last
      inStr[lenght - 1] = '\0';     //remove last char '\n' from fgets function
      outStr = (char *) malloc(lenght); //alloc new string of lenght
      if (!outStr) {
        printf("Error in alloc memory...\n");
        exit(EXIT_FAILURE);
      }
      changed = set(inStr, &outStr);  //call function
      printf("Original string: %s\n", inStr);
      printf("Changed string: %s and changed letters: %d\n", outStr, changed);
      free(outStr);                 //free alloc memory
      getchar();
      return 0;
    }
    
    int set(char *in, char **out)
    {
      char *tmpString = *out;       //temp variable, out cannot be used like out++
      int changed = 0;              //changed letters
      while (*in) {
        if (*in >= 65 && *in <= 90) {
          *tmpString = *in + 32;
          changed++;
        } else if (*in >= 97 && *in <= 122) {
          *tmpString = *in - 32;
          changed++;
        } else {
          *tmpString = *in;
        }
        in++;
        tmpString++;
      }
      *tmpString = '\0';            //add ending char '\0'
      return changed;
    }
    Last edited by Salem; 02-09-2015 at 03:18 PM. Reason: fixed train-wreck colour/font

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function Prototype, Function Call, and Function definition
    By dmcarpenter in forum C Programming
    Replies: 9
    Last Post: 04-09-2013, 03:29 AM
  2. Replies: 13
    Last Post: 03-20-2012, 08:29 AM
  3. Replies: 15
    Last Post: 06-09-2009, 02:19 AM
  4. Print function: sending a function.. through a function?
    By scarlet00014 in forum C Programming
    Replies: 3
    Last Post: 11-05-2008, 05:03 PM
  5. Replies: 9
    Last Post: 01-02-2007, 04:22 PM

Tags for this Thread