I have been trying to make a function, is_isogram, return a value that is an alphabetized string. When I pass the value through the function from main, the variable to be returned is set to the correct value.
However, when I return the variable from the function, it does not return anything in main. Along with this, I get an error for unable to read memory when I initialize the variable to hold the return value in main.
#include <stdbool.h>
#include <ctype.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <Windows.h>
#include "isogram.h"
char is_isogram(char phrase[])
{
int i;
for (i = 0; phrase[i]; i++) {
tolower(phrase[i]);
}
if (phrase == NULL) {
return false;
}
char temp;
int count1;
int count2;
char *alphabet = (char *)malloc(sizeof(char) * (strlen(phrase) + 1));
int n = strlen(phrase);
for (count1 = 0; count1 < n - 1; count1++) {
for (count2 = count1 + 1; count2 < n; count2++) {
if (phrase[count1] > phrase[count2]) {
temp = phrase[count1];
phrase[count1] = phrase[count2];
phrase[count2] = temp;
alphabet = phrase;
break;
}
}
}
return alphabet;
}
This function does not return the variable alphabet. I have been trying to use malloc and other techniques to return this local variable as a value. I wanted to use every character string as an array with "[]," however I would get errors about needing to initialize an array. The value returned is currently just a sizeable garbage value, however, when I step through the process of debugging, the variable alphabet is 'abb.'
int main() {
char *bet = is_isogram("bab\0");
if (bet == 'abb\0') {
return 0;
} else {
return -1;
}
}
The variable bet is throwing an error before even accessing the function. It tells me it was unable to read the memory and the value for bet is close to NULL for the remainder of the program.
In conclusion, the program is not giving returning a value of 'abb' when from the function locally, nor is it saving the variable in memory. It throws garbage into the variable, but the variable is killed, and a new variable cannot be adequately initialized in main.
char is_isogram(char phrase[]).if (bet == 'abb\0')is also not going to work. You should be seeing compilation warnings for these things. If not it's time to learn to turn the warning level up.tolower(phrase[i]);returns a value which you ignore. It does not alter the value passed to it. Tryphrase[i] = tolower(phrase[i]);alphabet = phrase;you are overwriting the memory pointer thatmallocgave you. Don't do that.sizeof(char)is 1 by definition. The functionis_isogram()is declared to return achar, not achar*. The statementalphabet = phraseis almost certainly an error.char is_isogram(char phrase[])must returnchar, yetreturn alphabet;is returningchar *.