returning a string array from function on stack? | Bytes (2024)

Home Posts Topics Members FAQ

armedmonkey

returning a string array from function on stack? | Bytes (1) 2 New Member

I need to write a function that takes a delimited string and produces an array of strings (just like string.Split() in C#).

Is there a way to allocate this array on the stack so that the caller does not have to worry about freeing each pointer?

I'm using GCC C and only have access to standard libraries.

I am a novice in C, but I understand that stack space is quite limited. These arrays should be on the short side as they just contain unix paths.

The reason I am trying to do this is
a) because the code would look cleaner without having the free code in the caller
b) i'm doing this for a class, and the professor specified:

parse path – split into array of strings. (if you allocate memory here, be sure to free it before you return)

which is not really a requirement, but made me wonder how this is accomplished because as I understand it to accomplish this you have to use strtok and allocate a copy of each string onto the heap, copying and enlarging your array when you reach capacity.

Dec 6 '09 #1

Subscribe Reply

Banfa

9,065 returning a string array from function on stack? | Bytes (5) Recognized Expert Moderator Expert

OK whether stack space is limited or not is actually implementation defined. For instance on windows stack space is normally not very limited at all since it can grow. However on many platforms stack space is limited and I would say it is best practice to treat stack space as though it were limited.

You can not do what you describe on the stack using basic types (you could do it with a class) because what you describe requires a array of pointers that can increase in size (and presumably the pointers have to pointer to varying sizes of data). The size of what is allocated on the stack is generally fixed at compile time so anything that changes data size at run time can not be on the stack.

Dec 6 '09 #2

reply

donbock

2,426 returning a string array from function on stack? | Bytes (6) Recognized Expert Top Contributor

Are you using C or C++?

In C there are only a few options:

1. The function can malloc space for the fragment strings plus the array of points. It is the caller's responsibility to free this memory when done with it. Sounds like you are trying to avoid this option.

2. The caller can pass the necessary memory to the function. This can be either automatic [stack] variables or malloc'ed by the caller. If the latter then the caller is still responsible for freeing the memory. If this option is chosen then the function ought to be able to signal an error to the caller if the provided memory isn't big enough.

3. The caller and function can share access to file-scope variables (either static or extern). This approach is usually considered ... inelegant. It is also not thread-safe.

Here's an example of option 2 using automatic variables:

Expand|Select|Wrap|Line Numbers

  1. #defineNSTRINGS10
  2. #defineMAX_STRING_SIZE40
  3. ...
  4. voidcaller(void)
  5. {
  6. ...
  7. intisFailed;
  8. charstrings[NSTRINGS][MAX_STRING_SIZE];
  9. char*constarray[NSTRINGS]={
  10. strings[0],strings[1],strings[2],strings[3],strings[4],
  11. strings[5],strings[6],strings[7],strings[8],strings[9]};
  12. ...
  13. isFailed=function(...,array,NSTRINGS,MAX_STRING_SIZE);
  14. ...
  15. }
  16. ...
  17. intfunction(...,char*constarray,intnstrings,intmax_string_size)
  18. {
  19. ...
  20. }

Note:

  1. Macros are sometimes necessary in C; they are never necessary and usually ill-advised in C++.
  2. Variables isFailed, strings, and array are automatic variables within function 'caller'. They disappear when 'caller' returns.
  3. Two-dimensional arrays are tricky to use correctly. The only reason I used one here is that it is a concise way to allocate several char arrays all of the same length.
  4. Strictly speaking, trickier use of the two-dimensional array could eliminate the need for the explicit array variable. In my opinion you're better off not being that tricky. Refer to Arrays Revealed to see what I'm talking about.
  5. char * const means that the contents of the strings may be changed, but the string pointers in the array cannot. That's why we need an initializer.
  6. There is no way in C for the function to infer the dimension of the array argument. You should explicitly pass the number of strings in the array and the maximum length of the strings. It is inelegant for the function to refer to the macros direclty, even though they might be in scope.

Dec 7 '09 #3

reply

weaknessforcats

9,208 returning a string array from function on stack? | Bytes (8) Recognized Expert Moderator Expert

Is there a way to allocate this array on the stack so that the caller does not have to worry about freeing each pointer?

Create a process private heap. Allocate from that heap rather than the CRT heap. At the end just delete the heap.

Dec 7 '09 #4

reply

armedmonkey

2 returning a string array from function on stack? | Bytes (9) New Member

Thank you guys, that answers my question very well.

Dec 7 '09 #5

reply

Sign in to post your reply or Sign up for a free account.

Similar topics

6 14034

Returning an array by reference from a function

by: Krackers |last post by:

How do you write a function which returns a reference to an array. I can only get a function to return a copy of the array itself. I've had a look at some other threads in this group an the return value of a function acts like 'by Val' returning the value only (except for objects) can you make it return a reference instead? cheers, Krackers

Visual Basic 4 / 5 / 6

1 3329

C question: Returning string array from function

by: john |last post by:

Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value for my first element but my subsequent printf's will return garbage. Can someone let me know what I am doing wrong. Thanks in advance. -jlewis

C / C++

2 3641

C++ Client needs to fetch a string array from a C# COM server.

by: Bnc119 |last post by:

Hello, I have written a C# COM server that has a few methods and a property called DataItems that returns an ArrayList. During the course of execution the ArrayList gets populated with several strings. I am having issues retrieving these strings from my C++ client. My C# code looks like this: public object DataItems { get

C# / C Sharp

3 2700

Returning an array in a property get returns a copy. How to get a reference?

by: Faustino Dina |last post by:

Hi, The following code is from an article published in Informit.com at http://www.informit.com/guides/content.asp?g=dotnet&seqNum=142. The problem is the author says it is not a good idea to return an array as a property because it will return a copy of the array instead a reference to it. How can I force the property to return a reference to the array? Is it only a feature of arrays? I hope normal class objects (including collections)...

C# / C Sharp

5 10041

Returning char* / System.String array from unmanaged c++ dll into a c# application

by: Mark Ingram |last post by:

Hi, how can i return an array of strings from an unmanaged c++ dll into a c# application? cheers Mark

.NET Framework

5 19599

Problem with webservice returning an array (You must implement a default accessor on System.Array because it inherits from ICollection. )??

by: Stacey Levine |last post by:

I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return an Array instead of an ArrayList. Now I get the message when I try to run just my webservice...

.NET Framework

17 11522

Returning an array of strings in C

by: kleary00 |last post by:

Hi, I am writing a function that needs to return an array of strings and I am having some trouble getting it right. I need some help. Here is what I consider an array of 100 strings: char *array_string Thanks, -Kim

C / C++

19 1842

Returning a string array from a function

by: Adam |last post by:

Hi, I'd like to return an (arbitrary length) string array from a function so that after calling the array I've got a list of strings I can access. After much perusing of the internet I found a related answer here (by Eric Sosman) which involved creating an array of pointers and using that, so it looks something like:

C / C++

9 2684

Array Function

by: =?Utf-8?B?RGFya21hbg==?= |last post by:

Hi, I am wondering how you multi-dimension an array function? My declared function looks like this: Public Function GetCustomerList(ByVal Val1 As String, ByVal Val2 As Long, ByVal Val3 As String) As String() Previously I dimensioned a single dimension Array to the size I wanted and

Visual Basic .NET

5 1406

String array Function

by: sarabonn |last post by:

hallo, I have a function which takes 2 values as input and i want to return that 2 values, so how should write the return statement to return 2 values of String array. I also i should retrieve these values in a button click event. here is my code. public String newop(string userna,string pwd) { cwe_pro.GetFolderContentRequestType preq = new cwe_pro.GetFolderContentRequestType(); ...

.NET Framework

9462

What is ONU?

by: marktang |last post by:

ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...

General

9287

Changing the language in Windows 10

by: Hystou |last post by:

Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...

Windows Server

10046

Problem With Comparison Operator <=> in G++

by: Oralloy |last post by:

Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...

C / C++

1 9857

The easy way to turn off automatic updates for Windows 10/11

by: Hystou |last post by:

Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...

Windows Server

9722

Discussion: How does Zigbee compare with other wireless protocols in smart home applications?

by: tracyyun |last post by:

Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...

General

6542

Couldn’t get equations in html when convert word .docx file to html file in C#.

by: conductexam |last post by:

I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...

C# / C Sharp

5155

Trying to create a lan-to-lan vpn between two differents networks

by: TSSRALBI |last post by:

Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

Networking - Hardware / Configuration

5318

Windows Forms - .Net 8.0

by: adsilva |last post by:

A Windows Forms form does not have the event Unload, like VB6. What one acts like?

Visual Basic .NET

3 2677

Comprehensive Guide to Website Development in Toronto: Expert Insights from BSMN Consultancy

by: bsmnconsultancy |last post by:

In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

General

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisem*nts and analytics tracking please visit the page.

returning a string array from function on stack? | Bytes (2024)

FAQs

How to return an array of strings from a function? ›

  1. In Java, you can return a string array by declaring the return type of a method as String[] and using the return keyword followed by the string array that you want to return. ...
  2. In this example, the method getStringArray() returns a string array containing the values "Hello", "World", and "!"
Dec 28, 2021

Can we return an array from a function? ›

Typically, returning a whole array to a function call is not possible. We could only do it using pointers. Moreover, declaring a function with a return type of a pointer and returning the address of a C type array in C++ doesn't work for all cases.

How to return string array in C function? ›

Return string from function

A string in C is an array of char type. In the following example, we pass the string with a pointer, manipulate it inside the function, and return it back to main(). Inside the called function, there is a local string. The string passed is concatenated with the local string before returning.

How do you return a string array in Python? ›

To return the length of a string array element-wise, use the numpy. char. str_len() method in Python Numpy. The method returns an output array of integers.

Can you return a string from a function? ›

Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.

How do I convert a string back to an array? ›

There are four ways to convert a String into String array in Java:
  1. Using String. split() Method.
  2. Using Pattern. split() Method.
  3. Using String[ ] Approach.
  4. Using toArray() Method.

How to return array from function in C++ without pointer? ›

Use std::vector<std::vector<int>> or std::array<std::vector<int>, 2> instead of plain arrays, which can't be returned from functions. Don't return a pointer to a vector<int> , just return the vector<int> .

How to return an array using a function in C++? ›

  1. you don't return an array in c++. You return a pointer to an array.
  2. For example, if I want a fucntion that takes not inputs and returns a pointer to an array it would be as follows.
  3. int* createAndFillArray(int n)
  4. {
  5. int * mydata = new int[n];
  6. for(int i=0;i<n;i++) mydata[i]=0.
  7. return mydata;
  8. }
Jan 8, 2021

How to pass string array in function in C? ›

An array can be passed to C functions using pointers by supplying a reference to the array's base address, and a multidimensional array can also be passed to C methods.

How to return a string variable from a function in C? ›

You return a string by returning a char*. However, you MUST ensure that the allocation that the char* is pointing to remains around once the function returns, so that means that it must be either a static string (a string that you made a compile time, like known error strings), or a string that is on the heap.

How do I return an array to a string? ›

To convert a JavaScript array to string we can simply use the toString() method of JavaScript on the given array. This method returns the value inside the given array as a string. Let us see some examples of the conversion of an array with different data types into strings.

How do you return a string from a function in Python? ›

To return a string in Python, you can define a function that returns the desired string value. Here's an example: def get_string(): return "Hello, world!"

How to return string[] in Java? ›

Using Only StringBuffer to Take and Return String Data in Java
  1. public static void main(String[] args) { // take input Scanner scan = new Scanner(System.in); ...
  2. String str = scan. nextLine(); ...
  3. // Now, the return type is also StringBuffer. ...
  4. String reverseStr = new String(reversrSb); ...
  5. for(int i=sb. ...
  6. }
May 1, 2020

How to return an array value from a function in Java? ›

To return an array, you declare the method's return type as the array type and then use the return statement to return the array. The code prints 1 2 3 4 5 which confirms that it is returning and processing a one-dimensional array.

Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 5912

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.