FAQ Database Discussion Community


Initialize Const variable of struct

c++,data-structures,struct
Looked around at several other questions and answers, but I can't seem to figure out how to apply it to my situation. Here is my setup: typdef struct sensor { const unsigned char pin; //otherVariables }Sensor; Sensor *left = new Sensor(); void initStruct() { left->pin = 1; //illegal initialization }...

Systemverilog: Simulation error when passing structs as module input\outputs

struct,system-verilog,dpi,questasim
I am trying to pass one structure as an input and get the output in another structure. However I am having some issues during simulation. The following example code compiles fine in questasim, however the simulation gives the following error: Connection type 'core_tb_sv_unit.struct ' is incompatible with 'core_sv_unit.struct ' for...

How can I pass a struct to a kernel in JCuda

java,struct,cuda,jni,jcuda
I have already looked at this http://www.javacodegeeks.com/2011/10/gpgpu-with-jcuda-good-bad-and-ugly.html which says I must modify my kernel to take only single dimensional arrays. However I refuse to believe that it is impossible to create a struct and copy it to device memory in JCuda. I would imagine the usual implementation would be to...

Choosing cells in a struct with specific conditions

arrays,matlab,struct
Data looks more like this: T = struct('Direction', {[1,1,1,1],[1,1,2,1],[2,2,2,2,2], [2,2,2,2,1,2], [2,2,2,2,2],[3,1,4,5]}, 'Tr‌ial', {'correct','incorrect','incorrect','correct','correct','incorrect'}); this is just an example and i have other fields as well T = T(arrayfun(@(x) all(x.Direction == 2), T)); I already have the above code which works fine but it only gives me the [2,2,2,2,2] and it...

Use base struct as function argument in inheritance scenario

