Search Results

Search found 2566 results on 103 pages for 'struct'.

Page 9/103 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Using unset member variables within a class or struct

    - by Doug Kavendek
    It's pretty nice to catch some really obvious errors when using unset local variables or when accessing a class or struct's members directly prior to initializing them. In visual studio 2008 you get an "uninitialized local variable used" warning at compile-time and get a run-time check failure at the point of access when debugging. However, if you access an uninitialized struct's member variable through one of its functions, you don't get any warnings or assertions. Obviously the easiest solution is don't do that, but nobody's perfect. For example: struct Test { float GetMember() const { return member; } float member; }; Test test; float f1 = test.member; // Raises warning, asserts in VS debugger at runtime float f2 = test.GetMember(); // No problem, just keeps on going This surprised me, but it makes some sense -- the compiler can't assume calling a function on an unused struct is an error, or how else would you initialize or construct it? And anything fancier just quickly brings up so many other complications that it makes sense that it wouldn't bother classifying which functions are ok to call and when, especially just as a debugging help. I know I can set up my own assertions or error checking within the class itself, but that can complicate some simpler structs. Still, it would seem like within the context of the function call, wouldn't it know insides GetMember() that member wasn't initialized yet? I'm assuming it's not only relying on static compile-time deduction, given the Run-Time Check Failure #3 it raises during execution, so based on my current understanding of it it would seem reasonable for the same checks to apply. Is this just a limitation of this specific compiler/debugger (Visual Studio 2008), or more tied to how C++ works?

    Read the article

  • Calling from C# to C function which accept a struct array allocated by caller

    - by lifey
    I have the following C struct struct XYZ { void *a; char fn[MAX_FN]; unsigned long l; unsigned long o; }; And I want to call the following function from C#: extern "C" int func(int handle, int *numEntries, XYZ *xyzTbl); Where xyzTbl is an array of XYZ of size numEntires which is allocated by the caller I have defined the following C# struct: [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] public struct XYZ { public System.IntPtr rva; [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 128)] public string fn; public uint l; public uint o; } and a method: [System.Runtime.InteropServices.DllImport(@"xyzdll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern Int32 func(Int32 handle, ref Int32 numntries, [MarshalAs(UnmanagedType.LPArray)] XYZ[] arr); Then I try to call the function : XYZ xyz = new XYZ[numEntries]; for (...) xyz[i] = new XYZ(); func(handle,numEntries,xyz); Of course it does not work. Can someone shed light on what I am doing wrong ?

    Read the article

  • Accessing a struct collection property from within another collection

    - by paddyb
    I have a struct that I need to store in a collection. The struct has a property that returns a Dictionary. public struct Item { private IDictionary<string, string> values; public IDictionary<string, string> Values { get { return this.values ?? (this.values = new Dictionary<string, string>()); } } } public class ItemCollection : Collection<Item> {} When testing I've found that if I add the item to the collection and then try to access the dictionary the structs values property is never updated. var collection = new ItemCollection { new Item() }; // pre-loaded with an item collection[0].Values.Add("myKey", "myValue"); Trace.WriteLine(collection[0].Values["myKey"]); // KeyNotFoundException here However if I load up the item first and then add it to a collection the values field is maintained. var collection = new ItemCollection(); var item = new Item(); item.Values.Add("myKey", "myValue"); collection.Add(item); Trace.WriteLine(collection[0].Values["myKey"]); // ok I've already decided that a struct is the wrong option for this type, and when using a class the issue doesn't occur, but I'm curious what's different between the two methods. Can anybody explain what's happening?

    Read the article

  • cocoa Expected specifier-qualifier-list before struct

    - by Circle
    I read the other posted solutions to using structs and resolving the "Expected specifier-qualifier-list before struct" related errors, but those aren't working. Is it different in Objective C? Do I need to declare my struct somewhere else in the class? It gives me the error on the line where I declare the typedef. Here is how it looks right now: @interface ClassA : NSObject { NSString *name; typedef struct _point { uint32_t x; uint64_t y; } Point; Point a; } @end

    Read the article

  • converting between struct and byte array

    - by chonch
    his question is about converting between a struct and a byte array. Many solutions are based around GCHandle.Alloc() and Marshal.StructureToPtr(). The problem is these calls generate garbage. For example, under Windows CE 6 R3 about 400 bytes of garbarge is made with a small structure. If the code below could be made to work the solution could be considered cleaner. It appears the sizeof() happens too late in the compile to work. public struct Data { public double a; public int b; public double c; } [StructLayout(LayoutKind.Explicit)] public unsafe struct DataWrapper { private static readonly int val = sizeof(Data); [FieldOffset(0)] public fixed byte Arr[val]; // "fixed" is to embed array instead of ref [FieldOffset(0)] public Data; // based on a C++ union }

    Read the article

  • Marshal struct to unmanaged array

    - by Pedro
    Hi guys, I have a C# struct to represent a cartesian vector, something like this: public struct Vector { private double x; private double y; private double z; //Some properties/methods } Now I have an unmanaged C dll that I need to call with P/Invoke. Some methods expect a double[3] parameter. The unmanaged C signature is something like void Cross(double a[3], double b[3], double c[3]); Is there any way to set up a P/Invoke signature so I can pass instances of my Vector struct and marshal them transparently to unmanaged double[3]? I would also need bidirectional marshaling as the unmanaged function needs to write the output to the argument array, so I guess I would need to marshal as LpArray. Any ideas? Thanks Pedro

    Read the article

  • struct method linking

    - by James
    I'm updating some old code that has several POD structs that were getting zero'd out by memset (don't blame me...I didn't write this part). Part of the update changed some of them to classes that use private internal pointers that are now getting wiped out by the memset. So I added a [non-virtual] reset() method to the various structs and refactored the code to call that instead. One particular struct developed an "undefined reference to `blah::reset()'" error. Changing it from a struct to a class fixed the error. Calling nm on the .o file h, the mangled function names for that method look the same (whether it's a class or a struct). I'm using g++ 4.4.1, on Ubuntu. I hate the thought that this might be a compiler/linker bug, but I'm not sure what else it could be. Am I missing some fundamental difference between structs and classes? I thought the only meaningful ones were the public/private defaults and the way everyone thinks about them.

    Read the article

  • Tuple struct constructor complains about private fields

    - by Grubermensch
    I am working on a basic shell interpreter to familiarize myself with Rust. While working on the table for storing suspended jobs in the shell, I have gotten stuck at the following compiler error message: tsh.rs:8:18: 8:31 error: cannot invoke tuple struct constructor with private fields tsh.rs:8 let mut jobs = job::JobsList(vec![]); ^~~~~~~~~~~~~ It's unclear to me what is being seen as private here. As you can see below, both of the structs are tagged with pub in my module file. So, what's the secret sauce? tsh.rs use std::io; mod job; fn main() { // Initialize jobs list let mut jobs = job::JobsList(vec![]); loop { /*** Shell runtime loop ***/ } } job.rs use std::fmt; pub struct Job { jid: int, pid: int, cmd: String } impl fmt::Show for Job { /*** Formatter ***/ } pub struct JobsList(Vec<Job>); impl fmt::Show for JobsList { /*** Formatter ***/ }

    Read the article

  • llvm clang struct creating functions on the fly

    - by anon
    I'm using LLVM-clang on Linux. Suppose in foo.cpp I have: struct Foo { int x, y; }; How can I create a function "magic" such that: typedef (Foo) SomeFunc(Foo a, Foo b); SomeFunc func = magic("struct Foo { int x, y; };"); so that: func(SomeFunc a, SomeFunc b); // returns a.x + b.y; ? Note: So basically, "magic" needs to take a char*, have LLVM parse it to get how C++ lays out the struct, then create a function on the fly that returns a.x + b.y; Thanks!

    Read the article

  • Boost multiindex complex struct

    - by StrifeLow
    In boost multiindex example complex_structs, it use one key in the car_manufacturer struct for car_table. If car_manufacturer have been modify to have 2 ID struct car_manufacturer { std::string name; int cm_code; car_manufacturer(const std::string& name_, const int& cm_code_):name(name_), cm_code(cm_code_){} }; What will be the key_from_key struct looks like? Have try to add another KeyExtractor or use composite index inside key_from_key, but still cannot compile. Please help on this. Thanks.

    Read the article

  • basic json > struct question

    - by danwoods
    I'm working with twitter's api, trying to get the json data from http://search.twitter.com/trends/current.json which looks like: {"as_of":1268069036,"trends":{"2010-03-08 17:23:56":[{"name":"Happy Women's Day","query":"\"Happy Women's Day\" OR \"Women's Day\""},{"name":"#MusicMonday","query":"#MusicMonday"},{"name":"#MM","query":"#MM"},{"name":"Oscars","query":"Oscars OR #oscars"},{"name":"#nooffense","query":"#nooffense"},{"name":"Hurt Locker","query":"\"Hurt Locker\""},{"name":"Justin Bieber","query":"\"Justin Bieber\""},{"name":"Cmon","query":"Cmon"},{"name":"My World 2","query":"\"My World 2\""},{"name":"Sandra Bullock","query":"\"Sandra Bullock\""}]}} My structs look like: type trend struct { name string query string } type trends struct { id string arr_of_trends []trend } type Trending struct { as_of string trends_obj trends } and then I parse the JSON into a variable of type Trending. I'm very new to JSON so my main concern is making sure I've have the data structure correctly setup to hold the returned json data. I'm writing this in 'Go' for a project for school. (This is not part of a particular assignment, just something I'm demo-ing for a presentation on the language)

    Read the article

  • Code crashing compiler: main() returning a struct instead of an int

    - by AndrejaKo
    Hi! I'm experimenting with a piece of C code. Can anyone tell me why is VC 9.0 with SP1 crashing for me? Oh, and the code is meant to be an example used in a discussion why something like void main (void) is evil. struct foo { int i; double d; } main (double argc, struct foo argv) { struct foo a; a.d=0; a.i=0; return a.i; } If I put return a; compiler doesn't crash.

    Read the article

  • Can C/C++ compiler report struct member offset

    - by Chen Jun
    Hello, everyone. I'd like to ask, can compiler(e.g. Visual C++) generate a report(.txt) telling struct member offset for a struct/all structs? If so, it helps debugging quite a lot. For example, when you read disassembler code in the debugger, it can be easier to associate an offset value to a struct member. Also, it is better to have compiler report offset of each local variable on a function stack frame(e.g. the offset relative to ebp on an X86 machine). Thank you in advance.

    Read the article

  • c struct map to ruby using SWIG

    - by pierr
    Hi, Is there any body can confirm the description here is true? My experience is that I can not use Example::Vector.new at all. C/C++ structs are wrapped as Ruby classes, with accessor methods (i.e. "getters" and "setters") for all of the struct members. For example, this struct declaration: struct Vector { double x, y; }; gets wrapped as a Vector class, with Ruby instance methods x, x=, y and y=. These methods can be used to access structure data from Ruby as follows: $ irb irb(main):001:0> require 'Example' true irb(main):002:0> f = Example::Vector.new #<Example::Vector:0x4020b268> irb(main):003:0> f.x = 10 nil irb(main):004:0> f.x 10.0

    Read the article

  • Allocating memory in char * struct

    - by mrblippy
    hi, im trying to read in a word from a user, then dynamically allocate memory for the word and store it in a struct array that contains a char *. i keep getting a implicit declaration of function âstrlenâ so i know im going wrong somewhere. struct class { char class_code[7]; char *name; }; char buffer[101]; struct unit units[1000]; scanf("%s", buffer); units[0].name = (char *) malloc(strlen(buffer)+1); strcpy(units[0].name, buffer);

    Read the article

  • Allocating memory for a char pointer that is part of a struct

    - by mrblippy
    hi, im trying to read in a word from a user, then dynamically allocate memory for the word and store it in a struct array that contains a char *. i keep getting a implicit declaration of function âstrlenâ so i know im going wrong somewhere. struct class { char class_code[4]; char *name; }; char buffer[101]; struct unit units[1000]; scanf("%s", buffer); units[0].name = (char *) malloc(strlen(buffer)+1); strcpy(units[0].name, buffer);

    Read the article

  • Memory error, access violation.

    - by Ordo
    Hello! I'm learning C on my own and as a exercise i have written a program but it does not work. The program is splitted into 3 parts. A header file, a main file for executing the program a file to define the functions. I'm not using all the functions yet but that shouldn't be the problem. Here is my header file, nothing special in it. #ifndef EMPLOYEE_H #define EMPLOYEE_H struct Employee { char first[21]; char last[21]; char title[21]; int salary; }; struct Employee* createEmployee(char*, char*, char*, int); // Creates a struct Employee object on the heap. char* getfirstname (struct Employee*); char* getlastname (struct Employee*); char* gettitle (struct Employee*); int getsalary (struct Employee*); void setfirstname (struct Employee*, char*); void setlastname (struct Employee*, char*); void settitle (struct Employee*, char*); void setsalary (struct Employee*, int); void printEmployee(struct Employee*); #endif In this file i define the functions and how they work: #include "7.1.h" #include <stdio.h> #include <stdlib.h> #include <string.h> struct Employee* createEmployee(char* first, char* last, char* title, int salary) // Creates a struct Employee object on the heap. { struct Employee* p = (struct Employee*) malloc(sizeof(struct Employee)); if (p != NULL) { strcpy(p->first, first); strcpy(p->last, last); strcpy(p->title, title); p->salary, salary; } return p; } char* getfirstname (struct Employee* p) { if (p != NULL) return p ? p->first : ""; } char* getlastname (struct Employee* p) { if (p != NULL) return p ? p->last : ""; } char* gettitle (struct Employee* p) { if (p != NULL) return p ? p->title : ""; } int getsalary (struct Employee* p) { if (p != NULL) return p ? p->salary : 0; } void setfirstname (struct Employee* p, char* first) { if (p != NULL) strcpy(p->first, first); } void setlastname (struct Employee* p, char* last) { if (p != NULL) strcpy(p->last, last); } void settitle (struct Employee* p, char* title) { if (p != NULL) strcpy(p->title, title); } void setsalary (struct Employee* p, char* salary) { if (p != NULL) p->salary, salary; } void printEmployee(struct Employee* p) { if (p != NULL) { printf("%s, %s, %s, %d", p->first, p->last, p->salary, p->salary ); } } And the last file is used to executed the program/functions: #include "7.1.h" #include <stdio.h> #include <stdlib.h> int main () { char decision; struct Employee emp; struct Employee* emps[3]; for ( int i = 0; i < 1; i ++) { printf("Please type in the emplooyes data.\nFirstname:"); scanf("%s", emp.first); printf("Lastname:"); scanf("%s", emp.last); printf("Title:"); scanf("%s", emp.title); printf("Salary:"); scanf("%d", &emp.salary); emps[i] = createEmployee(emp.first, emp.last, emp.title, emp.salary); } printf("Do you want to print out your information? (Y/N):"); scanf("%c", &decision); if (decision == 'y' || decision == 'Y') { printEmployee(emps[1]); } } I don't know what the problem is. I 'm always getting the following error message after typing in first, last, title and salary for the first time. The error is written in german. It means: Unhandled exception at 0x102de42e (msvcr100d.dll) in 7.1.exe: 0xC0000005: Access violation when writing to 0xCCCCCCCC position. I could fix the first problem with the hints given below. Now when i want to print out the employee data using the function:printEmployee(emps[1]);, I get the same kind of error with access violation.

    Read the article

  • Read from file into pointer to struct

    - by cla barzu
    I need help with pointers in C. I have to read from a file, and fill an array with pointers to struct rcftp_msg . Since now I did the next things: struct rcftp_msg { uint8_t version; uint8_t flags; uint16_t len; uint8_t buffer[512]; }; struct rcftp_msg *windows [10]; pfile = fopen(file,"r"); // Open the file I have to read from the file into the buffer, but I don't know how to do it. I tried the next: for (i = 0; i <10; i++){ leng=fread (**windows[i]->buffer**,sizeof(uint8_t),512,pfile); } I think windows[i]-buffer is bad, cuz that don't work. Sorry for my bad English :(

    Read the article

  • Array as struct database?

    - by user2985179
    I have a struct that reads data from the user: typedef struct { int seconds; } Time; typedef struct { Time time; double distance; } Training; Training input; scanf("%d %lf", input.time.seconds, input.distance); This scanf will be looped and the user can input different data every time, I want to store this data in an array for later use. I THINK I want something like arr[0].seconds and arr[0].distance. I tried to store the entered data in an array but it didn't really work at all... Training data[10]; data[10].seconds = input.time.seconds; data[10].distance = input.distance; The data will wipe when the program closes and that's how I like it to be. So I want it to be stored in an array, no files or databases!

    Read the article

  • InvalidCastException in DataGridView

    - by Max Yaffe
    (Using VS 2010 Beta 2 - .Net 4.0 B2 Rel) I have a class, MyTable, derived from BindingList where S is a struct. S is made up of several other structs, for example: public class MyTable<S>:BindingList<S> where S: struct { ... } public struct MyStruct { public MyReal r1; public MyReal r2; public MyReal R1 {get{...} set{...}} public MyReal R2 {get{...} set{...}} ... } public struct MyReal { private Double d; private void InitFromString(string) {this.d = ...;} public MyReal(Double d) { this.d = d;} public MyReal(string val) { this.d = default(Double); InitFromString(val);} public override string ToString() { return this.real.ToString();} public static explicit operator MyReal(string s) { return new MyReal(s);} public static implicit operator String(MyReal r) { return r.ToString();} ... } OK, I use the MyTable as a binding source for a DataGridView. I can load the data grid easily using InitFromString on individual fields in MyStruct. The problem comes when I try to edit a value in a cell of the DataGridView. Going to the first row, first column, I change the value of the existing number. It gives an exception blizzard, the first line of which says: System.FormatException: Invalid cast from 'System.String' to 'MyReal' I've looked at the casting discussions and reference books but don't see any obvious problems. Any ideas?

    Read the article

  • Why might stable_sort be affecting my hashtable values?

    - by zebraman
    I have defined a struct ABC to contain an int ID, string NAME, string LAST_NAME; My procedure is this: Read in a line from an input file. Parse each line into first name and last name and insert into the ABC struct. Also, the struct's ID is given by the number of the input line. Then, push_back the struct into a vector masterlist. I am also hashing these to a hashtable defined as vector< vector , using first name and last name as keywords. That is, If my data is: Garfield Cat Snoopy Dog Cat Man Then for the keyword cash hashes to a vector containing Garfield Cat and Cat Man. I insert the structs into the hashtable using push_back again. The problem is, when I call stable_sort on my masterlist, my hashtable is affected for some reason. I thought it might be happening since the songs are being ordered differently, so I tried making a copy of the masterlist and sorting it and it still affects the hashtable though the original masterlist is unaffected. Any ideas why this might be happening?

    Read the article

  • Returning a struct pointer

    - by idealistikz
    Suppose I have the following struct and function returning a pointer: typedef struct { int num; void *nums; int size; } Mystruct; Mystruct *mystruct(int num, int size) { .... } I want to define any Mystruct pointer using the above function. Should I declare a Mystruct variable, define the properties of Mystruct, assign a pointer to it, and return the pointer or define the properties of a mystruct property through a pointer immediately?

    Read the article

  • Why do I need an intermediate conversion to go from struct to decimal, but not struct to int?

    - by Jesse McGrew
    I have a struct like this, with an explicit conversion to float: struct TwFix32 { public static explicit operator float(TwFix32 x) { ... } } I can convert a TwFix32 to int with a single explicit cast: (int)fix32 But to convert it to decimal, I have to use two casts: (decimal)(float)fix32 There is no implicit conversion from float to either int or decimal. Why does the compiler let me omit the intermediate cast to float when I'm going to int, but not when I'm going to decimal?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >