Are the same type variables in struct guaranteed to be in contiguous in memory wothout any padding?

  c++

I am currently working with Vulkan and want to create reliable way to enymerate through all physical device features without needing to call them by name. Currently I am getting pointer to struct and enumerating in loop like in array:

VkPhysicalDeviceFeatures Features{};
uint32_t size = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
VkBool32* ptr = (VkBool32*)(&Features);
for(uint32_t i = 0; i < size; i++)
{
  // do something with features
  ptr[i];
}

Entire VkPhysicalDeviceFeatures structure have only VkBool32 members which are typedef uint32_t. Is this guaranteed that if in structure there are many variables listed one after another with the same type they will be contiguous in memory without padding? What if in struct there are some other variables with different types and after them there are many variables with the same type? Example:

typedef struct VkPhysicalDeviceVulkan11Features {
    VkStructureType    sType;
    void*              pNext;
    VkBool32           storageBuffer16BitAccess;
    VkBool32           uniformAndStorageBuffer16BitAccess;
    VkBool32           storagePushConstant16;
    VkBool32           storageInputOutput16;
    VkBool32           multiview;
    VkBool32           multiviewGeometryShader;
    VkBool32           multiviewTessellationShader;
    VkBool32           variablePointersStorageBuffer;
    VkBool32           variablePointers;
    VkBool32           protectedMemory;
    VkBool32           samplerYcbcrConversion;
    VkBool32           shaderDrawParameters;
} VkPhysicalDeviceVulkan11Features;

Can i use the same approach with enumerating like in array but not starting at beginning but like this

VkPhysicalDeviceVulkan11Features Features{};
VkBool32* ptr = (VkBool32*)(&Features.storageBuffer16BitAccess)

I am not asking if this approach in code will be readable but if this will be error free, if this will alway work as intended and when enumerating like in array code will always get values from correct memory location?

Source: Windows Questions C++

LEAVE A COMMENT