C - [Error] invalid conversion from 'char' to 'const char*' [-fpermissive] - c

There's a bunch of threads about C++, but I'm stuck with regular C here and can't find an answer anywhere.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main() {
char word[26], letter, reverse[26], length;
printf("Enter word: ");
scanf("%s", &word);
length=strlen(word);
for (int i=0; i<=length; i++) {
letter = word[length-i];
strcpy(reverse, letter);
printf("%c\n", reverse);
}
getch();
}
I'm getting errors as the title states.
13 25 ~ [Error] invalid conversion from 'char' to 'const char*'
[-fpermissive]
51 18 C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include\string.h [Note]
initializing argument 2 of 'char* strcpy(char*, const char*)'
What the code should do is reverse the written word and type it out line by line, by each last letter.
Etc. - Type in "food" and the program should output:
d
od
ood
food
I know I messed up somewhere in the 'letter', but I have no clue how to fix it.
Also I'm trying to avoid using std::, personal prefrence.

Try this:
int main( void ) {
char word[26], reverse[26];
int length, i;
printf("Enter word: ");
scanf("%s", &word);
length=strlen(word);
for (i=0; i<length; i++) {
reverse[i] = word[length - i - 1];
}
/* Put \0 to terminate the string */
reverse[length]='\0';
printf("%s\n", reverse);
}
Note that in the for loop you have to use only < and not <= because you'll get out of bounds of the array (negative index) and you have to put the \0 terminator to terminate your reverse string. You don't need letter and btw strcpy works not with single chars, since a single char is not a string (because of the missing string terminator (\0)).
Edit:
int main( void ) {
char word[26], reverse[26];
int length, i;
printf("Enter word: ");
scanf("%s", &word);
length=strlen(word);
for (i=0; i<length; i++) {
reverse[i] = word[length - i - 1];
/* Put \0 to terminate the string */
reverse[i + 1]='\0';
printf("%s\n", reverse);
}
}

Problems:
You pass the address of an array to scanf, rather than passing the array.
You don't copy the null termination correctly.
strcat must have null terminated strings as parameters, it cannot work with single characters. You don't need to use it here anyway.
Fixed program:
#include <stdio.h>
#include <string.h>
int main (void)
{
char word[26];
char reverse[26];
size_t length;
size_t i;
printf("Enter word: ");
scanf("%s", word);
length=strlen(word);
for (i=0; i<length; i++)
{
reverse[i] = word[length-i-1];
}
reverse[i] = '\0';
printf("Reverse: %s\n", reverse);
return 0;
}
Output:
Enter word: stackoverflow
Reverse: wolfrevokcats

There are a bunch of errors in the code. The one that you are asking about is due to the fact that you are passing a char (i.e. the variable letter) rather than the address (i.e. &letter)
This "fix" would cause the compiler error to disappear, however it would cause another one to appear. This is because we'd now be passing a pointer to a char rather than a pointer to a terminated string.
for (i=0 ; i<26 ; i++)
reverse[i] = word[25-i];

Here i have to pass in strcat(char * s1, const char * s2);
Here reverse is the cha* and &letter is const char*.
Check out this one.
this is the code what you want as output.
int main()
{
char word[26], letter, length;
int n, c, d;
char reverse[26];
char temp[26];
printf("Enter word: ");
scanf("%s", word);
length=strlen(word);
for (int i=0; i<=length; i++)
{
letter = word[length-i];
strcat(reverse, &letter);
n = strlen(reverse);
for (c = n - 1, d = 0; c >= 0; c--, d++)
temp[d] = reverse[c];
temp[d] = '\0';
printf("%s\n", temp);
}
return 0;
}
Output :-

Related

My ouput for C differs from compiler to compiler

I am writing a function longestStrInAr() that takes in an array of strings str and size (>0) as parameters, and returns the longest string and also the length of the longest string.
If two or more strings have the same longest string length, then the first appeared string will be
returned to the calling function.
This is the main function:
#include <stdio.h>
#include <string.h>
#define N 20
char *longestStrInAr(char str[N][40], int size, int *length);
int main()
{
int i, size, length;
char str[N][40], first[40], last[40], *p, *result;
char dummychar;
printf("Enter array size: \n");
scanf("%d", &size);
scanf("%c", &dummychar);
for (i=0; i<size; i++) {
printf("Enter string %d: \n", i+1);
fgets(str[i], 40, stdin);
if (p=strchr(str[i],'\n')) *p = '\0';
}
result = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", result, length);
return 0;
}
This is the function I have to write:
char *longestStrInAr(char str[N][40], int size, int *length)
{
int i,j, len;
*length =0;
char *longstr;
for (i = 0; i< size; i++){
j = 0;
len = 0;
while (str[i][j]!='\0'){
len++;
j++;
if (len > *length){
*length = len;
longstr = str[i];
}
}
}
return longstr;
}
My test input is
Enter array size:
4
Enter string 1:
Kenny
Enter string 2:
Mary
Enter string 3:
Peter
Enter string 4:
Sun
In XCode, I am able to receive the correct output:
longest: Kenny
length: 5
But using 2 different online compilers, I get the output below on both occasions:
longest: Kenny
length: 6
Why does my length differ?
Thank you.
probably one of them is a windows based compiler.
there "\n" is tread as two characters \r and \n
\r is called as carriage return
\n is called as line feed.
with this you get a byte extra there.

