Search Results

Search found 3255 results on 131 pages for 'pointers'.

Page 2/131 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Copying pointers in C++

    - by tunnuz
    Hello, I have a class A containing two pointers to objects of another class B. I want to initialize one pointer or the other depending on which one is passed to init(), which also takes other parameters. My situation is thus the following: class A { public: A(); init(int parameter, int otherParameter, B* toBeInitialized); protected: B* myB; B* myOtherB; }; Now my point is that I want to call init() as: init(640, 480, this->myB); or init(640, 480, this->myOtherB); Now, my init is implemented as: void init( int parameter, int otherParameter, B* toBeInitialized ) { toBeInitialized = someConstructorFunction(parameter, otherParameter); } The problem is that the two pointers are not initialized, I suspect that toBeInitialized is overwritten, but the original parameter is not modified. I am doing something wrong? Should I use references to pointers? Thank you Tommaso

    Read the article

  • How to use shared_ptr for COM interface pointers

    - by Seefer
    I've been reading about various usage advice relating to the new c++ standard smart pointers unique_ptr, shared_ptr and weak_ptr and generally 'grok' what they are about when I'm writing my own code that declares and consumes them. However, all the discussions I've read seem restricted to this simple usage situation where the programmer is using smart in his/her own code, with no real discussion on techniques when having to work with libraries that expect raw pointers or other types of 'smart pointers' such as COM interface pointers. Specifically I'm learning my way through C++ by attempting to get a standard Win32 real-time game loop up and running that uses Direct2D & DirectWrite to render text to the display showing frames per second. My first task with Direct2D is in creating a Direct2D Factory object with the following code from the Direct2D examples on MSDN: ID2D1Factory* pD2DFactory = nullptr; HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pD2DFactory); pD2DFactory is obviously an 'out' parameter and it's here where I become uncertain how to make use of smart pointers in this context, if indeed it's possible. My inexperienced C++ mind tells me I have two problems: With pD2DFactory being a COM interface pointer type, how would smart_ptr work with the Add() / Release() member functions for a COM object instance? Are smart pointers able to be passed to functions in situations where the function is using an 'out' pointer parameter technique? I did experiment with the alternative of using _com_ptr_t in the comip.h header file to help with pointer lifetime management and declared the pD2DFactory pointer with the following code: _com_ptr_t<_com_IIID<pD2DFactory, &__uuidof(pD2DFactory)>> pD2DFactory = nullptr; and it appears to work so far but, as you can see, the syntax is cumbersome :) So, I was wondering if any C++ gurus here could confirm whether smart pointers are able to help in cases like this and provide examples of usage, or point me to more in-depth discussions of smart pointer usage when needing to work with other code libraries that know nothing of them. Or is it simply a case of my trying to use the wrong tool for the job? :)

    Read the article

  • boost::serialization of mutual pointers

    - by KneLL
    First, please take a look at these code: class Key; class Door; class Key { public: int id; Door *pDoor; Key() : id(0), pDoor(NULL) {} private: friend class boost::serialization::access; template <typename A> void serialize(A &ar, const unsigned int ver) { ar & BOOST_SERIALIZATION_NVP(id) & BOOST_SERIALIZATION_NVP(pDoor); } }; class Door { public: int id; Key *pKey; Door() : id(0), pKey(NULL) {} private: friend class boost::serialization::access; template <typename A> void serialize(A &ar, const unsigned int ver) { ar & BOOST_SERIALIZATION_NVP(id) & BOOST_SERIALIZATION_NVP(pKey); } }; BOOST_CLASS_TRACKING(Key, track_selectively); BOOST_CLASS_TRACKING(Door, track_selectively); int main() { Key k1, k_in; Door d1, d_in; k1.id = 1; d1.id = 2; k1.pDoor = &d1; d1.pKey = &k1; // Save data { wofstream f1("test.xml"); boost::archive::xml_woarchive ar1(f1); // !!!!! (1) const Key *pK = &k1; const Door *pD = &d1; ar1 << BOOST_SERIALIZATION_NVP(pK) << BOOST_SERIALIZATION_NVP(pD); } // Load data { wifstream i1("test.xml"); boost::archive::xml_wiarchive ar1(i1); // !!!!! (2) A *pK = &k_in; B *pD = &d_in; // (2.1) //ar1 >> BOOST_SERIALIZATION_NVP(k_in) >> BOOST_SERIALIZATION_NVP(d_in); // (2.2) ar1 >> BOOST_SERIALIZATION_NVP(pK) >> BOOST_SERIALIZATION_NVP(pD); } } The first (1) is a simple question - is it possible to pass objects to archive without pointers? If simply pass objects 'as is' that boost throws exception about duplicated pointers. But I'm confused of creating pointers to save objects. The second (2) is a real trouble. If comment out string after (2.1) then boost will corectly load a first Key object (and init internal Door pointer pDoor), but will not init a second Door (d_in) object. After this I have an inited *k_in* object with valid pointer to Door and empty *d_in* object. If use string (2.2) then boost will create two Key and Door objects somewhere in memory and save addresses in pointers. But I want to have two objects *k_in* and *d_in*. So, if I copy a values of memory objects to local variables then I store only addresses, for example, I can write code after (2.2): d_in.id = pD->id; d_in.pKey = pD->pKey; But in this case I store only a pointer and memory object remains in memory and I cannot delete it, because *d_in.pKey* will be unvalid. And I cannot perform a deep copy with operator=(), because if I write code like this: Key &operator==(const Key &k) { if (this != &k) { id = k.id; // call to Door::operator=() that calls *pKey = *d.pKey and so on *pDoor = *k.pDoor; } return *this; } then I will get a something like recursion of operator=()s of Key and Door. How to implement proper serialization of such pointers?

    Read the article

  • Declaration, allocation and assignment of an array of pointers to function pointers

    - by manneorama
    Hello Stack Overflow! This is my first post, so please be gentle. I've been playing around with C from time to time in the past. Now I've gotten to the point where I've started a real project (a 2D graphics engine using SDL, but that's irrelevant for the question), to be able to say that I have some real C experience. Yesterday, while working on the event system, I ran into a problem which I couldn't solve. There's this typedef, //the void parameter is really an SDL_Event*. //but that is irrelevant for this question. typedef void (*event_callback)(void); which specifies the signature of a function to be called on engine events. I want to be able to support multiple event_callbacks, so an array of these callbacks would be an idea, but do not want to limit the amount of callbacks, so I need some sort of dynamic allocation. This is where the problem arose. My first attempt went like this: //initial size of callback vector static const int initial_vecsize = 32; //our event callback vector static event_callback* vec = 0; //size static unsigned int vecsize = 0; void register_event_callback(event_callback func) { if (!vec) __engine_allocate_vec(vec); vec[vecsize++] = func; //error here! } static void __engine_allocate_vec(engine_callback* vec) { vec = (engine_callback*) malloc(sizeof(engine_callback*) * initial_vecsize); } First of all, I have omitted some error checking as well as the code that reallocates the callback vector when the number of callbacks exceed the vector size. However, when I run this code, the program crashes as described in the code. I'm guessing segmentation fault but I can't be sure since no output is given. I'm also guessing that the error comes from a somewhat flawed understanding on how to declare and allocate an array of pointers to function pointers. Please Stack Overflow, guide me.

    Read the article

  • C++ arithmetic with pointers

    - by user69514
    I am trying to add the following: I have an array of double pointers call A. I have another array of double pointers call it B, and I have an unsigned int call it C. So I want to do: A[i] = B[i] - C; how do I do it? I did: A[i] = &B[i] - C; I don't think I am doing this correctly.

    Read the article

  • Getting my head around the practical applications of strong and weak pointers in Objective-C

    - by Chris Wilson
    I've just read the accepted excellent answer to this question that clarifies the conceptual differences between strong and weak pointers in Objective-C, and I'm still trying to understand the practical differences. I come from a C++ background where these concepts don't exist, and I'm having trouble figuring out where I would use one vs the other. Could someone please provide a practical example, using Objective-C code, that illustrates the different uses of strong and weak pointers?

    Read the article

  • Why no switch on pointers?

    - by meeselet
    For instance: #include <stdio.h> void why_cant_we_switch_him(void *ptr) { switch (ptr) { case NULL: printf("NULL!\n"); break; default: printf("%p!\n", ptr); break; } } int main(void) { void *foo = "toast"; why_cant_we_switch_him(foo); return 0; } gcc test.c -o test test.c: In function 'why_cant_we_switch_him': test.c:5: error: switch quantity not an integer test.c:6: error: pointers are not permitted as case values Just curious. Is this a technical limitation? EDIT People seem to think there is only one constant pointer expression. Is that is really true, though? For instance, here is a common paradigm in Objective-C (it is really only C aside from NSString, id and nil, which are merely a pointers, so it is still relevant — I just wanted to point out that there is, in fact, a common use for it, despite this being only a technical question): #include <stdio.h> #include <Foundation/Foundation.h> static NSString * const kMyConstantObject = @"Foo"; void why_cant_we_switch_him(id ptr) { switch (ptr) { case kMyConstantObject: // (Note that we are comparing pointers, not string values.) printf("We found him!\n"); break; case nil: printf("He appears to be nil (or NULL, whichever you prefer).\n"); break; default: printf("%p!\n", ptr); break; } } int main(void) { NSString *foo = @"toast"; why_cant_we_switch_him(foo); foo = kMyConstantObject; why_cant_we_switch_him(foo); return 0; } gcc test.c -o test -framework Foundation test.c: In function 'why_cant_we_switch_him': test.c:5: error: switch quantity not an integer test.c:6: error: pointers are not permitted as case values It appears that the reason is that switch only allows integral values (as the compiler warning said). So I suppose a better question would be to ask why this is the case? (though it is probably too late now.)

    Read the article

  • What are function pointers good for ?

    - by gramm
    Hi, I have trouble seing the utility of the function pointers. I guess it may be useful in some case (it exists, after all), but I can't think of a case where it's better or unavoidable to use a function pointer. Could you give some example of good use of function pointers (in C or C++)? Many thanks :)

    Read the article

  • What is the point of function pointers?

    - by gramm
    Hi, I have trouble seing the utility of the function pointers. I guess it may be useful in some cases (they exist, after all), but I can't think of a case where it's better or unavoidable to use a function pointer. Could you give some example of good use of function pointers (in C or C++)? Many thanks :)

    Read the article

  • what is meant by normalization in huge pointers

    - by wrapperm
    Hi, I have a lot of confusion on understanding the difference between a "far" pointer and "huge" pointer, searched for it all over in google for a solution, couldnot find one. Can any one explain me the difference between the two. Also, what is the exact normalization concept related to huge pointers. Please donot give me the following or any similar answers: "The only difference between a far pointer and a huge pointer is that a huge pointer is normalized by the compiler. A normalized pointer is one that has as much of the address as possible in the segment, meaning that the offset is never larger than 15. A huge pointer is normalized only when pointer arithmetic is performed on it. It is not normalized when an assignment is made. You can cause it to be normalized without changing the value by incrementing and then decrementing it. The offset must be less than 16 because the segment can represent any value greater than or equal to 16 (e.g. Absolute address 0x17 in a normalized form would be 0001:0001. While a far pointer could address the absolute address 0x17 with 0000:0017, this is not a valid huge (normalized) pointer because the offset is greater than 0000F.). Huge pointers can also be incremented and decremented using arithmetic operators, but since they are normalized they will not wrap like far pointers." Here the normalization concept is not very well explained, or may be I'm unable to understand it very well. Can anyone try explaining this concept from a beginners point of view. Thanks, Rahamath

    Read the article

  • How do the operators < and > work with pointers?

    - by Øystein
    Just for fun, I had a std::list of const char*, each element pointing to a null-terminated text string, and ran a std::list::sort() on it. As it happens, it sort of (no pun intended) did not sort the strings. Considering that it was working on pointers, that makes sense. According to the documentation of std::list::sort(), it (by default) uses the operator < between the elements to compare. Forgetting about the list for a moment, my actual question is: How do these (, <, =, <=) operators work on pointers in C++ and C? Do they simply compare the actual memory addresses? char* p1 = (char*) 0xDAB0BC47; char* p2 = (char*) 0xBABEC475; e.g. on a 32-bit, little-endian system, p1 p2 because 0xDAB0BC47 0xBABEC475? Testing seems to confirm this, but I thought it'd be good to put it on StackOverflow for future reference. C and C++ both do some weird things to pointers, so you never really know...

    Read the article

  • What was that tutorial on pointers?

    - by pecker
    Hello, I once read a tutorial/article on Pointers somewhere. It was not a general tutorial but it explained how to clearly understand the complex & confusing pointers (especially like the ones that are usually asked in interview). It was more like http://www.codeweblog.com/right-left-rule-complex-pointer-analysis/ I'm unable to find it. Could any one post it here. PS: I did tried to google it but couldn't find. I'm asking it here because I thought it was popular.

    Read the article

  • Vector of Object Pointers, general help and confusion

    - by Staypuft
    Have a homework assignment in which I'm supposed to create a vector of pointers to objects Later on down the load, I'll be using inheritance/polymorphism to extend the class to include fees for two-day delivery, next day air, etc. However, that is not my concern right now. The final goal of the current program is to just print out every object's content in the vector (name & address) and find it's shipping cost (weight*cost). My Trouble is not with the logic, I'm just confused on few points related to objects/pointers/vectors in general. But first my code. I basically cut out everything that does not mater right now, int main, will have user input, but right now I hard-coded two examples. #include <iostream> #include <string> #include <vector> using namespace std; class Package { public: Package(); //default constructor Package(string d_name, string d_add, string d_zip, string d_city, string d_state, double c, double w); double calculateCost(double, double); void Print(); ~Package(); private: string dest_name; string dest_address; string dest_zip; string dest_city; string dest_state; double weight; double cost; }; Package::Package() { cout<<"Constucting Package Object with default values: "<<endl; string dest_name=""; string dest_address=""; string dest_zip=""; string dest_city=""; string dest_state=""; double weight=0; double cost=0; } Package::Package(string d_name, string d_add, string d_zip, string d_city, string d_state, string r_name, string r_add, string r_zip, string r_city, string r_state, double w, double c){ cout<<"Constucting Package Object with user defined values: "<<endl; string dest_name=d_name; string dest_address=d_add; string dest_zip=d_zip; string dest_city=d_city; string dest_state=d_state; double weight=w; double cost=c; } Package::~Package() { cout<<"Deconstructing Package Object!"<<endl; delete Package; } double Package::calculateCost(double x, double y){ return x+y; } int main(){ double cost=0; vector<Package*> shipment; cout<<"Enter Shipping Cost: "<<endl; cin>>cost; shipment.push_back(new Package("tom r","123 thunder road", "90210", "Red Bank", "NJ", cost, 10.5)); shipment.push_back(new Package ("Harry Potter","10 Madison Avenue", "55555", "New York", "NY", cost, 32.3)); return 0; } So my questions are: I'm told I have to use a vector of Object Pointers, not Objects. Why? My assignment calls for it specifically, but I'm also told it won't work otherwise. Where should I be creating this vector? Should it be part of my Package Class? How do I go about adding objects into it then? Do I need a copy constructor? Why? What's the proper way to deconstruct my vector of object pointers? Any help would be appreciated. I've searched for a lot of related articles on here and I realize that my program will have memory leaks. Using one of the specialized ptrs from boost:: will not be available for me to use. Right now, I'm more concerned with getting the foundation of my program built. That way I can actually get down to the functionality I need to create. Thanks.

    Read the article

  • C# wrapper for array of three pointers

    - by fergs
    I'm currently working on a C# wrapper to work with Dallmeier Common API light. See previous posting: http://stackoverflow.com/questions/2430089/c-wrapper-and-callbacks I've got pretty much everything 'wrapped' but I'm stuck on wrapping a callback which contains an array of three pointers & an array integers: dlm_setYUVDataCllback int(int SessionHandle, void (*callback) (long IPlayerID, unsigned char** yuvData, int* pitch, int width, int height, int64_t ts, char* extData)) Function Set callback, to receive current YUV image. Arguments SessionHandle: handle to current session. Return PlayerID (see callback). Callback - IPlayerId: id to the Player object - yuvData: array of three pointers to Y, U and V part of image The YUV format used is YUV420 planar (not packed). char *y = yuvData[0]; char *u = yuvData[1]; char *v = yuvData[2]; - pitch: array of integers for pitches for Y, U and V part of image - width: intrinsic width of image. - height - ts : timestamp of current frame - extData: additional data to frame How do I go about wrapping this in c#? Any help is much appreciated.

    Read the article

  • C++ Returning Pointers/References

    - by m00st
    I have a fairly good understanding of the dereferencing operator, the address of operator, and pointers in general. I however get confused when I see stuff such as this: int* returnA() { int *j = &a; return j; } int* returnB() { return &b; } int& returnC() { return c; } int& returnC2() { int *d = &c; return *d; } In returnA() I'm asking to return a pointer; just to clarify this works because j is a pointer? In returnB() I'm asking to return a pointer; since a pointer points to an address, the reason why returnB() works is because I'm returning &b? In returnC() I'm asking for an address of int to be returned. When I return c is the & operator automatically "appended" c? In returnC2() I'm asking again for an address of int to be returned. Does *d work because pointers point to an address? Assume a, b, c are initialized as integers. Can someone validate if I am correct with all four of my questions?

    Read the article

  • Pointers into elements in a container

    - by Pillsy
    Say I have an object: struct Foo { int bar_; Foo(int bar) bar_(bar) {} }; and I have an STL container that contains Foos, perhaps a vector, and I take // Elsewhere... vector<Foo> vec; vec.push_back(Foo(4)); int *p = &(vec[0].bar_) This is a terrible idea, right? The reason is that vector is going to be storing its elements in a dynamically allocated array somewhere, and eventually, if you add enough elements, it will have to allocate another array, copy over all the elements of the original array, and delete the old array. After that happens, p points to garbage. This is why many operations on a vector will invalidate iterators. It seems like it would be reasonable to assume that an operation that would invalidate iterators from a container will also invalidate pointers to data members of container elements, and that if an operation doesn't invalidate iterators, those pointers will still be safe. However, many reasonable assumptions are false. Is this one of them?

    Read the article

  • initalizing two pointers to same value in "for" loop

    - by MCP
    I'm working with a linked list and am trying to initalize two pointers equal to the "first"/"head" pointer. I'm trying to do this cleanly in a "for" loop. The point of all this being so that I can run two pointers through the linked list, one right behind the other (so that I can modify as needed)... Something like: //listHead = main pointer to the linked list for (blockT *front, *back = listHead; front != NULL; front = front->next) //...// back = back->next; The idea being I can increment front early so that it's one ahead, doing the work, and not incrementing "back" until the bottom of the code block in case I need to backup in order to modify the linked list... Regardless as to the "why" of this, in addition to the above I've tried: for (blockT *front = *back = listHead; /.../ for (blockT *front = listHead, blockT *back = listHead; /.../ I would like to avoid pointer to a pointer. Do I just need to initialize these before the loop? As always, thanks!

    Read the article

  • When to pass pointers in functions?

    - by yCalleecharan
    scenario 1 Say my function declaration looks like this: void f(long double k[], long double y[], long double A, long double B) { k[0] = A * B; k[1] = A * y[1]; return; } where k and y are arrays, and A and B are numerical values that don't change. My calling function is f(k1, ya, A, B); Now, the function f is only modifying the array "k" or actually elements in the array k1 in the calling function. We see that A and B are numerical values that don't change values when f is called. scenario 2 If I use pointers on A and B, I have, the function declaration as void f(long double k[], long double y[], long double *A, long double *B) { k[0] = *A * *B; k[1] = *A * y[1]; return; } and the calling function is modified as f(k1, ya, &A, &B); I have two questions: Both scenarios 1 and 2 will work. In my opinion, scenario 1 is good when values A and B are not being modified by the function f while scenario 2 (passing A and B as pointers) is applicable when the function f is actually changing values of A and B due to some other operation like *A = *B + 2 in the function declaration. Am I thinking right? Both scenarios are can used equally only when A and B are not being changed in f. Am I right? Thanks a lot...

    Read the article

  • complex arguments for function

    - by myPost1
    My task is to create function funCall taking four arguments : pointer for 2d array of ints that stores pairs of numbers variable int maintaining number of numbers in 2d array pointer for table of pointers to functions int variable storing info about number of pointers to functions I was thinking about something like this : typedef int(*funPtr)(int, int); funPtr arrayOfFuncPtrs[]; void funCall( *int[][]k, int a, *funPtr z, int b); { }

    Read the article

  • C# memory management: unsafe keyword and pointers

    - by Alerty
    What are the consequences (positive/negative) of using the unsafe keyword in C# to use pointers? For example, what becomes of garbage collection, what are the performance gains/losses, what are the performance gains/losses compared to other languages manual memory management, what are the dangers, in which situation is it really justifiable to make use of this language feature... ?

    Read the article

  • Why can't I add pointers

    - by Knowing me knowing you
    Having very similiar code like so: LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const { return (this + &right);//IN THIS PLACE I'M GETTING AN ERROR } LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator-(const Iterator& right)const {//substracts one iterator from another return (this - &right);//HERE EVERYTHING IS FINE } err msg: Error 1 error C2110: '+' : cannot add two pointers Why I'm getting an err in one place and not in both?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >