技术疑问:EGG结构体中spams成员是否应定义为SPAM**而非SPAM*?
Should the
spams member of EGG be SPAM** instead of SPAM*? Great question! Let’s break this down based on your current code and your future plan to store SPAM arrays in the spams member.
First, let’s look at how your code works right now:
my_spamsis a static array ofSPAMstructs, which decays to aSPAM*pointer (pointing to the first element of the array) when assigned tomy_eggs[0].spams.- With the current
SPAM*definition, you can already iterate through all elements using thenum_spamscount (since the array is contiguous in memory). This works perfectly for a single SPAM array.
Now, let’s clarify the difference between SPAM* and SPAM**:
SPAM*: This points to either a singleSPAMstruct, or the start of a contiguous array ofSPAMstructs. It’s ideal when you’re working with one array (whether statically allocated like yourmy_spams, or dynamically allocated withmalloc). You use thenum_spamsfield to know how many elements are in that single array.SPAM**: This is a pointer to a pointer toSPAM—it’s used when you need to manage multiple independent SPAM arrays (like a collection of separate arrays, each with their own length). For example, if you wanted to store 3 different SPAM arrays (each with different sizes) inspams, you’d useSPAM**to hold pointers to each of those arrays.
So, do you need to change it to SPAM**?
It depends on your exact future needs:
- If you only ever need to store one SPAM array (even if you resize it dynamically later, e.g., using
realloc), keepSPAM*. Here’s an example of dynamic allocation withSPAM*:// Dynamically create a SPAM array with 3 elements EGG dynamic_egg = { "dynamic egg", 3, malloc(3 * sizeof(SPAM)) }; // Assign values to the array elements dynamic_egg.spams[0] = (SPAM){ "nameA", "valueA" }; dynamic_egg.spams[1] = (SPAM){ "nameB", "valueB" }; dynamic_egg.spams[2] = (SPAM){ "nameC", "valueC" }; - If you need to store multiple independent SPAM arrays (e.g., a list of separate arrays where each can grow/shrink independently), then you should switch to
SPAM**. Here’s how that might look:// Create an EGG that holds 3 separate SPAM arrays EGG multi_array_egg = { "multi-array egg", 3, malloc(3 * sizeof(SPAM*)) }; // Assign the first array (dynamic, 2 elements) multi_array_egg.spams[0] = malloc(2 * sizeof(SPAM)); multi_array_egg.spams[0][0] = (SPAM){ "nameX", "valueX" }; multi_array_egg.spams[0][1] = (SPAM){ "nameY", "valueY" }; // Assign the second array (dynamic, 1 element) multi_array_egg.spams[1] = malloc(1 * sizeof(SPAM)); multi_array_egg.spams[1][0] = (SPAM){ "nameZ", "valueZ" }; // Assign the third array (your existing static array) multi_array_egg.spams[2] = my_spams;
In short: Stick with SPAM* if you’re managing a single SPAM array. Use SPAM** only if you need to manage multiple distinct SPAM arrays.
内容的提问来源于stack exchange,提问作者Milind
相关产品推荐
相关产品推荐

