The title might seem a little confusing but I'll try to explain. I have a struct and I know I'm getting a certain number of char arrays, which have a constant size, so to give an example:
1. abcd
2. bcde
3. cdef
etc.
So far I have searched on different forums and I have the following code:
1 2 3
struct a{
char(*arr)[4];
};
This seems to compile, but I'm not sure how to initialise and use it afterwards, not even sure if it is correct. Any idea of how to achieve something like this? Thanks in advance.
Do not forget to leave room for the 0 end of string marker that C uses. You need [5].
to use it you need to allocate memory for it manually and release it after
I will be honest, I do not know how to allocate/use the thing you made either. this is how I know to do it:
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
typedefchar c4[5] ;
struct a { c4* many;};
a s;
s.many = new c4[100];
sprintf(s.many[42], "fubr");
cout << s.many[42];
delete[] s.many;
}
you can, and probably should, move the allocation and deallocation into a constructor/destructor for the struct.
But that aside, do you have to do this using C like constructs, or can you use c++?
C++ would just say
struct a
{
vector<string> data;
};
...
data.push_back("abcd"); //add items to the vector.
...
cout << data[i]; //works like array of strings here.
Hi, sorry that I have been inactive, it's just that I've been tasked with doing 10 different things since and I totally forgot about this issue.
I didn't leave space for the termination char on purpose, since I'm going to create another string out of those, which should not containt anything else except the relevant characters, because then I have to send it to a server, where it will get encoded. So if I had a termination char in there then the end result would be faulty.
typdef is definitely a good idea, no clue why I didn't think of it myself. Oh well...
that will cause you some troubles. If you leave off the space for the 0 character, you MUST NOT use standard C string functions that depend on either it being there (strlen, etc) or that put it there as a result (sprintf, strcpy, strcat, etc).
what I recommend in that case is to have a temporary C string that you can do these operations safely with, and use a memcpy to move the 4 letters you want to keep from the result into your target storage. Or if you do not need the C string functions, just dump the letters you need and keep going is fine too. Just be careful with it.