I've rewrote the whole thing. Based on my shallow understanding of dynamic memory alloc and pointers. (hopefully)
Learning C is not a bed of roses...
Please help me... Thanks..
1. I believe there are still some problems with the way I;ve used realloc() .
2. Apparantly, "char s[]" cannot be a very long sentence! Else when executing the code, it hangs.
char s[]="morse code"; /*still runs*/
char s[]="morse code m"; /*still runs*/
char s[]="morse code mo"; /* The program hangs */
I dont get it. Why is that so?
3. Is this correct? I believe not. returning a value signifies the end of function! How do I rectify this?
Code:
char *toMorse(char *s)
{
..
..
..
....malloc()....
..
..
..
return x; /*Can a function return the value
/* first, then free(x)? I*/
/*believe not! */
/*But I cannot free(x) before I */
/*return the value, else the return */
/*value is empty or null*/
free(x);
}
The code:
Code:
#include <stdio.h>
void toUpperCase(char *s);
char *toMorse(char *s);
int main(int argc, char *argv[])
{
char s[]="morse code";
char *yy=NULL;
yy=toMorse(s);
printf("%s ",yy);
return 0;
}
char *toMorse(char *s)
{
char c[][37] = {
".-", /* A*/
"-...", /* B*/
"-.-.", /* C*/
"-..", /* D*/
".", /* E*/
"..-.", /* F*/
"--.", /* G*/
"....", /* H*/
"..", /* I*/
".---", /* J*/
"-.-", /* K*/
".-..", /* L*/
"--", /* M*/
"-.", /* N*/
"---", /* O*/
".--.", /* P*/
"--.-", /* Q*/
".-.", /* R*/
"...", /* S*/
"-", /* T*/
"..-", /* U*/
"...-", /* V*/
".--", /* W*/
"-..-", /* X*/
"-.--", /* Y*/
"--..", /* Z*/
"-----", /* 0*/
".----", /* 1*/
"..---", /* 2*/
"...--", /* 3*/
"....-", /* 4*/
".....", /* 5*/
"-....", /* 6*/
"--...", /* 7*/
"---..", /* 8*/
"----." /* 9*/
};
char *x;
toUpperCase(s);
x=(char *)malloc(10*sizeof(char));
if(x==NULL)
{
printf("Error Allocating Memory");
exit(1);
}
while(*s)
{
if(*s>=65 && *s<=90)
{
x=(char *)realloc(x,5*sizeof(char));
if(x==NULL)
{
printf("Error Allocating Memory");
exit(1);
}
strcat(x,c[*s-65]);
strcat(x," ");
s++;
}
else if(*s>=48 && *s<=57)
{
x=(char *)realloc(x,5*sizeof(char));
if(x==NULL)
{
printf("Error Allocating Memory");
exit(1);
}
strcat(x,c[*s-22]);
strcat(x," ");
s++;
}
else if(*s==32)
{
x=(char *)realloc(x,3*sizeof(char));
if(x==NULL)
{
printf("Error Allocating Memory");
exit(1);
}
strcat(x,"/ ");
s++;
}
else
s++;
}
return x;
free(x);
}
void toUpperCase(char *s)
{
while(*s)
{
if(*s>=97 && *s<=122)
*s++-=32;
else
s++;
}
}