Search Results

Search found 88 results on 4 pages for 'dereference'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Accessing structure elements using pointers

    - by Arun Nadesh
    Hi Everybody, Greetings! I got surprised when the following program did not crash. typedef struct _x{ int a; char b; int c; }x; main() { x *ptr=0; char *d=&ptr->b; } As per my understanding the -> operator has higher precedence over & operator. So I expected the program to crash at the below statement when we try to dereference the NULL pointer tr. char *d=&ptr->b; But the statement &ptr->b evaluates to a valid address. Could somebody please explain where I'm wrong? Thanks & Regards, Arun

    Read the article

  • C++: set of C-strings

    - by Nicholas
    I want to create one so that I could check whether a certain word is in the set using set::find However, C-strings are pointers, so the set would compare them by the pointer values by default. To function correctly, it would have to dereference them and compare the strings. I could just pass the constructor a pointer to the strcmp() function as a comparator, but this is not exactly how I want it to work. The word I might want to check could be part of a longer string, and I don't want to create a new string due to performance concerns. If there weren't for the set, I would use strncmp(a1, a2, 3) to check the first 3 letters. In fact, 3 is probably the longest it could go, so I'm fine with having the third argument constant. Is there a way to construct a set that would compare its elements by calling strncmp()? Code samples would be greatly appreciated.

    Read the article

  • Container of shared_ptr's but iterate with raw pointers

    - by Sean Lynch
    I have a class that holds a list containing boost::shared_ptrs to objects of another class. The class member functions that give access to the elemets in the list return raw pointers. For consistency I'd also like to be able to iterate with raw pointers instead of shared_ptrs. So when I dereference the list iterator, I'd like to get raw pointer, not a shared_ptr. I assume I need to write a custom iterator for this. Is this correct? If so can someone point me in the right direction - I've never done this before.

    Read the article

  • @Local annotation in EJB 3.

    - by stratwine
    Hi, I have a stateless session bean and a standalone-java-program acting as a client. The bean method executes just fine when the interface is marked @Remote. However,when I mark that interface with @Local instead of @Remote, I get the following Exception. [java] javax.naming.NamingException: Could not dereference object [Root exception is java.lang.RuntimeException: Could not find InvokerLocator URL at JNDIaddress "chapter1/HelloUserBean/local"; looking up local Proxy from Remote JVM?] But I expected even the latter to work, since it is the same computer that the code executes in. Seeing this behavior, I am assuming that, the Application-Server and the Standalone-Java-Program use different JVM instances and not a single JVM instance and so this client can access only through a remote interface. Is that assumption correct ? Thanks !

    Read the article

  • Basic help needed with pointers

    - by sbsp
    Hi, i asked some time ago on an account i cant remember how to manipulate basic pointers and someone gave me a really good demo for example char *ptr = hello (hello = a char array) so now *ptr is pointing at h ptr++ = moves the ptr to point at the next element, to get its value i do *ptr and that gives me e ok so far i hope :D but now i need to manipulate a char **ptr and was wondering how i do this in a way that mimmicks the effects of a 2d array? some basic tips would be much appreciated as i need to do an assignment that has a **ptr to immitate a 2d array and without knowing how it does this first means i cant even solve it on paper (for example, how do you dereference a **ptr, how do you get [x][y] values etc) thanks

    Read the article

  • C++ Pointer Issue

    - by Winder
    _stuckVertices is an array of pointers and I would like to update one index of that array without using _stuckVertices[ (row * _cols) + column ] 3 times. The reason it is an array of pointers is because the vast majority of the time the pointer will be NULL. The following code works but I need to dereference a each time I use it: void Cloth::stickPoint(int column, int row) { Anchor **a = &_stuckVertices[ (row * _cols) + column ]; if (!*a) *a = new Anchor(this, column, row); (*a)->stick(); } I originally had it written like this, but the _stuckVertices pointer doesn't get updated: void Cloth::stickPoint(int column, int row) { Anchor *a = _stuckVertices[ (row * _cols) + column ]; if (!a) a = new Anchor(this, column, row); a->stick(); } Is there a way to write Anchor *a = _stuckVertices[ index ] so that a is like an alias into the array that I can update, or is something like the first piece of code how I should do this? Thanks

    Read the article

  • passing Perl method results as a reference

    - by arareko
    Some XML::LibXML methods return arrays instead of references to arrays. Instead of doing this: $self->process_items($xml->findnodes('items/item')); I want to do something like: $self->process_items(\$xml->findnodes('items/item')); So that in process_items() I can dereference the original array instead of creating a copy: sub process_items { my ($self, $items) = @_; foreach my $item (@$items) { # do something... } } I can always store the results of findnodes() into an array and then pass the array reference to my own method, but let's say I want to try a reduced version of my code. Is that the correct syntax for passing the method results or should I use something different? Thanks!

    Read the article

  • Basic help needed with pointers (double indirection)

    - by sbsp
    Hi, i asked some time ago on an account i cant remember how to manipulate basic pointers and someone gave me a really good demo for example char *ptr = "hello" (hello = a char array) so now *ptr is pointing at h ptr++ = moves the ptr to point at the next element, to get its value i do *ptr and that gives me e ok so far i hope :D but now i need to manipulate a char **ptr and was wondering how I do this in a way that mimmicks the effects of a 2d array? some basic tips would be much appreciated as I need to do an assignment that has a **ptr to imitate a 2d array and without knowing how it does this first means I cant even solve it on paper (for example, how do you dereference a **ptr, how do you get [x][y] values etc) thanks

    Read the article

  • C pointer question, dereferencing crash

    - by skynorth
    Why do this work? int *var; while(scanf("%d", &var) && *var != 0) printf("%d \n", var); While this does not? int *var; while(scanf("%d", &var) && var != 0) printf("%d \n", var); Doesn't * (dereference operator) give you the value pointed by the pointer? So why does *var != 0 crash the program, while var != 0 does not?

    Read the article

  • Reading another packages symbol table in Perl

    - by justintime
    I am trying to read a global symbol from another package. I have the package name as a string. I am using qualify_to_ref from Symbol module my $ref = qualify_to_ref ( 'myarray', 'Mypackage' ) ; my @array = @$ref ; gives me Not an ARRAY reference at ...... I presume I am getting the format of the dereference wrong. Here is a complete example program. use strict; use Symbol ; package Mypackage ; our @myarray = qw/a b/ ; package main ; my $ref = qualify_to_ref ( 'myarray', 'Mypackage' ) ; my @array = @$ref ;

    Read the article

  • Are unspecified and undefined behavior required to be consistent between compiles?

    - by sharptooth
    Let's pretend my program contains a specific construct the C++ Standard states to be unspecified behavior. This basically means the implementation has to do something reasonable but is allowed not to document it. But is the implementation required to produce the same behavior every time it compiles a specific construct with unspecified behavior or is it allowed to produce different behavior in different compiles? What about undefined behavior? Let's pretend my program contains a construct that is UB according to the Standard. The implementation is allowed to exhibit any behavior. But can this behavior differ between compiles of the same program on the same compiler with same settings in the same environment? In other words, if I dereference a null pointer on line 78 in file X.cpp and the implementation formats the drive in such case does it mean that it will do the same after the program is recompiled?

    Read the article

  • Mathematica Programming Language&ndash;An Introduction

    - by JoshReuben
    The Mathematica http://www.wolfram.com/mathematica/ programming model consists of a kernel computation engine (or grid of such engines) and a front-end of notebook instances that communicate with the kernel throughout a session. The programming model of Mathematica is incredibly rich & powerful – besides numeric calculations, it supports symbols (eg Pi, I, E) and control flow logic.   obviously I could use this as a simple calculator: 5 * 10 --> 50 but this language is much more than that!   for example, I could use control flow logic & setup a simple infinite loop: x=1; While [x>0, x=x,x+1] Different brackets have different purposes: square brackets for function arguments:  Cos[x] round brackets for grouping: (1+2)*3 curly brackets for lists: {1,2,3,4} The power of Mathematica (as opposed to say Matlab) is that it gives exact symbolic answers instead of a rounded numeric approximation (unless you request it):   Mathematica lets you define scoped variables (symbols): a=1; b=2; c=a+b --> 5 these variables can contain symbolic values – you can think of these as partially computed functions:   use Clear[x] or Remove[x] to zero or dereference a variable.   To compute a numerical approximation to n significant digits (default n=6), use N[x,n] or the //N prefix: Pi //N -->3.14159 N[Pi,50] --> 3.1415926535897932384626433832795028841971693993751 The kernel uses % to reference the lastcalculation result, %% the 2nd last, %%% the 3rd last etc –> clearer statements: eg instead of: Sqrt[Pi+Sqrt[Sqrt[Pi+Sqrt[Pi]]] do: Sqrt[Pi]; Sqrt[Pi+%]; Sqrt[Pi+%] The help system supports wildcards, so I can search for functions like so: ?Inv* Mathematica supports some very powerful programming constructs and a rich function library that allow you to do things that you would have to write allot of code for in a language like C++.   the Factor function – factorization: Factor[x^3 – 6*x^2 +11x – 6] --> (-3+x) (-2+x) (-1+x)   the Solve function – find the roots of an equation: Solve[x^3 – 2x + 1 == 0] -->   the Expand function – express (1+x)^10 in polynomial form: Expand[(1+x)^10] --> 1+10x+45x^2+120x^3+210x^4+252x^5+210x^6+120x^7+45x^8+10x^9+x^10 the Prime function – what is the 1000th prime? Prime[1000] -->7919 Mathematica also has some powerful graphics capabilities:   the Plot function – plot the graph of y=Sin x in a single period: Plot[Sin[x], {x,0,2*Pi}] you can also plot 3D surfaces of functions using Plot3D function

    Read the article

  • Crash Report in Ubuntu... hardware problem?

    - by Andrew
    Got this on my machine. I was just browsing the web on Chrome and my computer froze. I recently just built this machine. I have a feeling it is a hardware problem... Possibly one of my parts arrived broken in some way.... Starting anac(h)ronistic cron Stopping anac(h)ronistic cron Stopping cold plug devices Stopping log initial device creation Starting enable remaining boot-time encrypted block devices Starting configure network device security Starting configure virtual network devices Starting save udev log and update rules Stopping configure virtual network devices Stopping save udev log and update rules Checking battery state... Stopping System V runlevel compatibility Stopping enable remaining boot-time encrypted block devices Stopping Mount filesystems on boot 91.573384] BUG: unable to handle kernel NULL pointer dereference at (null) 91.573437] IP: [<ffffffff81313514>] strcmp+0x14/0x30 91.573470] PGD 1f7822067 PUD 1ed7a6067 PMD 0 91.573498] Oops: 0000 [#1] SMP 91.573519] CPU 3 91.573531] Modules linked in: dm_crypt bnep snd_hda_codec_realtek rfcomm bluetooth parport_pc ppdev arc4 fglrx(P) rt2800usb rt2800lib crc_ccitt rt2x00usb rt2x00lib mac0021 cfg80211 psmouse snd_hda_intel snd_hda_codec snd_hwdep snd_pcm snd_seq_midi snd_rawmidi snd_seq_midi_event snd_seq snd_timer send_seq_device snd joydev mac_hid mei(C) soundcore serio_raw snd_page_alloc lp parport ses enclosure usbhid hid i915 drm_kms_helper drm i2c_algo_bit mxm_umi tg_video wmi usb_storage 91.573826] 91.573837] Pid: 2297, comm: update-notifier Tainted: P C O 3.2.0-29-generic #46-Ubuntu To Be Filled By O.E.M. To Be Filled By O.E.M./Z77 Extreme4 91.573912] RIP: 0010:[<ffffffff81313514>] [<ffffffff81313514>] strcmp+0x14/0x30 91.573954] RSP: 0018:ffff8801f83f5bb8 EFLAGS: 00010246 91.573982] RAX: 0000000000000000 RBX: 0000000000000000 RCX: 0000000000000000 91.574019] RDX: 0000000000000069 RSI: 0000000000000000 RDI: ffff88021adb26f8 91.574056] RBP: ffff8801f83f5bb8 R08: ffff88022f2d6e80 R09: 0000000000000000 91.574093] R10: ffff88021e7dbf00 R11: 0000000000000003 R12: ffff88021c10eb40 91.574130] R13: 0000000000000000 R14: ffff88021adb26f8 R15: ffff8801f83f5d40 91.574168] FS: 00007f958cf53940(0000) GS:ffff88022f2c0000(0000) kn1GS:0000000000000000 91.574210] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 91.574240] CR2: 0000000000000000 CR3: 000000021f6d7000 CR4: 00000000000406e0 91.574277] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 91.574314] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000000 91.574351] Process update-notifier (pid: 2297, threadinfo ffff801f83f4000, task ffff880208fe2e00) 91.574397] Stack: 91.574409] ffff8801f83f5be8 ffffffff811ed509 ffff88021adb26c0 ffff88021b8b7020 91.574453] ffff88021b461c60 fffffffffffffffe ffff8801f83f5c18 ffffffff811ed61f 91.574496] ffff88021adb26c0 ffff88021b8b7020 ffff8801f83f5dc8 0000000000000001 91.574539] Call Trace: 91.574558] [<ffffffff811ed509] sysfs_find_dirent+0x59/0x110 91.574591] [<ffffffff811ed61f] sysfs_lookup+0x5f/0x110 91.574621] [<ffffffff81182745] d_alloc_and_lookup+0x45/0x90 91.574654] [<ffffffff8118fe65] ? d_lookup+0x35/0x60 91.574683] [<ffffffff811848d2] do_lookup+0x202/0x310 91.574712] [<ffffffff8118660c] path_lookupat+0x11c/0x750 91.574744] [<ffffffff81318db7] ? __strncpy_from_user+0x27/0x60 91.574778] [<ffffffff81186c71] do_path_lookup+0x31/0xc0 91.574809] [<ffffffff81187779] user_path_at_empty+0x59/0xa0 91.574842] [<ffffffff81187822] ? do_filp_open+0x42/0xa0 91.574872] [<ffffffff811877d1] user_path_at+0x11/0x20 91.574902] [<ffffffff8117c80a] vfs_fstatat+0x3a/0x70 91.574933] [<ffffffff81161cff] ? kmem_cache_free+0x2f/0x110 91.574965] [<ffffffff8117c85e] vfs_lstat+-x31/0x70 91.574993] [<ffffffff8117c9fa] sys_newlstat+0x1a/0x40 91.575022] [<ffffffff81176ee1] ? do_sys_open+0x171/0x220 91.575053] [<ffffffff8117cb1a] ? sys_readlinkat+0x7a/0xb0 91.575086] [<ffffffff81661ec2] system_call_fastpath+0x16/0x1b 91.575118] Code: 83 c1 01 40 84 ff 75 ef 5d c3 66 66 66 66 2e 0f 1f 84 00 00 00 00 00 00 55 31 c0 48 89 e5 66 2e 0f 1f 84 00 00 00 00 00 0f b6 14 07 <3a> 14 06 75 0f 48 83 c0 01 84 d2 75 ef 31 c0 5d c3 0f 1f 00 19 91.577243] RIP [<ffffffff81313514>] strcmp+0x14/0x30 91.579314] RSP <ffff8801f83f5bb8> 91.581385] CR2: 0000000000000000

    Read the article

  • What are the disadvantages of self-encapsulation?

    - by Dave Jarvis
    Background Tony Hoare's billion dollar mistake was the invention of null. Subsequently, a lot of code has become riddled with null pointer exceptions (segfaults) when software developers try to use (dereference) uninitialized variables. In 1989, Wirfs-Brock and Wikerson wrote: Direct references to variables severely limit the ability of programmers to re?ne existing classes. The programming conventions described here structure the use of variables to promote reusable designs. We encourage users of all object-oriented languages to follow these conventions. Additionally, we strongly urge designers of object-oriented languages to consider the effects of unrestricted variable references on reusability. Problem A lot of software, especially in Java, but likely in C# and C++, often uses the following pattern: public class SomeClass { private String someAttribute; public SomeClass() { this.someAttribute = "Some Value"; } public void someMethod() { if( this.someAttribute.equals( "Some Value" ) ) { // do something... } } public void setAttribute( String s ) { this.someAttribute = s; } public String getAttribute() { return this.someAttribute; } } Sometimes a band-aid solution is used by checking for null throughout the code base: public void someMethod() { assert this.someAttribute != null; if( this.someAttribute.equals( "Some Value" ) ) { // do something... } } public void anotherMethod() { assert this.someAttribute != null; if( this.someAttribute.equals( "Some Default Value" ) ) { // do something... } } The band-aid does not always avoid the null pointer problem: a race condition exists. The race condition is mitigated using: public void anotherMethod() { String someAttribute = this.someAttribute; assert someAttribute != null; if( someAttribute.equals( "Some Default Value" ) ) { // do something... } } Yet that requires two statements (assignment to local copy and check for null) every time a class-scoped variable is used to ensure it is valid. Self-Encapsulation Ken Auer's Reusability Through Self-Encapsulation (Pattern Languages of Program Design, Addison Wesley, New York, pp. 505-516, 1994) advocated self-encapsulation combined with lazy initialization. The result, in Java, would resemble: public class SomeClass { private String someAttribute; public SomeClass() { setAttribute( "Some Value" ); } public void someMethod() { if( getAttribute().equals( "Some Value" ) ) { // do something... } } public void setAttribute( String s ) { this.someAttribute = s; } public String getAttribute() { String someAttribute = this.someAttribute; if( someAttribute == null ) { setAttribute( createDefaultValue() ); } return someAttribute; } protected String createDefaultValue() { return "Some Default Value"; } } All duplicate checks for null are superfluous: getAttribute() ensures the value is never null at a single location within the containing class. Efficiency arguments should be fairly moot -- modern compilers and virtual machines can inline the code when possible. As long as variables are never referenced directly, this also allows for proper application of the Open-Closed Principle. Question What are the disadvantages of self-encapsulation, if any? (Ideally, I would like to see references to studies that contrast the robustness of similarly complex systems that use and don't use self-encapsulation, as this strikes me as a fairly straightforward testable hypothesis.)

    Read the article

  • Generating %pc relative address of constant data

    - by Hudson
    Is there a way to have gcc generate %pc relative addresses of constants? Even when the string appears in the text segment, arm-elf-gcc will generate a constant pointer to the data, load the address of the pointer via a %pc relative address and then dereference it. For a variety of reasons, I need to skip the middle step. As an example, this simple function: const char * filename(void) { static const char _filename[] __attribute__((section(".text"))) = "logfile"; return _filename; } generates (when compiled with arm-elf-gcc-4.3.2 -nostdlib -c -O3 -W -Wall logfile.c): 00000000 <filename>: 0: e59f0000 ldr r0, [pc, #0] ; 8 <filename+0x8> 4: e12fff1e bx lr 8: 0000000c .word 0x0000000c 0000000c <_filename.1175>: c: 66676f6c .word 0x66676f6c 10: 00656c69 .word 0x00656c69 I would have expected it to generate something more like: filename: add r0, pc, #0 bx lr _filename.1175: .ascii "logfile\000" The code in question needs to be partially position independent since it will be relocated in memory at load time, but also integrate with code that was not compiled -fPIC, so there is no global offset table. My current work around is to call a non-inline function (which will be done via a %pc relative address) to find the offset from the compiled location in a technique similar to how -fPIC code works: static intptr_t __attribute__((noinline)) find_offset( void ) { uintptr_t pc; asm __volatile__ ( "mov %0, %%pc" : "=&r"(pc) ); return pc - 8 - (uintptr_t) find_offset; } But this technique requires that all data references be fixed up manually, so the filename() function in the above example would become: const char * filename(void) { static const char _filename[] __attribute__((section(".text"))) = "logfile"; return _filename + find_offset(); }

    Read the article

  • Can I use boost::make_shared with a private constructor?

    - by Billy ONeal
    Consider the following: class DirectoryIterator; namespace detail { class FileDataProxy; class DirectoryIteratorImpl { friend class DirectoryIterator; friend class FileDataProxy; WIN32_FIND_DATAW currentData; HANDLE hFind; std::wstring root; DirectoryIteratorImpl(); explicit DirectoryIteratorImpl(const std::wstring& pathSpec); void increment(); public: ~DirectoryIteratorImpl() {}; }; class FileDataProxy //Serves as a proxy to the WIN32_FIND_DATA struture inside the iterator. { friend class DirectoryIterator; boost::shared_ptr<DirectoryIteratorImpl> iteratorSource; FileDataProxy(boost::shared_ptr<DirectoryIteratorImpl> parent) : iteratorSource(parent) {}; public: std::wstring GetFolderPath() const { return iteratorSource->root; } }; } class DirectoryIterator : public boost::iterator_facade<DirectoryIterator, detail::FileDataProxy, std::input_iterator_tag> { friend class boost::iterator_core_access; boost::shared_ptr<detail::DirectoryIteratorImpl> impl; void increment() { impl->increment(); }; detail::FileDataProxy dereference() const { return detail::FileDataProxy(impl); }; public: DirectoryIterator() { impl = boost::make_shared<detail::DirectoryIteratorImpl>(); }; }; It seems like DirectoryIterator should be able to call boost::make_shared<DirectoryIteratorImpl>, because it is a friend of DirectoryIteratorImpl. However, this code fails to compile because the constructor for DirectoryIteratorImpl is private. Since this class is an internal implementation detail that clients of DirectoryIterator should never touch, it would be nice if I could keep the constructor private. Is this my fundamental misunderstanding around make_shared or do I need to mark some sort of boost piece as friend in order for the call to compile?

    Read the article

  • Nested dereferencing arrows in Perl: to omit or not to omit?

    - by DVK
    In Perl, when you have a nested data structure, it is permissible to omit de-referencing arrows to 2d and more level of nesting. In other words, the following two syntaxes are identical: my $hash_ref = { 1 => [ 11, 12, 13 ], 3 => [31, 32] }; my $elem1 = $hash_ref->{1}->[1]; my $elem2 = $hash_ref->{1}[1]; # exactly the same as above Now, my question is, is there a good reason to choose one style over the other? It seems to be a popular bone of stylistic contention (Just on SO, I accidentally bumped into this and this in the space of 5 minutes). So far, none of the usual suspects says anything definitive: perldoc merely says "you are free to omit the pointer dereferencing arrow". Conway's "Perl Best Practices" says "whenever possible, dereference with arrows", but it appears to only apply to the context of dereferencing the main reference, not optional arrows on 2d level of nested data structures. "MAstering Perl for Bioinfirmatics" author James Tisdall doesn't give very solid preference either: "The sharp-witted reader may have noticed that we seem to be omitting arrow operators between array subscripts. (After all, these are anonymous arrays of anonymous arrays of anonymous arrays, etc., so shouldn't they be written [$array-[$i]-[$j]-[$k]?) Perl allows this; only the arrow operator between the variable name and the first array subscript is required. It make things easier on the eyes and helps avoid carpal tunnel syndrome. On the other hand, you may prefer to keep the dereferencing arrows in place, to make it clear you are dealing with references. Your choice." Personally, i'm on the side of "always put arrows in, since itg's more readable and obvious tiy're dealing with a reference".

    Read the article

  • Trying to parse OpenCV YAML ouput with yaml-cpp

    - by Kenn Sebesta
    I've got a series of OpenCv generated YAML files and would like to parse them with yaml-cpp I'm doing okay on simple stuff, but the matrix representation is proving difficult. # Center of table tableCenter: !!opencv-matrix rows: 1 cols: 2 dt: f data: [ 240, 240] This should map into the vector 240 240 with type float. My code looks like: #include "yaml.h" #include <fstream> #include <string> struct Matrix { int x; }; void operator >> (const YAML::Node& node, Matrix& matrix) { unsigned rows; node["rows"] >> rows; } int main() { std::ifstream fin("monsters.yaml"); YAML::Parser parser(fin); YAML::Node doc; Matrix m; doc["tableCenter"] >> m; return 0; } But I get terminate called after throwing an instance of 'YAML::BadDereference' what(): yaml-cpp: error at line 0, column 0: bad dereference Abort trap I searched around for some documentation for yaml-cpp, but there doesn't seem to be any, aside from a short introductory example on parsing and emitting. Unfortunately, neither of these two help in this particular circumstance. As I understand, the !! indicate that this is a user-defined type, but I don't see with yaml-cpp how to parse that.

    Read the article

  • Official names for pointer operators

    - by FredOverflow
    What are the official names for the operators * and & in the context of pointers? They seem to be frequently called dereference operator and address-of operator respectively, but unfortunately, the section on unary operators in the standard does not name them. I really don't want to name & address-of anymore, because & returns a pointer, not an address. (A pointer is a language mechanism, while an address is an implementation detail. Addresses are untyped, while pointers aren't, except for void*.) The standard is very clear about this: The result of the unary & operator is a pointer to its operand. Symmetry suggests to name & reference operator which is a little unfortunate because of the collision with references in C++. The fact that & returns a pointer suggests pointer operator. Are there any official sources that would confirm these (or other) namings?

    Read the article

  • Loop through XML::Simple structure

    - by David
    So I have some xml file like this: <?xml version="1.0" encoding="ISO-8859-1"?> <root result="0" > <settings user="anonymous" > <s n="blabla1" > <v>true</v> </s> <s n="blabla2" > <v>false</v> </s> <s n="blabla3" > <v>true</v> </s> </settings> </root> I want to go through all the settings using the XML Simple. Here's what I have when I print the output with Data::Dumper: $VAR1 = { 'settings' => { 'user' => 'anonymous', 's' => [ { 'n' => 'blabla1', 'v' => 'true' }, { 'n' => 'blabla2', 'v' => 'false' }, { 'n' => 'blabla3', 'v' => 'true' } ] }, 'result' => '0' }; And here's my code $xml = new XML::Simple; $data = $xml->XMLin($file); foreach $s (keys %{ $data->{'settings'}->{'s'} }) { print "TEST: $s $data->{'settings'}->{'s'}->[$s]->{'n'} $data->{'settings'}->{'s'}->[$s]->{'v'}<br>\n"; } And it returns these 2 lines, without looping: TEST: n blabla1 true TEST: v blabla1 true I also tried to do something like this: foreach $s (keys %{ $data->{'settings'}->{'s'} }) { Without any success: Type of arg 1 to keys must be hash (not array dereference) How can I procede? What am I doing wrong? Thanks a lot!

    Read the article

  • Output iterator's value_type

    - by wilhelmtell
    The STL commonly defines an output iterator like so: template<class Cont> class insert_iterator : public iterator<output_iterator_tag,void,void,void,void> { // ... Why do output iterators define value_type as void? It would be useful for an algorithm to know what type of value it is supposed to output. For example, a function that translates a URL query "key1=value1&key2=value2&key3=value3" into any container that holds key-value strings elements. template<typename Ch,typename Tr,typename Out> void parse(const std::basic_string<Ch,Tr>& str, Out result) { std::basic_string<Ch,Tr> key, value; // loop over str, parse into p ... *result = typename iterator_traits<Out>::value_type(key, value); } The SGI reference page of value_type hints this is because it's not possible to dereference an output iterator. But that's not the only use of value_type: I might want to instantiate one in order to assign it to the iterator.

    Read the article

  • How do I repass a function pointer in C++

    - by fneep
    Firstly, I am very new to function pointers and their horrible syntax so play nice. I am writing a method to filter all pixels in my bitmap based on a function that I pass in. I have written the method to dereference it and call it in the pixel buffer but I also need a wrapper method in my bitmap class that takes the function pointer and passes it on. How do I do it? What is the syntax? I'm a little stumped. Here is my code with all the irrelevant bits stripped out and files combined (read all variables initialized filled etc.). struct sColour { unsigned char r, g, b, a; }; class cPixelBuffer { private: sColour* _pixels; int _width; int _height; int _buffersize; public: void FilterAll(sColour (*FilterFunc)(sColour)); }; void cPixelBuffer::FilterAll(sColour (*FilterFunc)(sColour)) { // fast fast fast hacky FAST for (int i = 0; i < _buffersize; i++) { _pixels[i] = (*FilterFunc)(_pixels[i]); } } class cBitmap { private: cPixelBuffer* _pixels; public: inline void cBitmap::Filter(sColour (*FilterFunc)(sColour)) { //HERE!! } };

    Read the article

  • Is it possible to store pointers in shared memory without using offsets?

    - by Joseph Garvin
    When using shared memory, each process may mmap the shared region into a different area of their address space. This means that when storing pointers within the shared region, you need to store them as offsets of the start of the shared region. Unfortunately, this complicates use of atomic instructions (e.g. if you're trying to write a lock free algorithm). For example, say you have a bunch of reference counted nodes in shared memory, created by a single writer. The writer periodically atomically updates a pointer 'p' to point to a valid node with positive reference count. Readers want to atomically write to 'p' because it points to the beginning of a node (a struct) whose first element is a reference count. Since p always points to a valid node, incrementing the ref count is safe, and makes it safe to dereference 'p' and access other members. However, this all only works when everything is in the same address space. If the nodes and the 'p' pointer are stored in shared memory, then clients suffer a race condition: x = read p y = x + offset Increment refcount at y During step 2, p may change and x may no longer point to a valid node. The only workaround I can think of is somehow forcing all processes to agree on where to map the shared memory, so that real pointers rather than offsets can be stored in the mmap'd region. Is there any way to do that? I see MAP_FIXED in the mmap documentation, but I don't know how I could pick an address that would be safe.

    Read the article

  • Handles Comparison: empty classes vs. undefined classes vs. void*

    - by Nawaz
    Microsoft's GDI+ defines many empty classes to be treated as handles internally. For example, (source GdiPlusGpStubs.h) //Approach 1 class GpGraphics {}; class GpBrush {}; class GpTexture : public GpBrush {}; class GpSolidFill : public GpBrush {}; class GpLineGradient : public GpBrush {}; class GpPathGradient : public GpBrush {}; class GpHatch : public GpBrush {}; class GpPen {}; class GpCustomLineCap {}; There are other two ways to define handles. They're, //Approach 2 class BOOK; //no need to define it! typedef BOOK *PBOOK; typedef PBOOK HBOOK; //handle to be used internally //Approach 3 typedef void* PVOID; typedef PVOID HBOOK; //handle to be used internally I just want to know the advantages and disadvantages of each of these approaches. One advantage with Microsoft's approach is that, they can define type-safe hierarchy of handles using empty classes, which (I think) is not possible with the other two approaches. What else? EDIT: One advantage with the second approach (i.e using incomplete classes) is that we can prevent clients from dereferencing the handles (that means, this approach appears to support encapsulation strongly, I suppose). The code would not even compile if one attempts to dereference handles. What else?

    Read the article

  • Is there a practical benefit to casting a NULL pointer to an object and calling one of its member fu

    - by zdawg
    Ok, so I know that technically this is undefined behavior, but nonetheless, I've seen this more than once in production code. And please correct me if I'm wrong, but I've also heard that some people use this "feature" as a somewhat legitimate substitute of a lacking aspect of the current C++ standard, namely, the inability to obtain the address (well, offset really) of a member function. For example, this is out of a popular implementation of a PCRE (Perl-compatible Regular Expression) library: #ifndef offsetof #define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field)) #endif One can debate whether the exploitation of such a language subtlety in a case like this is valid or not, or even necessary, but I've also seen it used like this: struct Result { void stat() { if(this) // do something... else // do something else... } }; // ...somewhere else in the code... ((Result*)0)->stat(); This works just fine! It avoids a null pointer dereference by testing for the existence of this, and it does not try to access class members in the else block. So long as these guards are in place, it's legitimate code, right? So the question remains: Is there a practical use case, where one would benefit from using such a construct? I'm especially concerned about the second case, since the first case is more of a workaround for a language limitation. Or is it? PS. Sorry about the C-style casts, unfortunately people still prefer to type less if they can.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >