apelsin
apelsin

Reputation: 55

String from a function in C

Currently in the process of learning a bit of c, but I'm having issues with strings.

I simply want to return a string using a function. This is to be part of a bigger program that's supposed to get the word from an external file, but I want a simple function like this just to get going.

PS. Yes the bigger program is for school. I don't want to simply copy code, i want to understand it. Just throwing that out there.

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

char* teststring()
{
    return (char*)"donald duck";
}

int main()
{
    char word[20];

    word = teststring();

    return 0;
}

I've tried various variations of returning a string, but my problem is that I'm unsure what to use as return type for the function and how to return it.

This is the most common error i get.

[Error] incompatible types when assigning to type 'char[20]' from type 'char *'

I've tried with different return types, declaring and initializing a char array and return it, and my latest test type conversion.

Thanks in advance.

Upvotes: 0

Views: 210

Answers (2)

tonga
tonga

Reputation: 11981

You'd better add const modifier to the function teststring() as it returns a pointer to a const string. You cannot reassign word which is the address of char[20] to a pointer that points to a constant string. It must be copied.

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

const char* teststring()
{
    return "donald duck";
}

int main()
{
    char word[20];

    strcpy(word, teststring());
    printf("%s", word);

    return 0;
}

Upvotes: 0

John Bode
John Bode

Reputation: 123598

Arrays (more properly, expressions of array type) cannot be the target of an assignment; you cannot copy the contents of one array to another using the = operator.

For strings, you will need to use either the strcpy or strncpy functions:

strcpy( word, teststring() ); // assumes word is large enough to hold the
                              // returned string.

For other arrays, use memcpy.

Upvotes: 3

Related Questions