Search code examples
cstringfunctionvoid

Functions and strings


im very new to programming, trying to learn C and cant figure out how to create/use a simple function.

Im trying to create a function called stringtest and then call it into the main and simply make the string strA print ABC.

void stringtest(char strA[20])
{
    strA = "ABC";
}

int main()
{
    char strA;
    stringtest(strA[20]);
    printf("This is strA", strA);

  return 0;
}

Solution

  • You need to read up on pointers and the C syntax in general.

    This is one way you could do it.

    #include <stdio.h>
    #include <string.h>
    
    void stringtest(char *strA) {
        strcpy(strA, "ABC");
    }
    int main(int argc, const char * argv[]) {
        char strA[20];
        stringtest(&strA[0]);
        printf("This is strA -> %s \n", strA);
        return 0;
    }
    

    Take care,

    /Anders.