#Function and Switch in C

1 messages · Page 1 of 1 (latest)

wind gorge
#

can i return a string in a function in c?

glacial escarp
#

Yes you can. You need to return a char pointer to do so.

#

;compile

#include <stdio.h>

char * getSomeString() {
    return "hello world";
}

int main(void) {
    printf("%s", getSomeString());

    return 0;
}
shrewd burrowBOT
#
Program Output
hello world
autumn carbon
#

normally, you would allocate memory so

#

;compile c

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

char* getSomeNewString(const char ch)
{
    static const char* s = "hello world  "; // extra spaces

    // Duplicate string and modify
    char* copy = strdup(s); // return must be same size or lower
    copy[ 5] =  ch;
    copy[12] = '!';
    return copy;
}

int main()
{
   char* s = getSomeNewString('-');
   if (s != NULL) {
     printf("%s\n", s);
     free(s);
   }
   char* z = getSomeNewString('\0');
   if (z != NULL) {
     printf("%s\n", z);
     free(z);
   }
   return 0;
}
shrewd burrowBOT
#
Program Output
hello-world !
hello
autumn carbon
#

;compile c

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

void modifyString(char* s, const char ch, const size_t maxlen)
{
    if (maxlen > 5)
    s[ 5] =  ch;

    if (maxlen > 12)
    s[12] = '!';
}

#define MAXLEN 20
int main()
{
   static const char* h = "hello world  "; // extra spaces
   char s[MAXLEN+1] = {0};
   assert(strlen(h) < MAXLEN);

   strncpy(s, h, MAXLEN);
   modifyString(s, '-', MAXLEN);
   printf("%s\n", s);

   strncpy(s, h, MAXLEN);
   modifyString(s, '\0', MAXLEN);
   printf("%s\n", s);

   return 0;
}
shrewd burrowBOT
#
Program Output
hello-world !
hello
hushed nymph
#

I agree with fd26. It's more normal to take a char* as input and to write to the memory designated by that pointer instead of returning a char *.

autumn carbon
#

but approach is valid

#

if you pass a pointer, you need to pass the buffer size also

#

if you return a char* then it must be free()