I suggest you to store distinct point values in List(). You can use following code to achieve it: using System; using System.Collections.Generic; namespace Test { struct Point { public readonly double X; public readonly double Y; public Point(double x, double y) { X = x; Y = y; } }...
You cannot define methods of non-local types. As per Spec: The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. (Emphasis added.) What you can do is create...
Your question is a bit unclear but here is how I would do this. struct Character { var name: String var age: Int } struct Book { var title: String var characters: [Character] } var books: [Book] = [] func createBooks() { let character1 = Character(name: "John", age: 24) let...
Though there is likely a more efficient method, the first thing that comes to mind would be utilizing dynamic field names: handles = struct('a',1,'b',2,'c',3); cell1 = {'d','e','f'}; cell2 = {4,5,6}; for ii = 1:length(cell1) handles.(cell1{ii}) = cell2{ii}; end Which returns: handles = a: 1 b: 2 c: 3 d: 4...
Easiest way with the above code is to copy from a new instance, e.g.: menu blah; // reset blah to defaults blah = menu(); ...
c++,hash,struct,stl,unordered-set
What you could do is combine the hashes for all the vectors within the matrix. There is an overload of std::hash for std::vector<bool>. If you try something like this size_t hash_vector(const std::vector< std::vector<bool> >& in, size_t seed) { size_t size = in.size(); std::hash< std::vector<bool> > hasher; for (size_t i =...
c#,arrays,struct,resize,streamwriter
You need to declare your method in the following way: static void addClassMates(ref classMates[] classMateInfo) Notice the ref for the parameter....
c,opengl,struct,code-separation
The reason for not getting the window opened is that one has to specify GLFW_CONTEXT_VERSION_MINOR in addition to the other window hints. This could be done, e.g., with: glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); ...
c,arrays,sorting,struct,structure
First of all, the algorithm you are trying to build is not sorting. What you have here is (after fixing issues described below) one iteration of bubble sort. To make it actually sort the array you need to call dictioarySort 10 times. See https://en.wikipedia.org/wiki/Bubble_sort for more details. Now to the...
arrays,struct,go,initialization,custom-type
So basically given these basic types: type xchr int8 type xint int type xdob float64 type xflt float32 You want to copy the bytes (memory representation) of a value of the following struct type: type VEH1 struct { // 52 bytes total p xint // 4 bytes (READ BELOW) lat_lon_ele...
Following may help: struct pjs{ char* name; int size; int price; }; // safer to use one of the following declaration // void initArray(pjs *array, std::size_t size) // simpler // void initArray(pjs (&array)[10]) // more restrictive but unintuitive syntax void initArray(pjs* array) { array[1].size = 1; } int main() {...
You're using a mix of C++ (std::string) and C (char*) strings in an invalid way. In the constructor, you're building up the code in a C++ string, which is an object that automatically allocates and re-allocates the memory to hold the string data as the string grows. It will also...
The struct you see in the debugger is empty because when you enter Function1 the debugger 'forgets' any info about cs1 and knows just about baseStruct (which is empty). If you do something like childStruct *cs1 = reinterpret_cast<childStruct1>(&structVal) ; yoy should see everything there. But this takes to the real...
The two ways to store the questions on disk are: 1) Core data 2) Sqlite I would suggest the following architecture to retrieve the stored questions: 1) Store 250 questions in core data/sqlite with each question associated with a number 1-250. 2) When you need to select 50 questions randomly,...
c,arrays,struct,malloc,dynamic-memory-allocation
Array index in C is 0 based. For an array with 50 bytes of memory allocated, char name[50]; trying to use [50] as index is off-by-one and invokes undefined behaviour. That said, newPerson->name[50] = *nameInputPtr; is not the way you copy a string. You need to make use of strcpy(),...
What you are looking for is the packed attribute. This will force gcc to not do any padding around members. Taken from the GCC Online docs: packed This attribute, attached to an enum, struct, or union type definition, specified that the minimum required memory be used to represent the type....
struct,system-verilog,dpi,questasim
SystemVerilog has strong typing rules for user defined types. A typed declared in one scope is not the same as a type declared in another scope, even if it has the same name and same internal layout. A user defined type is only compatible with itself. Define your types in...
The sender segfaults because you are trying to send the data starting from the location of the Mat.data pointer itself and not from the location in memory where it points to. The receiver segfaults because there is no space to store the 768 KiB of data (should any arrive). You...
What is happening is that tPeca pecaJogo[tam]; is a local variable, and as such the whole array is allocated in the stack frame of the function, which means that it will be deallocated along with the stack frame where the function it self is loaded. The reason it's working is...
(The author of JCuda here (not "JCUDA", please)) As mentioned in the forum post linked from the comment: It is not impossible to use structs in CUDA kernels and fill them from JCuda side. It is just very complicated, and rarely beneficial. For the reason of why it is rarely...
c,pointers,memory-management,struct,fgets
Problems that I see: You are allocating the wrong amount of memory in the line: vet = (CLIENTES*)malloc(num*sizeof(int)); That should be: vet = malloc(num*sizeof(*vet)); See Do I cast the result of malloc?. The answers explain why you should not cast the return value of malloc. You are using fgets after...
c++,struct,operator-overloading,detection
I will assume your struct is named Fun Solution 1: Add getter, setter and notify I would write a getter and a setter for each properties of the said struct. It would look like this: struct Fun { Fun(System& sys): system{sys} {} void setGun(int g) { gun = g; notify();...
This happens because the >> operator for the input stream only grabs part of a line, and does not always grab the newline character at the end of the line. When followed by a call to getline, the getline will grab the rest of the line previously parsed, not the...
There are a lot of things wrong with your code. Here's what I noticed just right of the bat: You used a variable name append inside a function called append, which is bad form. I'm not even sure if that compiles. The= operator was used when == was actually needed....
The key concept is that you define the struct/class in a .h header, so that you can use it in multiple .cpp files. Whenever you need struct foo defined in foo.h, you #include "foo.h". You don't need to directly compile the header file, it will be pulled in by whichever...
The problem is at this line: byte[] stringBytes = GetBytes(text); How are you converting the string to a byte array? You are probably using a Unicode encoding, which will store each character as two bytes, and because your string is in the ASCII set, every other byte will be zero:...
You’re initializing them just fine. The problem is your store struct is using the default printing, which is an ugly mangled version of the struct name. If you make it conform to Printable, it should print out nicely: extension Store: Printable { var description: String { // create and return...
You're printing the channels info, not the data it contains. You don't want a loop, you just want to receive then print. json := <-index json.NewEncoder(os.Stdout).Encode(json) Now I do I need to point out, that code is not going to block. If you want to keep reading until all work...
c#,asp.net,asp.net-web-api,struct
It is standard array initialization. The only difference is that you have an array of structs. Just use: AttribStructTable = new [] { new AttribStruct { AttribName = "YOUR_NAME", AttribValues = new [] { "Value1", "Value2" } }, // There can be n array items } Reference to MSDN arrays...
A pointer in a struct is a fixed size, regardless of what it is pointing at, even if it is uninitialised. That way, sizeof(struct token) is a fixed length. When malloc is used, the memory is taken somewhere from the heap, we know not where, and should not care either....
if let selectedIndex = addStoreViewController.index { stores[selectedIndex] = store! } else { if let selectedUser = user { selectedUser.stores.append(store!) } } This appears to be the problem section. We can both simultaneously fix your problem and clean up your else code a bit: if let store = store, selectedIndex...
First, forward declare one of the structs and fully declare the other. You'll need to use either a reference or pointer for the forward declared type, since the compiler doesn't have its definition yet: struct PointI; struct PointF { PointF operator=(const PointI& point); float x, y; }; Next, you need...
You have declared coordinate startPt, endPt; in main() and you are trying to access them Readcoordinate(). To resolve error you should declarecoordinate startPt, endPt;inReadcoordinate()` or pass them as argument. coordinate Readcoordinate() { coordinate startPt; cout << "Enter Longitude(in degrees)" << endl; cin >> startPt.latitude >> startPt.longitude >> startPt.city; return startPt;...
In matlab the . operator allows you to create structs without explicit declaration, as in your case in which you are creating a struct with name line2 which contains a struct start with attribute cart. The . operator is also used to view the struct contents and extend existent structs....
structure is nothing but a class with all its data members and functions defined in public scope. So you can implement any operators which is valid for a class. If your question is on operator overloading, all overloaded operators can be defined for a class is valid for a structure....
objective-c,c,osx,cocoa,struct
They are using bit fields. In this case, it means that three values are stored in just 32 bits. Plus for future extension, they can add 29 more boolean variables in the same 32 bits, without changing the layout of the structure. If data is persisted, then adding these 29...
There are at least two problems with your code: one serious, one in terms of naming. In the function struct node join_nodes(struct node no1, struct node no2) no1 and no2 are passed by value. They are temporary objects, for all practical purposes. So the lines aux.right = &no1; aux.left =...
java,c#,pointers,struct,pointer-arithmetic
I assume that the above struct is actually used to overlay (effectively) an array of bits as a byte array or an int array. You can't do that in Java. Your choices are: Model it as a byte array, and take the performance hit when you are doing indexed copying....
The problem is that your operator= only works on individual elements, not on whole vectors. You need to define a constructor that converts an A into a B. Then you can use std::vector::assign rather than std::vector::operator=. #include <iostream> #include <vector> using namespace std; struct A { int x, y; A():...
This: int buf_len = *buf; will not magically read sizeof buf_len (you seem to expect it to be four) bytes from buf, since *buf is a value of type char. You should use uint8_t rather than char, and uint32_t rather than int, and read as many as you need, respecting...
c,pointers,memory-management,struct
Code with comments: void f_alloc(ssm **a) { *a = malloc(sizeof(ssm)); // Need to allocate the structure and place in into the *a - i.e. hello in main (*a)->p = malloc(sizeof(int)); // Allocate memory for the integer pointer p (i.e. hello ->p; } EDIT I think this is what you are...
Remember what you have is array of pointers so when you exit the function the array is out of scope. Have a pointer to pointer for this purpose as shown below. correntista **max_prelievo(FILE *fcorrentisti, FILE *fprelievi){ correntista **corr_max = malloc(sizeof(correntista *) * 2); corr_max[0] = malloc(sizeof(correntista)); corr_max[1] = malloc(sizeof(correntista)); /*.........*/...
c++,class,templates,struct,nested
When the compiler first passes over Proletarian - before it sees an instantiation for a specific type T - it need help to know that T::NESTED will refer to some type, which you can give it using typename as follows: template <typename T> class Proletarian { public: typename T::NESTED* tn;...
c,function,struct,type-conversion,typedef
There is no defined behavior for casting a structure to any pointer type. Very likely your compiler would reject such a cast, but if it accepted it then the resulting behavior is unlikely to be useful. Moreover, you cannot pass a type (i.e. whatever) as a function argument. You could...
I think your function parameter definition is wrong. Try this: void add(char *AddName) { .... } ...
When hiding library detail from consuming clients, it is not uncommon to do what you described in your last paragraph. But you don't need to "ship the details" with your lib and public header. For example: mylib.h #ifndef MYLIB_H typedef struct Data Data; void Func(Data *data); #endif mylibint.h #ifndef MYLIB_H_INTERNAL...
c++,c++11,struct,unique-ptr,allegro
In your createBlock function you take World by value which means that it will be copied. However, you can't copy a unique_ptr so that is where your error comes from. This would also mean that setting the unqiue_ptr in the function wouldn't have any effect. Instead you should take World...
c,arrays,pointers,struct,typedef
In function CM_Init, you are setting cmPacket.Data to point to a local array: uint8_t emptyBuffer[CM_MAX_DATA_SIZE] = {0x00}; cmPacket.Data = emptyBuffer; Accessing this memory address outside the scope of the function yields undefined behavior....
It seems like a local array (on the stack, perhaps?) is being passed to push() from the code below. locArr[0] = l->xloc; locArr[1] = l->yloc; push(s, locArr); But push() is storing a pointer to the local stack in items, not a copy of the local array, so it could be...
If I add methods to this struct, probably the internal structure will be changed. That's wrong; to satisfy your needs what you want is to keep your structure a POD, for which essentially you don't want: non-trivial constructors/destructors/assignment operators; virtual functions or virtual base classes; different access specifiers for...
struct Test { public int test1; public int test2; } [DllImport("mydll", CallingConvention = Cdecl)] public static extern void FillStruct( Test[] stTest, int size); [...] var test = new Test[n]; FillStruct(test, test.Length); I don't see the problem here. It does not matter what you do with the memory in your c...
You are passing a struct to your process_file function. It is, however, expecting a pointer to a struct. Change this line: process_file(Total_poly); to this: process_file(&Total_poly); Additionally, you'll need to change the -> operators in the printf statements in the main function to . operators....
When you pass structure to function, compiler generates code to copy structure contents, so function gets its own copy of parameters that it can freely modify without affecting original. Copying is performed for sizeof struct bytes. Your main problem here is that your structure have flexible array member, so its...
edit You edited your question, now p is a pointer, not an array. Yes, and you can omit the parenthesis. Yes, but you must have called malloc to allocate memory for it before calling realloc. edit Or you could initialize hello->p to NULL, so that calling realloc(hello->p, someSize) will return...
c++,templates,struct,const,extern
This is one of the parts of the standard that changed from C++03 to C++11. In C++03, [temp.arg.nontype] reads: A template-argument for a non-type, non-template template-parameter shall be one of: [...] [...] the address of an object or function with external linkage, including function templates and function template-ids but excluding...
Inside your doStuff() function, myCoords is already a pointer. You can simply pass that pointer itself to calculateCoords() and calculateMotorSpeeds() function. Also, with a function prototype like void calculateCoords(struct coords* myCoords) calling calculateCoords(&myCoords); from doStuff() is wrong, as it is passing struct coords**. Solution: Keep your function signature for calculateCoords()...
c#,reflection,struct,attributes
you should use :var t = typeof(ItemTypes).GetFields().Where(k => k.IsLiteral == true);
You can change the condition to sum( x.Direction == 2 ) + 1 >= numel( x.Direction ) This should return true even if one of the elements is 1...
It's possible, but the proposed API isn't very nice. You're going to have to put iteration state somewhere, and you're not leaving any room for that. I would propose something like: struct DgIter { struct Dg *dg; size_t index; size_t dataSet; }; Then you can have functions like: struct DgIter...
c,arrays,multidimensional-array,struct
Each currentGeneration is a pointer to a Generation. Yet when you declare an array Generation generations[MAX_GENERATIONS] it expects each index to be a Generation, not a pointer to one. But when you declare the array as Generation *generations[MAX_GENERATIONS] it expects each index to be a pointer to a Generation, which...
c++,visual-c++,for-loop,struct
The problem here is that you are using the [] operator on a type. You declared lines as a struct. (It helps to keep to give your typenames a capital letter so you can differentiate them more easily.) I think you meant to call sub[i].text.
arrays,function,swift,struct,shuffle
"...that doesn`t seem to work..." is a variation on perhaps the least helpful thing you can say when asking for help. What do you mean it "doesn't seem to work"?!?!? How doesn't it work? Explain what it's doing that doesn't meet your needs. Is it crashing? Is the shuffledQuestions array...
ios,swift,struct,nsuserdefaults
I think you can use Dictionary. You'll need to make method to wrap data to struct and vice versa. For example: var users : [String: AnyObject]() users["name"] = "SomeName" users["stores"] = yourStoreArray NSUserDefaults.standardUserDefaults().setObject(users, forKey: "Users") something like that. And when you need to get struct if let myDictionaryFromUD = userDefaults.objectForKey("Users")...
c++,arrays,generics,struct,member-access
Also pointer to members are a possible solution; in combination with a template function, the members can be of different type. But, yes, the syntax is something strange: #include <iostream> #include <vector> using namespace std; /// calculate the sum of a given structure member in a vector: template <typename T,...
You can't refer to a value inside its own declaration. You need to initialize the value first, then you can assign the method you want to use to Handler. testAuth := &Authorization{ Username: "someusername", Password: "somepassword", } testAuth.Handler = testAuth.HandleFunc auths := Authorizations{ "test": testAuth, } ...
Given that category 3 is simply anything not in categories 1 or 2, we can figure out what elements belong in category 3 in a couple of ways. We can get the indices of categories 1 and 2 and remove them from the set of all indices, or we can...
c,pointers,struct,malloc,dynamic-memory-allocation
This worked (on C and C++). Since you originally included both tags. change *c =(struct student)malloc(sizeof(struct student)); to c =(struct student*) malloc(sizeof(struct student)); ...
Nest is embedded in Input. The JSON {"value1":"test", "value2":"Somevalue", "value3":"othervalue", "ID": "12345"} will be correctly marshalled into your Input. If you want to use the JSON body from your Question then you will have to change Input to the following type Input struct { Value1 string Value2 string Value3 string...
No that code does not make sense. The pin member is const so you can't assign to it except in the initializer. The pin member, is not a pointer so assgning malloc() to it is not going to compile correctly. I think you need to remove const from the struct...
In C++ the notion of the class is defined the following way class-specifier: class-head { member-specificationopt} where class-head in turn is defined like class-head: class-key attribute-specifier-seqopt class-head-name class-virt-specifieropt base-clauseopt class-key attribute-specifier-seqopt base-clauseopt where class-key: class struct union Thus a structure is class with class-key struct. And (C++Standard 12.1 Constructors) 4...
c++,performance,class,loops,struct
This is easy-peasy work for a modern optimizer to handle. As a programmer you might look at that constructor and struct and think it has to cost something. "The constructor code involves branching, passing arguments through registers/stack, popping from the stack, etc. The struct is a user-defined type, it must...
c,arrays,struct,initialization,static-array
If you want to initialize the array by zeroes then you can write simply move new_move = { 0 }; If you want that the structure array would contain values of array char new_board[10][10] then you have to copy its element in the structure array. for example char new_board[10][10] =...
c++,templates,c++11,struct,variadic-templates
Basically this problem reduces to just sorting a list of types based on a given comparator. Once you have that, everything else follows. So this answer is just the sorting part. We'll start with a typelist: template <typename...> struct typelist { using type = typelist; }; I'm going to assume...
Yes, head is a pointer to the pointer of your head node. So you can access ->prev by doing: (*head)->prev = newNode; Without the parentheses, the operator precedence rules of C parse your statement as *(head->prev) = newNode; which is not what you want....
c,arrays,struct,extern,static-array
Change extern my_struct* my_array; To extern my_struct my_array[]; You can't use extern to modify your array into a pointer....
(I'm going to answer this myself, based on what I've learned from others' contributions.) Short Answer In short, this is a GCC bug which is fixed by version 5.1: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119 Workaround for earlier versions This problem does not occur when assigning to non-nested structures (structures that contain only built-in types)....
If you allocate memory, this memory is not cleared. char *data = (char*)malloc(100); This does allocate memory for 100 characters. But the memory can contain random data. If you write from this address you can end up writing random data into the file. Clear the memory to make sure there...
c,pointers,struct,variable-assignment,c-strings
So yes, typical beginner's mistake. Thanks to @WhozCraig I figured I was doing this wrong. I shouldn't have dereferenced the pointer. I have so much to learn. Thanks for the help! //this works fine char * name = "John"; name = "Doe"; ...
In C language const object is not a constant. You cannot use it to declare a non-VLA array. Your first declaration is not compilable in C language, which makes it unclear what you mean by "functions fine". See here for more details: Shall I prefer constants over defines? In your...
I changed a little bit your code, but I think you should use linked list as a data structure here, it's more simple and consume less memory. I made some tries and all went ok. :) Hope that help you!! #include <stdio.h> #include <stdlib.h> #include <ctype.h> typedef struct Record Record;...
If you're working with bitfields, you should use unsigned int. signed int is a problem for bit-fields.
The reason you get EXC BAD ACCESS is because you never actually allocate memory for info. In your struct nodo you have info defined to be a pointer to a character, but you never have any memory allocated for it. Depending on how big your input could be you could...
You (understandably) misinterpreted the error message: 14:22 error: wrong number of lifetime parameters: expected 1, found 0 [E0107] src\lib.rs:14 value : & 'a Cell , You thought "But I provided the lifetime parameter! It is 'a!" However, the compiler is trying to tell you that you did not provide a...
VexCL does not support operations with vectors of structs out of the box. You will need to help it a bit. First, you need to tell VexCL how to spell the type name of the struct. Let's say you have the following struct defined on the host side: struct point2d...
c++,pointers,recursion,struct,allocation
I don't understand your algorithm, but I can tell where you are failing. switch (coord) { case 'N':{ room_ptr->south->north = NULL; room_ptr->south = NULL; } case 'S':{ room_ptr->north->south = NULL; // <-- Program Fails Here room_ptr->north = NULL; } room_ptr->north at this moment is a null pointer and you are...
c,arrays,pointers,struct,memcpy
If you transfer data to another (different) architecture, do not just pass a structure as a blob. That is the way to hell: endianess, alignment, padding bytes, etc. all can (and likely will) cause trouble. Better serialize the struct in a conforming way, possily using some interpreted control stream so...
c,arrays,parsing,file-io,struct
I won't be writing the code, but can try to help with the algotihm, in general. Open the file. Help : fopen() Check for successful opening. Hint: Return value. Read a line from the file. Check for the success. Help : fgets() and Return value. Based on data pattern ,...
A few suggestions: You have groupCount being incremented by the constructor function of the struct. This means you can only have one array of the struct that uses your array function. I would recommend having the array be responsible for managing the count. To that affect if you want to...
I think, (and as I can see) MD5_CTX is already a typedef to a struct. You don't need to write struct MD5_CTX context;. Change it to MD5_CTX context; and it should work....
You need to let the compiler know what struct student is, and that's nowhere in the code. The errors mean: invalid use of undefined type ‘struct student’: You're using an undefined type dereferencing pointer to incomplete type: You're dereferencing (accessing actual value / structure) of an incomplete type, since the...
Regarding structures: Vehicle.Info is a pointer, so you need to declare it as IntPtr Info, and then use Marshal.PtrToStructure / Marshal.StructureToPtr to read/write its value in managed code; Vehicle.something2 is a byte array, not a byte, so you need to declare it this way: [MarshalAs(UnmanagedType.ByValArray, SizeConst=20)] byte[] something2=new byte[20]; Vehicle.Data...
From the very bottom of this page from the Swift Reference: NOTE The description above refers to the “copying” of strings, arrays, and dictionaries. The behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes...
Whenever a method in a struct modifies one of its own properties, you have to use the mutating keyword. I believe that if you write: mutating func intializeAllDataPoints() { ... } it should work for you. This article gives a little more background information....
struct,go,interface,switch-statement
In your example you are trying to pass the struct itself to the function rather than an instance of the struct. When I ran your code it wouldn't compile. I agree with the comments above though, this would be much better handled by making sure each struct satisfies the fmt.Stringer...
As others mentioned, you're reading an uninitialized local variable and that's undefined. So, anything is legit. Having said that, there is a particular reason for this behavior: gcc reuses variables on the stack as much as it can (i.e., as long as the generated code is provably correct). You can...
First get the required permutation for sorting using sort and structfun. Then apply that permutation using orderfields: [~, I] = sort(structfun(@(x) x.age, P1)); P1 = orderfields(P1, I); ...