struct interview questions
Top struct frequently asked interview questions
What's the difference between struct and class in .NET?
I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations are welcome.
Source: (StackOverflow)
Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
Source: (StackOverflow)
I want to initialize a struct element, split in declaration and initialization. This is what I have:
typedef struct MY_TYPE {
boolean flag;
short int value;
double stuff;
} MY_TYPE;
void function(void) {
MY_TYPE a;
...
a = { true, 15, 0.123 }
}
Is this the way to declare and initialize a local variable of MY_TYPE
in ANSI C (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?
Update I ended up having a static initialization element where I set every subelement according to my needs.
Source: (StackOverflow)
Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this question).
What's the actual problem with mutability and structs in C#?
Source: (StackOverflow)
I have seen many programs consisting of structures like the one below
typedef struct
{
int i;
char k;
} elem;
elem user;
I have seen this many times. Why is it needed so often? Any specific reason or applicable area?
Source: (StackOverflow)
When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to logically hold them all together into a cohesive whole.
I came across these rules here (cached):
- A struct should represent a single
value.
- A struct should have a memory
footprint less than 16 bytes.
- A struct should not be changed after
creation.
Do these rules work? What does a struct mean semantically?
Source: (StackOverflow)
In C++, is there any difference between:
struct Foo { ... };
and
typedef struct { ... } Foo;
Source: (StackOverflow)
I'm a beginner in C programming, but I was wondering what's the difference between using typedef when defining a structure versus not using typedef. It seems to me like there's really no difference, they accomplish the same.
struct myStruct{
int one;
int two;
};
vs.
typedef struct{
int one;
int two;
}myStruct;
Source: (StackOverflow)
Is it completely against the Java way to create struct like objects?
class SomeData1 {
public int x;
public int y;
}
I can see a class with accessors and mutators being more Java like.
class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int x;
private int y;
}
The class from the first example is notationally convenient.
// a function in a class
public int f(SomeData1 d) {
return (3 * d.x) / d.y;
}
This is not as convenient.
// a function in a class
public int f(SomeData2 d) {
return (3 * d.getX()) / d.getY();
}
Source: (StackOverflow)
In general, what are the advantages and disadvantages of using an OpenStruct as compared to a Struct? What type of general use-cases would fit each of these?
Source: (StackOverflow)
I came across some code containing the following:
struct ABC {
unsigned long array[MAX];
} abc;
When does it make sense to use a declaration like this?
Source: (StackOverflow)
In Noda Time v2, we're moving to nanosecond resolution. That means we can no longer use an 8-byte integer to represent the whole range of time we're interested in. That has prompted me to investigate the memory usage of the (many) structs of Noda Time, which has in turn led me to uncover a slight oddity in the CLR's alignment decision.
Firstly, I realize that this is an implementation decision, and that the default behaviour could change at any time. I realize that I can modify it using [StructLayout]
and [FieldOffset]
, but I'd rather come up with a solution which didn't require that if possible.
My core scenario is that I have a struct
which contains a reference-type field and two other value-type fields, where those fields are simple wrappers for int
. I had hoped that that would be represented as 16 bytes on the 64-bit CLR (8 for the reference and 4 for each of the others), but for some reason it's using 24 bytes. I'm measuring the space using arrays, by the way - I understand that the layout may be different in different situations, but this felt like a reasonable starting point.
Here's a sample program demonstrating the issue:
using System;
using System.Runtime.InteropServices;
#pragma warning disable 0169
struct Int32Wrapper
{
int x;
}
struct TwoInt32s
{
int x, y;
}
struct TwoInt32Wrappers
{
Int32Wrapper x, y;
}
struct RefAndTwoInt32s
{
string text;
int x, y;
}
struct RefAndTwoInt32Wrappers
{
string text;
Int32Wrapper x, y;
}
class Test
{
static void Main()
{
Console.WriteLine("Environment: CLR {0} on {1} ({2})",
Environment.Version,
Environment.OSVersion,
Environment.Is64BitProcess ? "64 bit" : "32 bit");
ShowSize<Int32Wrapper>();
ShowSize<TwoInt32s>();
ShowSize<TwoInt32Wrappers>();
ShowSize<RefAndTwoInt32s>();
ShowSize<RefAndTwoInt32Wrappers>();
}
static void ShowSize<T>()
{
long before = GC.GetTotalMemory(true);
T[] array = new T[100000];
long after = GC.GetTotalMemory(true);
Console.WriteLine("{0}: {1}", typeof(T),
(after - before) / array.Length);
}
}
And the compilation and output on my laptop:
c:\Users\Jon\Test>csc /debug- /o+ ShowMemory.cs
Microsoft (R) Visual C# Compiler version 12.0.30501.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.
c:\Users\Jon\Test>ShowMemory.exe
Environment: CLR 4.0.30319.34014 on Microsoft Windows NT 6.2.9200.0 (64 bit)
Int32Wrapper: 4
TwoInt32s: 8
TwoInt32Wrappers: 8
RefAndTwoInt32s: 16
RefAndTwoInt32Wrappers: 24
So:
- If you don't have a reference type field, the CLR is happy to pack
Int32Wrapper
fields together (TwoInt32Wrappers
has a size of 8)
- Even with a reference type field, the CLR is still happy to pack
int
fields together (RefAndTwoInt32s
has a size of 16)
- Combining the two, each
Int32Wrapper
field appears to be padded/aligned to 8 bytes. (RefAndTwoInt32Wrappers
has a size of 24.)
- Running the same code in the debugger (but still a release build) shows a size of 12.
A few other experiments have yielded similar results:
- Putting the reference type field after the value type fields doesn't help
- Using
object
instead of string
doesn't help (I expect it's "any reference type")
- Using another struct as a "wrapper" around the reference doesn't help
- Using a generic struct as a wrapper around the reference doesn't help
- If I keep adding fields (in pairs for simplicity),
int
fields still count for 4 bytes, and Int32Wrapper
fields count for 8 bytes
- Adding
[StructLayout(LayoutKind.Sequential, Pack = 4)]
to every struct in sight doesn't change the results
Does anyone have any explanation for this (ideally with reference documentation) or a suggestion of how I can get hint to the CLR that I'd like the fields to be packed without specifying a constant field offset?
Source: (StackOverflow)
I have defined this struct:
typedef struct
{
char A:3;
char B:3;
char C:3;
char D:3;
char E:3;
} col;
The sizeof(col)
give me the output of 3, but shouldn't it be 2? If I comment just one element, the sizeof
is 2. I don't understand why: five element of 3 bits are equal to 15 bits, and that's less than 2 bytes.
Is there an "internal size" in defining a structure like this one? I just need a clarification, because from my notion of the language so far, I expected a size of 2 byte, not 3.
Source: (StackOverflow)