Question

So, what I'm trying to do is create a function that switches uppercase characters to lowercase and vice-versa.

Here is what I'm working with:

#include <stdio.h>
#include <stdlib.h>

int caplowswitch(char string[], char switched[]);

int main(){

    char name[] = "whyisthisnotworking";
    char flipped[] = "";

    caplowswitch(name, flipped);


return 0;
}

int caplowswitch(char word[], char switched[]){

    char *ptrword = word;
    unsigned short int counter = 0;

    printf("Your text input is: %s \n", word);

    while(*ptrword != NULL){

    switched[counter] = (*ptrword ^ 0x20);
    counter++;
    ptrword++;

    }

    printf("Your flipped text is: %s \n", switched);

    return 1;
}

In the process of learning. Thanks for your time.

Was it helpful?

Solution

  1. You forgot to add null termination to switched. You need to add

    switched[counter] = '\0';  // add '\0' to the end
    

    before

    printf("Your flipped text is: %s \n", switched);
    
  2. You need to change while(*ptrword != NULL) to while(*ptrword != '\0').

  3. As @ooga pointed out, you'd better allocate enough space to flipped. So change char flipped[] = ""; to char flipped[100] = "";.

After fixing these issues, it should work as expected. Check out running result on Ideone.

OTHER TIPS

You aren't giving enough space to flipped. By defining and initializing it as:

char flipped[] = "";

you are only giving it a single character, initialized to '\0', since that form of definition allocates only enough space to hold the given string, and you've passed the empty string. Try

char flipped[100] = "";

There are three mistakes in your code.

Point1:

Never char flipped[] = ""; allocate memory like this. This is not an proper procedure.

Point2:

Dont check null character like this while(*ptrword != NULL). You should check like while(*ptrword != '\0') this.

Point3:

null termination is required for switched. So after while(*ptrword != NULL) { ...} set switched[counter]='\0'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top