#Function and Switch in C
1 messages · Page 1 of 1 (latest)
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;
}
Program Output
hello world
Malassi#0410 | 30ms | c | x86-64 gcc 12.2 | godbolt.org
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;
}
Program Output
hello-world !
hello
fd26#6261 | 38ms | c | x86-64 gcc 12.2 | godbolt.org
;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;
}
Program Output
hello-world !
hello
fd26#6261 | 43ms | c | x86-64 gcc 12.2 | godbolt.org
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 *.