I am creating this program as part of an assignment for college. The objective is to copy char* slogan = "Comp10120 is my favourite module"; to a new string while removing consonants and capitalising all letters. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void printStrings();
char *slogan = "Comp10120 is my favourite module";
char *p = slogan;
char *slogan_copy = NULL;
int main ()
{
//Get size of original string
int slogan_size = 0;
while (*p++ != '\0')
slogan_size++;
// Dynamically allocate memory to copy of string
slogan_copy = (char*) malloc ((slogan_size+1) * sizeof(char));
//Place string terminator at end of copy string
slogan_copy[slogan_size] = '\0';
//Reset p pointer to start of string
p = slogan;
int offset = 0;
while (*p != '\0')
{
//If the current element in the string is a consonant,
//or as defined in the if statement,
//if p is not a vowel and is between a and z or A and Z:
if ((!(*p == 'a' || *p == 'e' || *p == 'i' || *p == 'o' || *p == 'u'))
&& (((*p > 'a') && (*p < 'z')) || ((*p > 'A') && (*p < 'Z'))))
p++;
else
//Copy element to slogan_copy and capitalise
slogan_copy[offset++] = *p++;
slogan_copy[offset] = toupper(slogan_copy[offset]);
}
//Place string terminator after last element copied.
slogan_copy[offset] = '\0';
printStrings();
return 0;
}
void printStrings ()
{
printf("Origianl String: %s\n",*slogan);
printf("Modified String: %s",*slogan_copy);
}
When I try to execute, I get the error
initializer element is not constant
char *p = slogan;
^~~~~~
I am assuming that it is because I am trying to perform operations on slogan as if it was just a regular array of characters, and not a pointer to a string. However, I don't know how to fix this error.
In addition to this, I tried changing char*slogan = "Comp10120 is my favourite module"; to char slogan[] = "Comp10120 is my favourite module"; to see if it would work, out of curiosity. It complies, but crashes upon execution. Any ideas as to how I could modify my code for it to work?
printf("Origianl String: %s\n",*slogan);You are passing acharwhen the function expects a pointer. Should be:printf("Origianl String: %s\n", slogan);char *p = slogan;at the beginning ofmain, then it will compile. But anyway your code is terribly complicated. And your abuse us global variables is questionable.char *slogan = ....should beconst char *slogan = ...., which meanschar *p = slogan;should beconst char *p = slogan;.