c++,inheritance,struct
I want to build a somewhat flexible inheritance for different HLSL-Shaders. Sadly my planned route did not work, and i am wondering why. Here is what i am doing: I have a base-struct and some structs which inherit from it: struct baseStruct {}; struct childStruct1 : public baseStruct { int...

Linking an extern static array of structs is not working correctly

c,arrays,struct,extern,static-array
I am trying to link a statically defined array of structs. I am using the extern modifier to do so. When I print out the memory address of my extern struct, it differs from the location that it appears to be in the executable. Here is what I have: type.h:...

Golang switch between structs

struct,go,interface,switch-statement
I'm new to golang and I'm trying to create a function that, based on the struct it's used on, will return a formatted string using Sprintf type Name struct { Title string First string Last string } type Location struct { Street string City string State string Zip string }...

Port C# Code to Java

java,c#,pointers,struct,pointer-arithmetic
Following problem: I have a c# program doing some de/encryption in a very low level way. I used a tool, to convert most of the c# code to Java, which worked for most of the things but when it comes to such low level parts, the tool fails. The following...

sending the length of the buffer and receive it with C from python

python,c,struct
I am using this simple python server code to send the length of the buffer that I am about to send: def server_mode(ip, port): try: s = socket() s.bind((ip, port)) print ("[*] Listening on %s:%d\n[*] Waiting for clients" % (ip, port)) if ("win32" == os.sys.platform): print("[*] Press Ctrl + Break...

Converting c++ struct to c# and using it?

c#,c++,struct
I have a c++ struct as follow: struct Vehicle { u32 something; Info *info; u8 something2[ 0x14 ]; Vector3f location; Template* data; }; struct Info { u32 speed; std::string name; BuffCollection** buffCollection; void* sectionPtr; }; struct Template { u32 templateID; }; From this question, I figured out the meaning of...

Lifetime parameters for an enum within a struct

struct,enums,rust,lifetime
I don't understand why I get an error with this type of structure enum Cell <'a> { Str(&'a str), Double(&'a f32), } struct MyCellRep<'a> { value: &'a Cell, ptr: *const u8, } impl MyCellRep{ fn new_from_str(s: &str) { MyCellRep { value: Cell::Str(&s), ptr: new_sCell(CString::new(&s)) } } fn new_from_double(d: &f32) {...

Golang Decode Nested JSON into Nested Struct

json,curl,struct,go,nested
I must be doing something wrong here. I've seen all the stackoverflows and my code doesn't look wrong to me..however, I'm not getting a good decoding of the the nested struct for some reason. Here's a snipit: type Input struct { Value1 string Value2 string Value3 string Value4 string Nest...

Adding Characters into Struct

c,string,struct
I am trying to read characters into a linked list (I made this simple test code just to try to read in the characters) for some reason I cannot get it to read in a character value. #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char name[50]; struct node...

Why do strange characters appear when I attempt to write to file?

c,arrays,file,struct
In this program I attempt to write a file that displays an unknown number of records entered by the user. Each record has the following fields: First Name, Last Name, Address, City, State, Zip Code, and Phone Number. I assumed the best way to do this would be to define...

Immutable value type [string] only has mutating members named append

ios,swift,struct
I'm trying to append a new Store object to my stores array in my User struct...I added a mutating func append to my Struct but I'm still missing something as I'm still getting the Immutable value type [Store] only has mutating members named 'append' error import Foundation import UIKit struct...

Load a C-Dll in C# with struct array as parameter

c#,arrays,struct
I try to import functions from my C-Dll. A function has a struct array as a parameter. The struct will be filled in the function. struct test { int test1; int test2; }; void FillStruct( struct test stTest[], int size) { if(size == 2){ stTest[0].test1 = 5; stTest[0].test2 = 5;...

C language, vector of struct, miss something?

c,vector,struct
This is a part of my program that I want to create a vector of struct typedef struct { char nome[501]; int qtd; int linha; int coluna; } tPeca; tPeca* criarPecas(FILE *pFile, int tam) { int i; tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca)); if (pecaJogo == NULL) return NULL; for (i =...

Efficiency penalty of initializing a struct/class within a loop

c++,performance,class,loops,struct
I've done my best to find an answer to this with no luck. Also, I've tested it and don't see any difference whatsoever in an optimized release build (there is a difference in debug)... still, I can't imagine why there is no difference, or how the optimizer is able to...

Using opaque pointers internally in library

c,struct
When writing a library, you sometimes want to hide implementation details from the user. The ideal tool for this is opaque structs or opaque pointers. A problem arises when another source file in the library wishes to use data from this struct. For example: this is the header file apple.h:...

Accessing char array inside struct showing out of bounds error

c,arrays,struct,malloc,dynamic-memory-allocation
I have the following C struct and using the function getPerson(void) that returns a pointer to my struct returns a pointer to a new struct using user input. The following code does not compile and it gives the following error: #include <stdio.h> #include <stdlib.h> typedef struct { char name[50]; int...

Stuck on Structs(c++)

c++,function,struct
Okay so this is what Ive been asked to do "make a struct called Coordinate that contains the latitude and longitude of a point on the surface of the Earth. The struct should also store a label or name for the coordinate (e.g., “Calgary”). Both the latitude and longitude member...

Scoping rules for struct variables in GCC

c,gcc,struct,clang,scoping
Consider the following C program #include <stdio.h> typedef struct s { int x; } s_t; int main() { int x; s_t a; scanf("%d", &x); if (x > 0) { s_t a; a.x = x; } printf("%d\n", a.x); } The a struct variable in the if branch clearly shadows the a...

How to simple assign vectors of different structs?

c++,vector,struct
So I have two different structs (a & b) with same variables and an overloaded = operator in struct b to convert a to b. I want to be able to simple assign a vector of a to a vector b, but compiler gives me an error: main.cpp|61|error C2679: binary...

Why is my array of struct not resizing with Array.Resize?

c#,arrays,struct,resize,streamwriter
I have an array of struct's declared as public struct classMates { public string first; public string last; public string ID; } I am using StreamReader to read in a .txt file and my variables correspond to their relevant value. ie. first == first name, ID == phone number. My...

Byte array to struct

c#,struct,bytearray,converter
I'm having trouble converting the string parts of the byte array. My struct looks like this: [StructLayout(LayoutKind.Sequential, Pack = 1)] struct Message { public int id; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] public string text; } Creation of test byte array: private static byte[] CreateMessageByteArray() { int id = 69; byte[] intBytes...

Trouble with a recursive algorithm and pointers

c++,pointers,recursion,struct,allocation
So I'm trying to make an algorithm that starts at the first "room" and then recursively goes outward and starts deleting all rooms from the outside in. A room is a struct with 4 "doors" (pointers to rooms): North, South, East, and West. The function takes two arguments: pointer to...

When is my struct too large?

swift,class,struct,stack,heap
We're encouraged to use struct over class in Swift. This is because The compiler can do a lot of optimizations Instances are created on the stack which is a lot more performant than malloc/free calls The downside to struct variables is that they are copied each time when returning from...

Handle a value being changed in a c++ struct

c++,struct,operator-overloading,detection
I have a struct that describes how the system should be initialised. I then have a method that returns a reference to said struct so that the user of the final system can change certain options after initialisation. I wish to detect when a value is changed and tell the...

Why can't i use struct nested in a struct as a type to declare variable in a class template? [duplicate]

c++,class,templates,struct,nested
This question already has an answer here: Where and why do I have to put the “template” and “typename” keywords? 6 answers You see, i like structs, so i put some structs inside structs and try to use these nested structs in a class template to declare some variables....

Swift Array Issues

ios,arrays,swift,struct,enums
I have this code: let posState = positionState(pos) if posState != .None { if posState == .Off { boardArray[pos.row][pos.column] == .On } else { boardArray[pos.row][pos.column] == .Off } } The issue I'm having is that when I attempt to change the value of an element in boardArray, nothing happens. Why...

Having two structs refer to each other's variables in C++

c++,struct
I have two different structs which I want to convert to each other like this: PointI a = PointI(3,5); PointF b = a; I assume that I will need to do something like the code below: struct PointF { PointF operator=(PointI point){ x = point.x; y = point.y; return *this;...

Can't sort array of structures alphabetically

c,arrays,sorting,struct,structure
I am trying to sort strings in an array of structures alphabetically then print, but my code doesn't work. I've been trying to figure out why for the past few hours, but can't figure it out. I'm sure its probably something super obvious, but I've only been programming for a...

Why Does Apple use “flags” Structs In Their Classes?

objective-c,c,osx,cocoa,struct
My question is about style/structure in Apple's Objective-C headers. Take NSSplitViewItem, for example: NSSplitViewItem (Apple): @interface NSSplitViewItem : NSObject { @private id _splitViewItemPrivateData; struct { unsigned int _collapsed:1; unsigned int _canCollapseFromDrag:1; unsigned int _canCollapseFromDoubleClickOnDivider:1; unsigned int _reserved:29; } _flags; } Why the Struct? Why does Apple seem to favor using...

How to write a hash function for a std::vector>

c++,hash,struct,stl,unordered-set
I have a struct which has one variable, a std::vector<std::vector<bool>> that represents a grid. One of these structs is equal to another if the grids are equal, or if any rotation of the grids is equal. I'm trying to use an unordered_set to store many of these, however, after some...

Initializing a struct from a constructor

c++,struct,constructor,g++
I'm getting back into writing some C++ and I'm honestly rusty. I get the feeling I'd find a quick answer to my question if I just knew how to phrase it properly, but still I'd appreciate your help. sanitycheck.cpp: #include <string> using namespace std; typedef struct STR_1 { int val_a,...

How do I load data from a txt file into variables in my C program?

c,arrays,parsing,file-io,struct
I have a program that has a struct of channels: struct channel { char title[40]; float gain; float offset; }; int main (int argc, char **argv) { struct channel channels[8]; } And a text file called configurationSettings.txt that holds the information needed to fill up 8 channels: Title1 20 30...

C: Make generic iteration function?

c,arrays,struct,iteration
I have an struct which defines an array of structs, each of which contain a couple more arrays. These inner arrays define my 'datasets'. In numerous places, I wish to iterate over all the datasets. To avoid 3 nested loops, I loop over the total number of datasets and have...

Golang add function to struct defined elsewhere

struct,go
I want to create a function on the sql.Row struct that scans a row into my struct ErrorModel. This is what I am doing: func (row *sql.Row) ScanErrorModel(mod *model.ErrorModel, err error) { err = row.Scan(&mod.MessageId, &mod.ServiceName, &mod.EventName, &mod.Hostname, &mod.Message, &mod.CriticalRate, &mod.Extra, &mod.Timestamp) return } func (dao *ErrorsDAO) Fetch(id string) (mod...

Add more fieldnames to an existing struct

string,matlab,struct
If I have a struct, handles, handles = struct('a',1,'b',2,'c',3) I also have a cell of strings and a cell of numbers cell1 = {'d','e','f'}; cell2 = {4,5,6}; How do I add the field names from cell1 to handles with values from cell2? ...

Assignment of all-zeroes to a nested struct in C (GCC versions < 5)

c,struct,variable-assignment
I have a nested struct in C99 (I'm using GCC 4.8.3 with -std=gnu99 -Wall). struct X { struct { int p; int q; } a; struct { int m; int n; } b; int c, d, e; }; I want to define a "default value" for it which is all-zeroes....

Converting a List defined in a Struct into Int[ , ]

c#,arrays,list,struct
I am struggling a bit with a list which is defined in a particular way. This is the situation: I have a Struct called Edge that is formed by two Points defined in the struct Point in the code (below). My input list is called "EDGE". Using that list I...

Potential issues with p* in structs?

c,pointers,struct,buffer
I have been churning through C for the last several months. In an effort to learn the language, the project is an arithmetic parser - formulas, variables, etc. I recently decided to go ahead and work out garbage collection because I have a lot of calls to this method: char*...

How do I correctly print a struct?

swift,struct
I'm trying to store an array of store structs within my users struct, but I can't get this to print correctly. struct users { var name: String = "" var stores: [store] } struct store { var name: String = "" var clothingSizes = [String : String]() } var myFirstStore...

Optional logic when passing structures in c++

c++,arrays,generics,struct,member-access
I am new too programming and am trying to pass an array of structures and an "option" to a function. I then want the function to be able to manipulate the data within the the array of the struct. struct coordinates{ int x; int y; int z; }COORD; The option...

Casting struct to NSUserDefaults in Swift?

ios,swift,struct,nsuserdefaults
Is there a way I can cast this Swift data set in someway to a form that is acceptable to NSUserDefauts? i.e. NSObject NSSet? (p.s. I realize NSUserDefaults isn't for this type of data, but I'm just testing) struct Users { var name: String = "" var stores: [Store] }...

Referencing yourself inside of a struct

struct,go
Let's say I have a type that's a struct like so: type Authorization struct { Username string Password string Handler func(http.HandlerFunc) http.HandlerFunc } And I have an array of these: type Authorizations map[string]*Authorization I want to be able to do something like this: var auth = Authorizations{ "test": *Authorization{ "someusername",...

Output random element from struct array

c,arrays,random,struct,arduino
Im trying to output a random element from an array of structs on my Arduino. The struct looks like this struct questionStructure { char question[7]; int answer; }; I call a method in my loop that holds a bunch of questions with answers and a random question is then supposed...

GLFW3 create window returns null

c,opengl,struct,code-separation
I was trying to put all GLFW3 init code from main to separate file. When I'm running the code, I get EXC_BAD_ACCESS on glew init function, because GLFW could not create window. Before code separation everything was ok. Is it possible to have GLFW setup code in other function? I'm...

struct member array size based on const int across files

c,arrays,struct
So I want to have a definition of the size of an array within a struct known at compile time. I would also like that number available as a variable for ease of use later. What I have is the following: const int BANANA_ARRAY_SIZE = 10; typedef struct { char...

MPI send struct with bytes array and integers

c++,opencv,struct,mpi,mat
I would like to send image data(array of unsigned char), width and height from rank 0 to rank 1. What is the best way to do this? I've read that to send complex data structure in MPI we can use packaging data or create own data type. What is better...

Issue with bit-fields

c,struct,printf,bit-fields
I have a question related to bit-fields in C. Here I have such a structure: struct Register { int bit:1; }; int main(void) { struct Register bit = {1}; printf("\nbit = %d", bit.bit); return 0; } Can you please explain me why do I get: bit = -1 ...

Allocating memory for pointers inside structures in functions

c,pointers,memory-management,struct
Let's say I declare a structure as it follows: typedef struct { int *numbers; int size; // Size of numbers once treated as array } sstruct; And I create in main() a pointer to structure (in order to later pass it by reference) using sstruct *example;. Then I have a...

How to reset all variables in a struct in C++?

c++,struct,reset
I know how to reset the variable manually one by one, but is their anyway I could call the struct function to re-read the menu(): part? Because those variables are already by default. Or do I have to reset them one by one myself? struct menu { bool update; bool...

struct table inside struct - ASP.NET - allegro webAPI

c#,asp.net,asp.net-web-api,struct
I stopped in one point. I'm writing a small ASP.NET application with WebAPI from polish site allegro.pl (it's similiar to ebay.com) This API have a method which returns me some data: (...) 3. searchArray | SearchResponseType[] Struct table, where are the information about offers that matches the question (...) Inside...

How to pass pointer to struct to a function?

c,function,pointers,struct
I am instantiating the struct within the main() function and I am passing a pointer to this structure over to a function. I would like to then pass this pointer to the original struct to another function, how would I do this? I am now lost in pointerception. struct coords...

Writing variables with points?

matlab,variables,struct
I discovered today that I can write a variable in Matlab like this : line2.start.cart = 1; Is this a structure of line2, that has a subelement start?...

Golang - structs, intializing and memcpy - what is the proper way?

arrays,struct,go,initialization,custom-type
I'm new to Go and I wish to translate some C/C++ code I have to Go but I haven't been able to. The problem resides in 2 places: how can I initialize a struct I've defined and how to do a "memcopy" The code I'm talking about is this: http://play.golang.org/p/e8N255qEAk...

Choosing cells in a structure with fields that contain random elements

arrays,matlab,struct,cells
I really appreciate it if anyone could answer this question. I asked many people and yet could not find a good answer. DATA = struct ('Direction',{[1,1,1,1],[1,1,2,1],[2,2,2,2,2],[2,2,2,2,1,2],[2,2,2,2],[1,4,3,5,2]); I have this structure and I am using the following code to the ones with a specific direction: DATA = DATA(arrayfun(@(x) sum(x.Direction == 2)...

What all operators can be defined inside a struct in C++? [duplicate]

c++,c++11,struct
This question already has an answer here: Operator overloading 6 answers I actually cannot understand 3rd,4th line in the following code in C++ : struct POINT { int x,y; POINT(int x = 0, int y = 0) : x(x), y(y) {} bool operator ==(POINT& a) {return a.x==x && a.y==y;}...

Pointer in Function from a Struct not working

c,function,struct
let's say i got a struct like this: typedef struct myInfo { WORD myCount; WORD data[0]; } myInfo; Well, i would like to use this struct (which is declare extern by the way), in another .c source file, where i've got a function like this: void dynamic_init(struct myInfo dummy){ macroPut(5,...

Global scope for array of structs inside function - Swift

arrays,function,swift,struct,shuffle
I would like to shuffle my array questions and use the shuffled array in the program when it starts. I have created this function that shuffles the array. func shuffleQuestions() { var shuffledQuestions = shuffle(questions) } This gives me an array with questions shuffled that inherits the values from the...

Appending two strings without str functions

c,string,struct,append
I'm having an issue trying to figure out how to append the char pointer c to the existing Struct String. I want to be able to take in input as such (considering a predefined Struct with the value of stuff being "Hello") append(test,"world") When I try to use strcat and...

expected 'struct polygons *' but argument is of

c,struct
I don't know why the error is coming as mentioned in the title. The data are all numbers and the function reads it without problem when tested without pointers. Note: I don't need to use 'malloc' or any other ones. I'm trying to figure what's going with the structure. #include<stdio.h>...

Working with an array within an array - Swift

arrays,swift,struct
I have an array of books. Books have a title and characters. Characters have a name and age. Both Book and Character are structs. When my App launches a set of default Books is created (the user will also add their own later. here is my basic code: (NOTE: The...

Stack Struct Updating Incorrectly During push Function

c,arrays,struct,stack
As part of an assignment, I am currently pushing an array of 2 integers to a stack style structure. With each push, it should add the new array of integers to the top of the stack. Instead it adds one, and changes the whole stack to match the new array....

C - understanding struct members vs pointers (char *)

c,pointers,struct,variable-assignment,c-strings
So I started learning C. It has been smooth so far, but I am finding it difficult understanding a few things. Since I am new, I don't really know what search terms to use, but all my searches have turned up nothing useful. Look at the code below #include <stdio.h>...

Pointers to structures that contain pointers

c,arrays,pointers,struct
Let's say I have a structure (datatype) as it follows: typedef struct { int size; int *p; } mystruct; I declare a new structure as a pointer, because I want to pass it by reference to other functions: mystruct *hello; I have three questions: I understand that to access the...

C++ Struct prototyping in separate header file

c++,c,struct,makefile
I am having trouble understanding an answer I saw in another post. It said that it is good practice to define a struct in a separate .h file so it can be used in other files. I think that is great and it solves my current dilemma, however I have...

C++ Struct is compiled into class?

c++,struct,memory-layout
I am working on C++. I am using MVSV 2010. When I compile a source code and dump the memory layout of all class with -d1reportAllClassLayout. For example, I declare struct: struct my_struct{ int a; }; And the memory layout of struct as following: class my_struct size(4): +--- 0 |...

How to allocate memory to struct pointer using malloc.h header?

c,pointers,struct,malloc,dynamic-memory-allocation
#include<stdio.h> #include<malloc.h> #include<stdlib.h> struct student { char name[25]; int age; }; int main() { struct student *c; *c =(struct student)malloc(sizeof(struct student)); return 0; } What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:...

How to assign a unique_ptr with a custom deleter

c++,c++11,struct,unique-ptr,allegro
I am trying to pass a pointer to a function that then sets a unique_ptr inside a struct to the pointer passed in. However, I get the following compile error on the last line of the function. error C2280: 'std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>>::unique_ptr(const std::unique_ptr< ALLEGRO_BITMAP,std::default_delete< ALLEGRO_BITMAP>> &)' : attempting to reference...

Understanding difference in Swift properties for structs and classes in assignment

ios,swift,oop,struct
My question is in regards to an error that I kept on seeing while writing a function to initialize an optional array in a struct that I solved by just changing the struct to the class. I am hoping that someone can explain to me what I am not understanding...

How to store large arrays of structs - Swift

arrays,swift,struct
I am creating a quiz app which has 2 modes (lets call them A & B). Each mode draws 50 random random questions from an array of structs with over 250 values. To clarify, mode A and mode B both have seperate question pools with over 250 questions, so in...

C create array of struct using constructor function

c,arrays,struct
I have a C struct: typedef struct { Dataset *datasets; int nDatasets; char *group_name; enum groupType type; } DatasetGroup; It has a constructor function like this: DatasetGroup * new_DatasetGroup(char *group_name, enum groupType type, enum returnCode *ret) { DatasetGroup *dg; dg = (DatasetGroup *) malloc(sizeof(DatasetGroup)); if (dg == NULL) { *ret...

Error while trying to update array element

c,arrays,pointers,struct,typedef
I am working on an embedded platform which does not have debugging features. So it is hard to say what is the error source. I have defined in header file: typedef struct cm_packet { CM_Header Header; //header of packet 3 bytes uint8_t *Data; //packet data 64 bytes CM_Footer Footer; //footer...

passing an array of structs to a function and changing it through the fucntion

c++,c,arrays,function,struct
so this is my code but it wont compile for some reason. Error 3 error C2036: 'pjs *' : unknown size Error 4 error C2100: illegal indirection Error 5 error C2037: left of 'size' specifies undefined struct/union 'pjs' void initArray(struct pjs* array) { (*array[1]).size = 1; } struct pjs{ char*...

type-conversion in one function in C

c,function,struct,type-conversion,typedef
I have one doubt, could it be possible to create one typedef struct whatever and then if one function requires: void function(char * something); when you call the function in main program write: function((char *) whatever); is that correct? Thank you!...

Adding to struct from a loop (c++)

c++,visual-c++,for-loop,struct
So I'm using the code below but am getting an error when trying to call the text from a line in the struct. struct lines { LPCSTR text; int mInt; }; for (int n = 0; n < lineCount - 1; ++n) { vector<lines> sub; lines lineData; LPCSTR onlinePlayerName =...

How to override C compiler aligning word-sized variable in struct to word boundary

c,gcc,struct,bit-packing
I have a structure specified as following Member 1, 16 bits Member 2, 32 bits Member 3, 32 bits which I shall be reading from a file. I want to read straight from the file into the struct. The problem is that the C compiler will align the variables m1,...

how to initialize static array within struct

c,arrays,struct,initialization,static-array
I have this struct: typedef struct { int start; int end; char board[10][10]; } move; when I try initializing it this way: char new_board[10][10] move struct new_move = {0, 0, new_board} I get this error: warning C4047: 'initializing' : 'char' differs in levels of indirection from 'char (*)[10]' any suggestions?...

Why I cannot use “fgets” to read a string to an element of my Struct?

c,pointers,memory-management,struct,fgets
I'm trying to create a program almost like "bank" using struct, but when the program should have read the string (variable "nome" that is name in portuguese) it totally ignore the "fgets" that I used. This is the part that I was talking about : printf("\nNome: \n"); fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);...

Initializing, constructing and converting struct to byte array causes misalignment

c,arrays,pointers,struct,memcpy
I am trying to design a data structure (I have made it much shorter to save space here but I think you get the idea) to be used for byte level communication: /* PACKET.H */ #define CM_HEADER_SIZE 3 #define CM_DATA_SIZE 16 #define CM_FOOTER_SIZE 3 #define CM_PACKET_SIZE (CM_HEADER_SIZE + CM_DATA_SIZE +...

copying the content of an dynamic array of structs into another dynamic array using memcpy

c,struct,malloc,memcpy
I want to copy the content of a dynamic array containing 2 structs to another dynamic array of the same size. I need an exact copy. When I compile, I get these 2 errors at the last line: invalid use of undefined type ‘struct student’ & dereferencing pointer to incomplete...

MATLAB - Sort struct by substruct field

matlab,sorting,struct
I'm a new Matlab user and a I have some doubts about structs. My case is: I have a struct P1 that have 3 "substructs"( A1, A2, A3) with two fields(Name and Age) and I want to sort my "substructs" by age. So, I have it: P1.A1.age = 33 P1.A2.age...

Using reflection to get attribute names in struct returns value__

c#,reflection,struct,attributes
I want to populate a combo box with all of the available item types in my struct ItemTypes: public enum ItemTypes { Ore, Ice, Mineral, Pi } In order not to add a new item type in 2 places if I do have to add one eventually (not likely, but...

C++ and packed struct

c++,class,struct
I have database project that I want to move from C to C++. In this C project I have lots of small packed structs, that I write directly to file or read from mmaped file - e.g. directly from memory address. I need the class in-memory representation, to be exactlybthe...

Reading a shader from a .txt file using a structure

c++,opengl,struct,shader
I've started learning how to use OpenGL and I absolutely hate having my shaders declared as global variables before my main(). I thought it would be cool to make a structure or class that would read the shader from a file in my project directory. The file reading works perfectly...

Accessing struct from double pointer

c,pointers,struct
I'm currently trying to implement a doubly linked list in C, and am not understanding how to access the struct from a double pointer. Here is my simple struct: typedef struct node { int val; struct node * next; struct node * prev; } node; Here is a simple method...

compile md5 checksum in C but got compile error

c,struct,compiler-errors,md5
Tried to follow the example in SO example, but when compiling the following, got error: $ gcc te.c te.c: In function ‘main’: te.c:10:17: error: storage size of ‘context’ isn’t known Here is the code: #include <string.h> #include <stdio.h> #include <openssl/md5.h> //#include <md5.h> int main(int argc, char *argv[]) { unsigned char...

How to search for specific structure from Structures of data array and read using fread?

c,struct,fread,fseek,strstr
My text file looks like this, Person.txt John { sex = "Male"; age = 23; }; Sara { sex = "Female"; age = 23; }; stephan { sex = "Male"; age = 25; }; I want to fetch the specific person's data based on the request. For Instance, I got...

nodes and structures in c

c,struct,nodes,huffman-coding
I'm trying to make a huffman coder.. but I'm having some problems... This is how I define my structure of a node.. struct node{ int type,prob; char *code; struct node *left, *right; }; I order by probabilities and I create a new node struct node join_nodes(struct node no1, struct node...

How to make a function return a pointer to array struct

c,arrays,pointers,struct
I'm working on a function in C that should return a pointer to an array struct. The struct is struct corr{ char nome[128]; char cognome[128]; char password[10]; float importo; }; typedef struct corr correntista; The function that return a pointer to this struct is correntista *max_prelievo(FILE *fcorrentisti, FILE *fprelievi){ correntista...

VexCL vector of structs?

c++,struct,opencl
So I know that it is possible to use custom types with OpenCL. But I haven't been able to use them with VexCL. Creating a device vector of structs works fine, but I can't perform any operations. As I haven't found any examples using custom types with VexCL my question...

goroutine channels over a for loop

json,struct,go,channels
My main function reads json from a file, unmarshals it into a struct, converts it into another struct type and spits out formatted JSON through stdout. I'm trying to implement goroutines and channels to add concurrency to my for loop. func main() { muvMap := map[string]string{"male": "M", "female": "F"} fileA,...

C++ reading a file into a struct

c++,struct,io,fstream
Using fstreams I have a file opened that contains numerous lines. Each contiguos set of 4 lines are such that: the first line is an int, the second and third are strings and fourth is a double. This sequence continues till EOF. I'm attempting to load these lines into a...

Why is my file output overwritten?

c,file,struct,formatting
My program takes user input and stores it in an array of Records that I've defined as a structure: struct Record. The user input is are the fields of the struct. Everything complies error free, but it seems I can't get the formatting correct. My program keeps asking for user...

Adding elements to Struct Array

c,arrays,multidimensional-array,struct
struct GENERATIONS { char generation[MAX_ROWS][MAX_COLS]; int hasCycle; }; typedef struct GENERATIONS Generation; I have an array of type struct: Generation generations[MAX_GENERATIONS]; I declare a Generationvariable like this: Generation *currentGeneration = NULL; currentGeneration = (Generation *) malloc(sizeof(Generation)); and attempt to add a generation to an array of generations: numGenerations is set...

A structure that stores its fields by size

c++,templates,c++11,struct,variadic-templates
I would like to know how can I do the following in C++: Consider these classes : C1 < C2 < C3 < ... < Cn, Ci < Cj means sizeof(Ci) < sizeof(Cj) I want a structure that uses variadic templates as a sequence of Ci's, OrderBySize<AnySequenceOfCis>, for example :...

Fill value by value a char *

c,list,pointers,struct,char
I'm trying to fill a char *info inside a struct nodo; This is struct : struct nodo { char *info; struct nodo *prec; struct nodo *succ; }; typedef struct nodo nodo; And this is whole function : nodo *q,*t = NULL,*head = NULL; int i, nodi=0 ; char *c =...

Passing a struct to a template with extern const. What is the extern for?

c++,templates,struct,const,extern
I am asking myself why the following code works and what the specifier extern does when instantiating baz_instance: struct baz { int value; }; extern const baz baz_instance = {3}; template<baz const& b> int foo(){ return b.value; } int main(){ foo<baz_instance>(); return 1; } Why does the above code compile...