Reputation: 462
Set up an array of the following musical instruments: CELLO GUITAR VIOLIN DOUBLE BASS Loop round and remove the vowels. My attempt:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *aszMusicalInstruments[4];
aszMusicalInstruments[0] = malloc(6 * sizeof(char));
aszMusicalInstruments[0] = "CELLO";
aszMusicalInstruments[1] = malloc(7 * sizeof(char));
aszMusicalInstruments[1] = "GUITAR";
aszMusicalInstruments[2] = malloc(12 * sizeof(char));
aszMusicalInstruments[2] = "DOUBLE BASS";
aszMusicalInstruments[3] = malloc(7 * sizeof(char));
aszMusicalInstruments[3] = "VIOlIN";
int iii;
for (iii = 0; iii < 4; iii++)
{
int jjj = 0;
while (aszMusicalInstruments[iii][jjj] != '\0')
{
if (aszMusicalInstruments[iii][jjj] == 'A' || aszMusicalInstruments[iii][jjj] == 'E' || aszMusicalInstruments[iii][jjj] == 'I' || aszMusicalInstruments[iii][jjj] == 'O' || aszMusicalInstruments[iii][jjj] == 'U')
{
aszMusicalInstruments[iii][jjj] = '_';
}
putchar(aszMusicalInstruments[iii][jjj]);
jjj++;
}
}
return 0;
}
But the program stops working just after printing C.
Upvotes: 1
Views: 109
Reputation: 399753
There's no need to do dynamic allication for this, it's just making the problem more complicated.
Just use an array:
char aszMusicalInstruments[][20] = {
"CELLO",
"GUITAR",
"DOUBLE BASS",
"VIOLIN"
};
This is a 2D array of characters, as opposed to a 1D array of character pointers (char *aszMusicalInstruments[] = { "CELLO", ...
), so you can modify the characters freely.
Upvotes: 2
Reputation: 134286
Point 1
malloc()
ing, need to free()
later.or,
malloc()
, instead strdup()
the string literal, need to free()
later.or,
malloc()
and assign the string literal to the pointer. no free()
required.Point 2:
As per your stated logic, the if
needs a counter else
part. You need to put
putchar(aszMusicalInstruments[iii][jjj]);
under else
condition of the if
check.
Upvotes: 1
Reputation: 50776
Instead of
aszMusicalInstruments[0] = malloc(6 * sizeof(char));
aszMusicalInstruments[0] = "CELLO";
you need:
aszMusicalInstruments[0] = malloc(6 * sizeof(char));
strcpy(aszMusicalInstruments[0], "CELLO");
Or even simpler:
aszMusicalInstruments[0] = strdup("CELLO");
The advantage of the last solution is that you d'ont have to worry about the length of the string.
Upvotes: 0
Reputation: 819
The line:
aszMusicalInstruments[0] = "CELLO"
Is not copying the string into the memory you have reserved. Instead it is changing the pointer to point to a constant string in you program.
To copy it into the memory you have just reserved with malloc
you shall use the srtcpy
function.
Upvotes: 0