We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,018 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

C++ to C

I have some code in C++ that uses an std::vector of std::strings to store an array of strings. I need to convert it into C. I thought that I would just create c versions of the functions I need (vector.back,vector.push_back,string.operator+=) but am getting lost in the double pointers. Can anybody lead me on the right track here?

4
Contributors
5
Replies
4 Hours
Discussion Span
1 Year Ago
Last Updated
6
Views
Labdabeta
Practically a Master Poster
615 posts since Feb 2011
Reputation Points: 27
Solved Threads: 31
Skill Endorsements: 1

std::vector and std::string do a lot of work internally. You'd probably be better off converting the 'what' instead of the 'how'. Ask yourself what the code is trying to accomplish and write C code to do it.

deceptikon
Challenge Accepted
Administrator
3,445 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57

I was thinking of rather than storing a char** to store a single char* string with some delimiting character. I really need a dynamic array of strings so I do not see any other choice.

Labdabeta
Practically a Master Poster
615 posts since Feb 2011
Reputation Points: 27
Solved Threads: 31
Skill Endorsements: 1

You're focusing too much on the 'how'. Explain what the program does and someone can help make suggestions.

deceptikon
Challenge Accepted
Administrator
3,445 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 57

Consider why you must convert to C. I cont see many reasons where C would be necessary over C++.

L7Sqr
Practically a Posting Shark
851 posts since Feb 2011
Reputation Points: 253
Solved Threads: 155
Skill Endorsements: 7

It's not all that difficult to do. Here's an example of push_back

const int BlockSize = 10; // allocate this number of elements at one time
int MaxArraySize = 0; // initial size of the array
int CurrentSize = 0; // current number of elements used in the array

char** array = 0; 

void ReallocArray()
{
   MaxArraySize += BlockSize;
   array = realloc(array,MaxArraySize);
}

char* push_back(const char* item)
{
    if( (CurrentSize+1) >= MaxArraySize )
    {
       ReallocArray();
    }
    array[CurrentSize] = malloc(strlen(item)+1);
    strcpy(array[CurrentSie], item);
    ++CurrentSize;
}
Ancient Dragon
Achieved Level 70
Team Colleague
32,128 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0776 seconds using 2.85MB