473,671 Members | 2,421 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

function returning array of strings

Hi All

I have to write a function which basically takes in a string and
returns an unknown number( at compile time) of strings

i hav the following syntax in mind

char *tokenize(char *)[]

is it ok?

if yes then how do i call the function inside a code?

Suppose it returns 3 strings then

i must hav something like

char *c[3];
c = tokenize(/*the string*/)[];

is this the correct way to declare and use function returning arrays of
string?

any suggestion will be most welcome

thanks & regards
shyam

Nov 28 '05 #1
5 5477

shyam wrote:
Hi All

I have to write a function which basically takes in a string and
returns an unknown number( at compile time) of strings

i hav the following syntax in mind

char *tokenize(char *)[]

is it ok?

No. Functions cannot return array types. Functions can return
pointers to arrays, however:

char *(*tokenize(cha r*))[N] // return a pointer to an N-element array
of pointer to char

But that's not what you need, since you don't know how many substrings
you are returning.
if yes then how do i call the function inside a code?

Suppose it returns 3 strings then

i must hav something like

char *c[3];
c = tokenize(/*the string*/)[];

is this the correct way to declare and use function returning arrays of
string?

No. You cannot assign to an array object like that.
any suggestion will be most welcome

It's hard to make suggestions without giving away the answer
completely, but I'll try.

Since you don't know ahead of time how many substrings are going to be
in the parameter string, you are going to have to dynamically allocate
an array to hold the pointers to the substrings. The general form for
doing something like that is

char **arr;

arr = malloc(sizeof *arr * number_of_subst rings)
if (arr)
{
size_t i;
for (i = 0; i < NUM_ARRAY_ELEME NTS)
{
arr[i] = next_substring; // type of arr[i] is char*
}
}

return arr;

Note how arr is declared; this will be the return type for the
function, as well as the type of the object in the caller.

Hopefully that was enough of a hint to get you headed in the right
direction.
thanks & regards
shyam


Nov 28 '05 #2

"shyam" <sh********@gma il.com> wrote
I have to write a function which basically takes in a string and
returns an unknown number( at compile time) of strings

i hav the following syntax in mind

char *tokenize(char *)[]

is it ok?

if yes then how do i call the function inside a code?

Suppose it returns 3 strings then

i must hav something like

char *c[3];
c = tokenize(/*the string*/)[];

is this the correct way to declare and use function returning arrays of
string?

No.

char **tokenize(char *string)
{
/* pass through the string, countin white space or other delimiters */
/* this tells you how many tokens - allocate an array of pointer to hold
them, which you return */

/* then pass thorugh again, pulling out all the tokens. Probably you want to
duplicate them
one at a time, holding the results in the array you return */
/* finally, caller probably wants some way of knowing how many tokens were
parsed. Either set an integer pointer, passed in, or set the last element of
the array to NULL. */
}
Nov 28 '05 #3
John Bode <jo*******@my-deja.com> wrote:
char **arr; arr = malloc(sizeof *arr * number_of_subst rings)
if (arr)
{
size_t i;
for (i = 0; i < NUM_ARRAY_ELEME NTS)
{
arr[i] = next_substring; // type of arr[i] is char*
}
} return arr;


A note for OP: You will have to arrange to tell the caller how many
array elements there are, perhaps by returning a struct containing an
integer and a char **.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 28 '05 #4
Hi All

Based on ur suggestions i hav complied the below program but i am stuck
with some segmentation error
I have included in the comments wherever i have doubts
Please advise

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

#define SP ' '

char **tokenize(char *);
char ** tokenize(char *ch)// to tokenize the string based on space
{

int count = 0;
char *mrk = ch;

while(*ch != '\0')
{
if(*ch == SP)

count++;

ch++;

}

count = count + 2;

ch = mrk;

char **c = (char **)malloc(count * sizeof(ch));

int count2;
char *fst,*lst;

fst = lst = ch;

for (count2 = 0; count2 < count - 1; count2++)
{

lst = strchr(lst,SP);

*lst = '\0'; //the DDD crashes at this point

lst++;

c[count2] = fst;

fst = lst;
}

c[count - 1] = NULL;

return c;

}
int main()
{

char *s = "hello how do u do";

char **t = tokenize(s);

printf("the str is %s\n",*t[0]);//similarly for s[1] & s[2]
}
regards
shyam

Nov 29 '05 #5
shyam wrote:
Hi All

Based on ur suggestions i hav complied the below program but i am stuck
with some segmentation error I have included in the comments wherever i have doubts
Please advise

#include<stdio. h>
#include<string .h>
#include<malloc .h>
There is no such header. It should be:

#include <stdlib.h>
char **c = (char **)malloc(count * sizeof(ch));
Should be:

char **c = malloc(count * sizeof *c);

Don't cast the value returned by malloc.
Also you should check to see if the malloc succeeded.
char *fst,*lst;
fst = lst = ch;

for (count2 = 0; count2 < count - 1; count2++)
{
lst = strchr(lst,SP);
*lst = '\0'; //the DDD crashes at this point
So you are modifying the string you passed in....

int main()
{
char *s = "hello how do u do";
char **t = tokenize(s);


.... But string literals are not modifiable, so you cause undefined
behaviour. Change your main function to this:

char s[] = "hello how do you do";
char **t = tokenize(s);

If you are using GCC then you can detect this error by
using the compiler switch -Wwritable-strings .

Nov 29 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
29049
by: Tweaxor | last post by:
Hey, I was trying to figure out was it possible in C to pass the values in an array from one function to another function. Is the possible in C? ex. y is the array that holds seven values If possible how could one pass these seven values in the array to a function that would check the values. I tried return y but it didn't work
5
2249
by: damian birchler | last post by:
What's wrong about this: 22: static void (*)(void) instruction_table = { jnz, halt, mv, add, mul, mv_reg, add_reg,
4
40853
by: Woody Splawn | last post by:
How would I pass an array back to a sub routine from a function? That is, I have a function that looks like this Public Function arrayTest() As Array Dim states() As String = { _ "AZ", "CA", "WA" _ } Return states End Function
4
15000
by: John | last post by:
Hi I need to return an array of string in my own split function (access 97). I have defined the function as below but I get err on 'As String()'. What can I do to make the function return an array of strings? Public Function Split(ByVal strIn As String, Optional strDelimiter As String = " ") As String() Thanks
18
2344
by: svata | last post by:
Hello to all, as a result from my previous post I'm busy with splitting code into functions. The one problem ( out of many ) I encounter is how to properly use/code a function which returns either array of characters(string) or a pointer to this array. I read some articles, some other posts and come to this solution:
20
8983
by: Andrew Morton | last post by:
Is it possible to have two function declarations which take the same parameters but return different types depending on how the function is used? function f(x) as string ' return a string end function function f(x) as string() ' return an array of strings end function
8
1786
by: jodleren | last post by:
Hi! I have a function, a part of my code which I can use as a function. It will return 2 arrays, and I am wondering what way to do so. Both arrays hold strings, there are no special keys. 1) setting the arrays as globals 2) returnin an array of arrays 3) returning a large array with a known marker to indicate when the 2nd part starts.
26
4850
by: aruna.mysore | last post by:
Hi all, I have a specific problem passing a function pointer array as a parameter to a function. I am trying to use a function which takes a function pointer array as an argument. I am too sure about the syntax of calling the same. #include <stdio.h> void fp1()
13
1981
by: Sri Harsha Dandibhotla | last post by:
Hello all. I recently came across a function declaration as : char(*(*x()))(); This was not in some code but it was in a C questions thread on some group. I tried to decipher what it returns but couldn't make complete sense out of it. Can someone please explain what this function is supposed to return and expand it step by step. Thanks,
0
8401
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,...
0
8926
Oralloy
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...
0
8673
tracyyun
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...
0
7444
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6236
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5703
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();...
0
4416
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2818
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1815
bsmnconsultancy
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...

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

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.