Integer from pointer warning

I have I problem. I get 2 warnings from console, but I dont know what's wrong with my code. Can you have look?
Program suppose to show lines with at least 11 characters and 4 numbers
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
if(isalpha(line)) numberAlpha++;
else if(isdigit(line)) numberDigit++;
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Both isalpha() and isdigit() takes an int, not a char *, as argument.
In your code, by passing the array name as the argument, you're essentially passing a char * (array name decays to the pointer to the first element when used as function argument), so, you're getting the warning.
You need to loop over the individual elements of line and pass them to the functions.
That said, just a suggestion, for hosted environment, int main() should be int main(void) to conform to the standard.
isalpha and isdigit are supposed to test if a char taken as int (a char can be safely converted to an int) is the encoding of an alphanumeric or digit character. You pass a char array, not an individual char. You need to test each char of the string you got, so you need a loop as:
for (int i=0; i<strlen(line); i++) {
if (isalpha(line[i])) numberAlpha++;
...
}
It is better to compute the length once:
int length = strlen(line);
for (int i=0; i<length; i++) {
...
}
You may also use a pointer to move along the string:
for (char *ptr = line; *ptr!=`\0`; ptr++) {
if (isalpha(*ptr)) ...
...
}
isalpha() and isdigit() functions take an int. But you are passing a char* i.e. the array line gets converted into a pointer to its first element (see: What is array decaying?). That's what the compiler complains about. You need to loop over line to find the number of digits and alphabets in it.
Also note that fgets() will read in the newline character if line has space. So, you need to trim it out before counting.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
line[strcspn(line, "\n")] = 0; // Remove the trailing newline, if any.
for (size_t i = 0; line[i]; i++) {
if(isalpha((unsigned char)line[i])) numberAlpha++;
else if((unsigned char)isdigit(line[i])) numberDigit++;
}
printf("alpha: %d, digits:%d \n", numberAlpha, numberDigit);
}
return 0;
}
Ok, i got something like this:
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
int i;
for(i=0; i<strlen(line); i++){
if(isalpha(line[i])) numberAlpha++;
else if(isdigit(line[i])) numberDigit++;
}
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Now the question is, if it is passible to make it first accepts data and then display only those line which follows the if statment. Now it shows line just after input it.

Pointer error when trying to use "strcpy" in C to copy char elements from one array to another

What I am trying to do is check if the word entered by the user has first five alphabetical letters and if it has, I need to copy those letters to another array.But it gives me an error saying "passing argument 1 of strcpy makes pointer from integer without cast[enabled by default]".
char s1[100];
char a1[100];
char alpha[5]={'a','b','c','d','e'};
int i,j,k=0;
printf("Enter a word");
fgets(s1,100,stdin);
for(i=0;i<strlen(s1);i++)
{
for(j=0;j<5;j++)
{
if(s1[i]==alpha[j])
{
strcpy(a1[k],s1[i]);
k++;
}
}
}
Need help to figure out what is wrong with this
strcpy has two input parameters char *. You can't use it for two characters. If you want to copy one character from one array to another then you need to use = operator as a1[k] = s1[i]
You only need one loop:
Replace char by char:
for(i = 0; i < strlen(s1); i++)
{
a1[i] = s1[i];
}
Or, use strcpy like this: strcpy(a1, s1);
Answering your comment:
I tried a1[k]= s1[i] but it displays some vague characters for a1 ex-: if s1 is "abc" , a1 displays as "abc!"
C strings need to be null terminated.
Try doing this:
char s1[100] = {0};
char a1[100] = {0};
Small example:
#include <string.h>
#include <stdio.h>
int main()
{
char s1[100] = {0};
char a1[100] = {0};
int i,j,k=0;
printf("Enter a word: ");
fgets(s1,100,stdin);
for(i = 0; i < strlen(s1); i++)
{
a1[i] = s1[i];
}
printf("a1 now contains: %s", a1);
return 0;
}

Split a string between words and insert newlines

i have a string that is made out of a few sentences.
for example:
hello world bye bye
now, i need to make this sentence into a coulmn of words:
hello
world
bye
bye
i have this idea going on, but i dont know how to write it correctly, so i was hopiny ypu guys could help me out.
this is what i have so far:
int len=0, k=0, stopatspace=0;
char temptext[100][15]={0};
char line[300]={0};
len=strlen(line);
printf("len is: %d", len);
for(k=0; k<len; k++)
{
if (k == ' ')
{
// i dont know what to write here in order to make it a cloumn
}
}
basiclly, my idea is to run on all the length of my line and when i reach a space i want it to enter (to go one line down so that it will look like a coulmn)
Suppose line is the char array that contains hello world bye bye and text is declared as
char text[100][15]; //I used 100 and 15 because your example contains it
and you want each word to be copied into each row of text. Then,use strtok() function with " "(space) as delimeter and place this in a loop that terminates when strtok() returns NULL to get each word. Copy each word to each row of text using strcpy() in the loop.
The code for this will look like this:
char text[100][15];
char line[]="hello world bye bye";
int i=0;
char *token=strtok(line," ");
while(token!=NULL)
{
strcpy(text[i],token);
i++;
token=strtok(NULL," ");
}
Now, to print it,you can use
for(int j=0;j<i;j++)
printf("text[%d]=%s",j,text[j]);
Another method would be to manually copy each character until a space is seen.
int len=strlen(line);
int i=0;
int k=0;
for(int j=0;j<len+1;j++)
{
if(line[j]==' ')
{
text[i][k]='\0';
i++;
k=0;
}
else
{
text[i][k]=line[j];
k++;
}
}
Note that the above code does not prevent buffer overflows. You can print each word using
for(int j=0;j<i+1;j++)
printf("text[%d]=%s",j,text[j]);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[100];
fgets(string, 100, stdin);
string[strlen(string)-1] = 0;
// create an array of pointers
char **string_array = (char**)malloc(sizeof(char*));
int i = 0, array_size;
// tokenize input
char *token = strtok(string, " ");
while(token!=NULL) {
// dynamically increase the array during run time
string_array = (char**)realloc(string_array, (i+1)*sizeof(char**));
// create the string as you would do when there is only one string
string_array[i] = (char*)malloc(strlen(token)+1);
strcpy(string_array[i], token);
token = strtok(NULL, " ");
i++;
}
array_size = i;
for(i=0; i<array_size; i++) {
printf("%s\n", string_array[i]);
}
return 0;
}
Basically you create an array of pointers and you allot memory for the strings one by one as you would do when there is only one string.
(if number of token is unknown, use realloc to increase the size of pointer to pointers.)
#include <stdio.h>
#include <ctype.h>
int main(void){
char line[300] = "hello world bye bye\n";
char temptext[100][15]={0};
int i=0, j, k=0;
while(line[k]){
if(isspace(line[k])){
++k;//skip space to word
continue;
}
for(j=0; j < 15-1 && line[k] && !isspace(line[k]); ++k, ++j)
temptext[i][j] = line[k];
if(j && ++i == 100)
break;
}
for(j=0; j<i; ++j)
puts(temptext[j]);
return 0;
}
#include<stdio.h>
#define NEWLINE printf("\n")
int main(void)
{
char string[]="hello world bye bye";
int index=0;
while(string[index])
{
if(string[index]==32)
{
NEWLINE;
index++;
}
else
{
printf("%c",string[index]);
index++;
}
}
NEWLINE;
}
// Whenever i encountered with a space, i am printing a new line on the screen. Here 32 is the ASCII value for space

Would does this function which converts a char array to an int array not work?

This program is supposed to convert the array of chars (string) into an array of ints by subtracting 97 from their ascii value (the input should be lower case cause a has an ascii value of 97). So if i enter the string abcd i should get 0123 but instead I somehow get this: 012134513789. I can't figure out where the problem is.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void userEnter(int*pattern, int n);
int main(void)
{
int n, i;
printf("What is the length of the array: ");
scanf("%d",&n);
int pattern[n];
printf("Enter the char array: ");
userEnter(pattern, n);
printf("The int array is: ");
for(i=0;i<n;i++)
{
printf("%d",pattern[i]);
}
printf("\n");
}
void userEnter(int*pattern, int n)
{
char input[n];
scanf("%s", input);
int i;
for(i = 0; i < n-1; i++)
{
pattern[i] = input[i]-97;
}
}
char input[n];
scanf("%s", &input);
should be
char input[n+1];
scanf("%s", input);
input is equivalent to &input[0]
You should also exit the for loop in userEnter when you encounter the nul character that ends the user-entered string. e.g. with something like
char* p = input;
while (*p != '\0') {
*pattern = (*p) - 'a';
p++;
pattern++;
}
As KingsIndian points out, you also need to increase the size of your input buffer. At present, you overflow that buffer and overwrite the loop counter i;
The length parameter n includes one character for null as well. So, if you input length for n 4 then you can only input 3 characters, for example abc because the 4th is for the null.
So you should change the declaration accordingly:
Change:
char input[n];
to:
char input[n+1];
Note that variable length arrays are allowed only since C99.

Resources