Search code examples
cstringstrlen

C simple string program does not compile


#include <stdio.h>
#include <string.h>

char Jones(char, char);

int main() {
    char name[]="Andrew";
    char surname[]="Jones";
    char result[80];
    result=Jones(name, surname);
    puts(result);
    return 0;
}

char Jones(char name, char surname)
{
    char result[80];
    int length;
    length = strlen(surname);
    for (int i=0; i<50; i++) 
    {
        result[length+i] = name[i];
    }
    return result;
}

The program does not compile and i dont know why. It is supposed to read two strings and swap their places. It should display eg. "Jones Andrew".


Solution

  • Here's one problem:

    char name[]="Andrew";
    char surname[]="Jones";
    char result[80];
    wynik=Jones(name, surname);
    

    This calls Jones() with character arrays (which will decay to character pointers), but the function is declared to accept single characters only.

    You should change the function to take char *name, char *surname, since it really does seem to expect strings.

    Further, you can't return a character array like you're doing in Jones(), you need to read up quite a bit on how to work with strings in C.

    Also, wynik looks undeclared, that'll also make it fail to build.