Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old August 28th, 2008, 09:27 PM
Newbie
 
Join Date: Aug 2008
Posts: 1
Default function to array

So I have this simple linked list and i want to insert its elements into a vector(in main function). I've tried the following function and in the main function v[i]=vectore(list);

int vectore(node *list){
if(list!=NULL){
vectore(list->next);
list=list->next;
return list->data;}

ps: im new to C and programming
Reply
  #2  
Old August 28th, 2008, 10:10 PM
boxfish's Avatar
Expert
 
Join Date: Mar 2008
Location: ♩♫♬♪♩
Posts: 380
Default

Hi,
I'm guessing you're doing this in C++; as far as I know, C does not have vectors. It looks like when you call your function, it returns the first item in your linked list. Because the vectore function does not do anything with the return value when it calls itself, all subsequent items are ignored. Your function needs to keep track of all the items as it goes. It could return a vector instead of an int, and take a vector as an argument. Or better yet, it takes a vector as an argument by reference and modifies it. So the header would be:
Expand|Select|Wrap|Line Numbers
  1. void vectore(node *list, vector<int>& vec){
Then if list isn't NULL, you push_back it's data into the vector, set list to it's next, then have the function call itself. You would get rid of the return statement.
Hope this helps.
Reply
Reply

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles