0
#include<stdio.h>
#include<string.h>
int main()
{
    char a[50];
    printf("nhap chuoi : ");
    gets(a);

    //cat cac ki tu trang cuoi chuoi
    for (int i= strlen(a)-1;i>=0;i--)
    {
        if(a[i]!=' ')
        {
            a[i+1]='\0';
        }
        break;
    }
    //cat cac ki tu trang dau chuoi
    for(int i=0; i<strlen(a); i++)
    {
        if(a[i]==' '&& a[i+1]!=' ');
        strcpy(a,a[i+1]);
    }
    printf("\nchuoi sau khi cat:");
    puts(a);
    return 0;
}//main

When I run program, it shows this error in line 17:

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

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
  • 4
    `a[i+1]` is a `char`, not a `char*`. And [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/995714). Also store `strlen(a)` in a variable instead of calling it in each loop like that – phuclv Jan 28 '21 at 04:04
  • `if(a[i]==' '&& a[i+1]!=' ');` doesn't do anything (check the semicolon) – Dmitri Jan 28 '21 at 04:09
  • @Từ Đức Sơn, can you explain what are you trying to do with code you wrote? – Ievgen Jan 28 '21 at 04:09
  • Looks like you're trying to trim spaces off the start and end of the string? – Dmitri Jan 28 '21 at 04:19
  • Actually, `gets` was considered so harmful / broken that it was **removed** from the language with C11. – DevSolar Jan 28 '21 at 08:46

1 Answers1

0

This:

if(a[i]==' '&& a[i+1]!=' ');
strcpy(a,a[i+1]);

does not make sense. First the semicolon after the if statement makes it a no-op. And the strcpy is also incorrect.

I guess you want to strip out a single character and thus wanted to write strcpy(a, &a[i+1]). That second parameter needs to be a pointer (a[i+1] is a char) That is however invalid as the source and destination overlap.

for possibly overlapping memory you need to use memmove, but there you have to specify the number of bytes to move (and not forget the terminating zero): memmove(a, &a[i+1], strlen(a)-i)

(the number of chars to copy is strlen(a)-(i+1) and we need to add one for the terminating zero)

So that code becomes:

if(a[i]==' '&& a[i+1]!=' ') {
    memmove(a, &a[i+1], strlen(a)-i);
}
koder
  • 2,038
  • 7
  • 10