I’m having an error in my C program

Asked

Viewed 184 times

-2

I am having the following error in row 13 column 39:

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

It’s for a college job, I can’t fix the mistake in any way, someone knows what to do?

#include <string.h>
#include <iostream>

using namespace std;

char conc(char *, char *);

int main (void)
{
    char nome1[30] = "Matheus ";
    char nome2[30] = "Fidelis";

    char *nomecompleto = conc(nome1,nome2);

    cout << *nomecompleto;
}

char conc(char *s1, char *s2)
{
    char *s = new char[strlen(s1)+strlen(s2)+1];
    char *aux = s;

    while(*s1) 
    {
        *aux = *s1;
        aux++;
        s1++;
    }

    while(*s2)
    {
        *aux = *s2;
        aux++;
        s2++;
    }
    *aux = '\0';
    return *s;
}

2 answers

2

You are trying to save in variable nomecompleto the return of function conc(nome1,nome2);, but the guys don’t match.

nomecompleto is a pointer (char), while the fun conc() returns a char.

To fix this just change the return and the type of the function conc.

At the beginning of the code, in the definition of the function:

char* conc(char *, char *);

And in its implementation:

char* conc(char *s1, char *s2){
  char *s = new char[strlen(s1)+strlen(s2)+1]; //(inalterado)
  [...]
  return s;
}

Note that the variable sis already a pointer, with that when executing return s; you will already be passing the memory address that was allocated to the new char (that’s the goal).

When you return *s, you create a copy of the char saved at the address that the pointer s points, then you would be returning a char where a pointer is expected (that is not the goal, with that the error would persist).

OBS: This solves invalid conversion error, but your code has other logic errors, which will prevent expected output.

0

Seems to me to be an error in initializing the char pointer type variable *nomecompleto which receives a char value of the conc function conc(nome1,nome2); in char *nomecompleto = conc(nome1,nome2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.