Reputation:
I am working on some practice programs and have run into an issue with my function squeez below. It is returning an integer rather than a char array as intended. The code is meant that the user enters, first a character string, followed by a character he wishes to remove. The squeez function receives both and outputs a string without the given character.
Currently my function gives the warning:
return makes integer from pointer without a cast [enabled by default]
I know the function is returning type 'int' b/c it also displays this 2nd error:
format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
/* Squeeze Function */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char squeez(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
{
if (s[i] != c)
{
s[j++] = s[i];
}
printf("%c %d", s[i], c);
}
printf("%s", s);
s[j] = '\0';
return s;
}
int main(void)
{
int i, c;
char str[10];
for (i = 0; (c = getchar()) != '\n'; ++i)
{
str[i] = c;
}
c = getchar();
printf("%s", squeez(str, c));
return EXIT_SUCCESS;
}
Any and all help would be appreciated thank you!
Upvotes: 0
Views: 3724
Reputation: 7582
You should change the return type to char *
:
char *squeez(char s[], int c) {
…
return s;
}
… because s
is a pointer (the address of the first character of the string).
A second problem is that squeez()
looks for a '\0'
terminator, but you never wrote one there. A third problem is that you might overflow the 10-byte buffer. The loop in main()
should look more like
#include <assert.h>
int main(void)
{
int i;
char str[10];
for (i = 0; i < sizeof(str) - 1; i++)
{
if ((str[i] = getchar()) == '\n')
{
break;
}
}
assert( (i == sizeof(str) - 1) || (str[i] == '\n') );
str[i] = '\0';
printf("%s", squeez(str, getchar()));
}
Upvotes: 3
Reputation: 4041
You have to return the character pointer. Change the returning char
to char *
.
If you are using the char then that will taken as a single character. So when you are using the char
you are able to return the character only. like this.
return s[0]; or else a character variable.
Upvotes: 0
Reputation: 331
You are actually returning a char pointer. So the return type of the function should be char *
.
Upvotes: 0