Copy string from 2D array to a 1D array in C

Joined
Nov 1, 2023
Messages
2
Reaction score
0
Hi,

I'm trying to copy a string from a malloc'd struct 2D array member to a nested struct 1D array member within the struct that contains my list of strings in my 2D array member. I cannot use strcpy() or memcpy() because of the fact that the source string is not in a constant (it's char *, not const char *). I also have to use pointers as the two arrays are allocated on the heap with malloc().

I've read numerous forum posts and looked at numerous examples to the point where my head hurts. But I cannot find anything that directly either provides an example that I'm able to understand, or that directly provides a complete example. Every single thing I try either causes the compiler to throw errors or warnings, or I get a segfault (I'm using Linux). I'm at my wits end with it, I do not know what else I can try, let alone what I'm doing wrong. I've lost count at the number of different things I've tried.

Could somebody either supply a C library function that I can use, or a complete example of using pointers to copy from a 2D malloc() allocated array in a struct to 1D malloc allocated array in nested struct within the before-mentioned struct? Can I also ask that any advice or examples be very clear with clear variable names used so I can understand it. I haven't included any code as it's in a number of headers as well as .c source code files and it would be just too long to post. Again, all I'd like to do is just copy one string from a 2D array in a struct to a 1D array in a nested struct within the struct my 2D array is a member of (where both array's are allocated by malloc().

(I did just think of something that would have caused everything I tried to fail, but I'd still be interested for people's thoughts on it - particularly if anyone knows of any C library function that could save me the trouble of writing my own string copy function that uses pointers directly)

Just a few things:
I understand what arrays are.
I understand what 2D arrays are (including pointer arrays).
I understand what pointers are.

Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top