Узнайте, как вернуть строку из функции C
В одной из моих программ на C у меня была задача вернуть строку из функции:
xxxxx myName() {
return "Flavio";
}
Сложнее всего определить тип возвращаемого значения.
Струны в Cнаходятсямассивыизchar
элементов, поэтому мы не можем вернуть строку - мы должны вернуть указатель на первый элемент строки.
Вот почему нам нужно использоватьconst char*
:
const char* myName() {
return "Flavio";
}
Вот пример рабочей программы:
#include <stdio.h>
const char* myName() {
return "Flavio";
}
int main(void) {
printf("%s", myName());
}
Если вы предпочитаете присвоить результат переменной, вы можете вызвать функцию следующим образом:
const char* name = myName();
Мы можем написатьуказательоператор*
также таким образом:
const char * myName()
const char *myName()
Все формы полностью действительны.
Обратите внимание на использованиеconst
, потому что из функции я возвращаюстроковый литерал, строка, заключенная в двойные кавычки, которая является константой.
Обратите внимание, что вы не можете изменить строковый литерал в C.
Еще одна вещь, о которой следует помнить, заключается в том, что вы не можете вернуть строку, определенную как локальную переменную из функции C, потому что переменная будет автоматически уничтожена (освобождена), когда функция завершит выполнение, и, как таковая, она не будет доступна, если вы, например, попробуете сделать:
#include <stdio.h>
const char* myName() {
char name[6] = "Flavio";
return name;
}
int main(void) {
printf("%s", myName());
}
у вас будет предупреждение и треп, например:
hello.c:5:10: warning: address of stack memory
associated with local variable 'name'
returned [-Wreturn-stack-address]
return name;
^~~~
1 warning generated.
B��Z> K���⏎Notice the B��Z> K���⏎
line at the end, which indicates that the memory that was first taken by the string now has been cleared and there’s other random data in that memory. So we don’t get the original string back.
Changing myName()
to
const char* myName() {
char *name = "Flavio";
return name;
}
makes the program work fine.
The reason is that variables are allocated on the stack, by default. But declaring a pointer, the value the pointers points to is allocated on the heap, and the heap is not cleared when the function ends.
Download my free C Handbook
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor