Как вернуть массив char из функции c
Перейти к содержимому

Как вернуть массив char из функции c

  • автор:

C++ Return Char Array From Function

Like an array of floating numbers or integers, every array index includes one element or character. We will discuss how to return a char array from a function in C++ in this article:

Use ‘for’ Loop to Return Character Array

In this code, we will be using a for loop in C++ to return an array of characters. We will construct the Character Array and then specify the size of that Array. Then we define an ‘integer’ data type variable. We can use the ‘for’ loop by allocating 0 to the ‘i’ variable, which would have a smaller value than the size of the array, and enhance the value of the ‘i’ by 1 at each loop. Before presenting the character array, we must retain the data in the variable on each iterative process.

using namespace std ;
int main ( )
{
int i ;
char char_arr [ 6 ] ;
char_arr [ 0 ] = ‘L’ ;
char_arr [ 1 ] = ‘M’ ;
char_arr [ 2 ] = ‘N’ ;
char_arr [ 3 ] = ‘O’ ;
char_arr [ 4 ] = ‘P’ ;
char_arr [ 5 ] = ‘Q’ ;
cout << " \n show all the characters: \n " ;
for ( i = 0 ; i < 6 ; i ++ )
{
cout << "char_arr[" << i << "]:" << char_arr [ i ] ;
cout << ( " \n " ) ;
}
getch ( ) ;
return 0 ;
}

Here we have to introduce two important header files <iostream> and <conio.h>. Along with this, we have been using the standard namespace. The main() function is invoked. We have initialized a variable ‘i’. We declare the character array and set the size of the array. There would be the character ‘ L’ in the ‘0’ index of the array. At the ‘1’ index, there would be the character ‘M’. At the ‘2’ index, there would be the character ‘N’. At the ‘3’ index, there would be character ‘O’. At the ‘4’ index, there would be the character ‘P’. At the ‘5’ index, there would be the character ‘Q’.

The ‘cout’ command is applied to print the line ‘show all the characters’ before displaying the character array elements. We display the defined character array members by using a for a loop. Within the body of the ‘for’ loop first, we start the loop variable ‘i’. We apply the condition on this variable ‘i<6’, and in the last part, we increment the value of this variable. We have utilized the ‘cout’ command to show the elements of the defined array. ‘\n’ is used to print the elements on separate lines.

In the end, we have entered getch() and ‘return 0’. In the code, we utilize the getch() method to keep the output display available till the user enters any key on the keyboard to close the output screen.

Use ‘while’ Loop to Return Character Array

In this instance, we will demonstrate how to utilize the while loop in C++ to return a character array. Before presenting the character array, we will be using a while loop to validate the ‘int’ variable smaller than the size of the array on each iteration and save the value in a character array.

Two libraries, <iostream> and <conio.h>, must be included at the program’s start. We’ve been employing the standard namespace. The function main() is being called. We’ve set up a variable called ‘i’ within the body of this method. Now the character array is declared. The components of the character array have been specified. The character ‘A’ will be at the array’s ‘0’ index. The character ‘L’ will be at index ‘1.’ Character ‘E’ will be found at the ‘2’ index. Character ‘E’ will be found at index ‘3’. Character ‘N’ will be found at index ‘4’. Character ‘A’ will be found at index ‘5.’ Character ‘A’ will be found at index ‘6.’

Before presenting the components of the character array, the ‘cout’ statement is used to display the text ‘show all the characters.’ The ‘while’ loop is being applied to illustrate the elements of the defined character array. We initially define the loop variable ‘i’ just outside the body of the ‘while’ loop. We have used the ‘cout’ statement to display the items of the declared array with their positions after applying the condition on the variable ‘i<7’. ‘\n’ would be applied to display every element on its line. We’ve added getch() and ‘return 0’ commands at the termination of the code.

To Return a Character Array, Utilize a ‘do-while’ Loop

In this case, we will use a do-while loop in C++ to return an array of characters.

First of all we integrate the header files <iostream> and <conio.h>. After using ‘namespace’, we invoked the main() function. The variable ‘i’ is initialized for storing the character array elements. We specify the members of the character array by declaring this array. We have to enter the ‘cout’ command to print the phrase just before the character array elements after initializing the variable ‘i’. We have employed a do-while loop. In the segment of ‘do,’ we have used the ‘cout’ statement to display all the elements of the required array. Then we apply condition ‘i<6’ in the body of the while portion. To terminate the code, we employ ‘return 0’.

Conclusion

The character arrays in the C++ language have been reviewed in this article. Character arrays are sets of characters held in the form of arrays. The preceding discussion includes three basic techniques for returning the character array from the function.

how to return a char array from a function in C

I want to return a character array from a function. Then I want to print it in main . how can I get the character array back in main function?

Please tell me what am I doing wrong?

3 Answers 3

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s) ;
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

Lazy notes in comments.

Also, you need to forward declare substring:

    The Overflow Blog
Linked
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How do I return a char array from a function?

You have to realize that char[10] is similar to a char* (see comment by @DarkDust). You are in fact returning a pointer. Now the pointer points to a variable ( str ) which is destroyed as soon as you exit the function, so the pointer points to. nothing!

Usually in C, you explicitly allocate memory in this case, which won’t be destroyed when the function ends:

Be aware though! The memory pointed at by str is now never destroyed. If you don’t take care of this, you get something that is known as a ‘memory leak’. Be sure to free() the memory after you are done with it:

Возврат char * из функции

Ниже представлены 3 функции. main () распечатывается как ожидалось.
Теперь, в mycharstack () строка хранится в стеке, я думаю, поэтому, так как «ch» выходит из области видимости, он не сможет вернуть строку. Как это работает правильно?
Я предполагаю, что строка, хранящаяся в mychar (), также находится в стеке. Это должно работать правильно?
Я предполагаю, что есть другие ошибки в коде и утечки памяти, пожалуйста, дайте мне знать, если таковые имеются. Я мог бы сделать это чище & проще с std :: string. Но я хочу понять, что происходит с char *.

Решение

В C ++ обработка строк отличается, например, от pascal.

Это делает следующее:

  1. char* ch = new char; создает память для ОДНОГО символа и назначает ее переменной ch
  2. ch = «Hello Heap»; присваивает переменной ch указатель на постоянную память, которая содержит байты «Hello Heap\0» , Кроме того, оригинальное содержание переменной ch теряется, что приводит к утечке памяти.
  3. return ch; возвращает указатель, хранящийся в переменной ch ,

То, что вы, вероятно, хотели

Обратите внимание strcpy -> у вас есть память в ch , в котором есть место для 11 символов, и вы заполняете его строкой из доступной только для чтения части памяти.

В этом случае будет утечка. Вам нужно будет удалить память после записи, например:

Это создаст массив в стеке с байтами «Hello Heap\0» , а затем пытается вернуть указатель на первый байт этого массива (который в вызывающей функции может указывать на что угодно)

Другие решения

Я полагаю, что в mycharstack () строка хранится в стеке, так как «ch» выходит из области видимости, она не должна иметь возможность вернуть строку. Как это работает правильно?

Строковый литерал ссылается на массив, который живет в статический объем памяти. Я надеюсь, что вы знаете о трех областях памяти: автоматическая память (или стек), свободное хранилище (или куча) и статическая память. Эта вещь в стеке — просто переменная указателя, и вы возвращаете значение указателя (адрес, который он хранит) по значению. Так что все в порядке, за исключением того, что вы должны были использовать const char* как тип указателя, потому что вы не можете изменять массив, на который ссылается строковый литерал.

Я предполагаю, что строка, хранящаяся в mychar (), также находится в стеке.

Строка (массив символов) хранится в статической памяти. char* это просто тип указателя, который вы можете использовать для передачи адресов. const также отсутствует.

Я предполагаю, что есть другие ошибки в коде и утечки памяти, пожалуйста, дайте мне знать, если таковые имеются.

Утечка в вашей третьей функции. Вы выделяете память только для одного символа в куче и сохраняете его адрес в переменной с именем ch , Следующим присваиванием вы перезаписываете этот адрес адресом строкового литерала. Итак, вы теряете память.

Вы, кажется, думаете о char* как тип для строковых переменных. Но это не так. Это тип для указателя на символ или последовательность символов. Указатель и строка, на которую он может указывать, — это две разные вещи. То, что вы, вероятно, должны использовать здесь, это std :: string.

Прежде всего, если вы используете C ++, используйте std::string представлять строки.

Теперь к вашему вопросу. char* это указатель на char (или массив char с). Строковые литералы (в кавычках) являются объектами только для чтения массива типа char хранится в какой-то постоянной памяти (ни в стеке, ни в куче).

Как char* является указателем, присвоение ему изменяет указатель. Так mychar() а также mycharstack() оба возвращают указатель на строковый литерал, хранящийся в постоянной памяти.

mycharheap() просто утечки. Вы выделяете один char в кучу, используя new char , а затем забыть его адрес и вместо этого вернуть указатель на строковый литерал. Я думаю, вы имели в виду это:

Тем не менее, чтобы повторить, не используйте char* для строк в C ++. использование std::string ,

Там нет ошибок в вашем коде просто утечка char , Но это довольно странно.

В части «Что ты хочешь» Йоссариан был быстрее меня.

функция mycharheap() протекает: вы указываете указатель на область памяти длиной один char размещается в куче, а затем вы модифицируете этот указатель, чтобы он указывал на строковый литерал, который хранится в постоянной памяти. Выделенная память не будет освобождена.

Пример ниже был вопрос, который возник, когда я пытался извлечь информацию из вызова функции.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *