c,pointers,initialization,language-lawyer,void-pointers
I think, the C11 standard is quite clear in this regard. Referring chapter 6.7.9, paragraph 10, If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. Now, an indeterminate value is , well, indeterminate (which you're referring to as garbage and / or NULL...
c++,pointers,operator-overloading,wrapper
This is a conversion operator. For example, you could use it to convert a Pointer<T> to a real T* and, additionally, use it everywhere a T* is expected: Pointer<float> p(new float); const float* p2 = p; In this case, the operator is only defined for the conversion to const raw...
None of them are "undefined behavior". They are just different pointer declarations: int const *ptr; // pointer to const int int *const *ptr; // pointer to const pointer to int int **const ptr; // const pointer to pointer to int int const **ptr; // pointer to pointer to const int...
printf("%d ", *(Data+m)); printf("%d ", Data[m]); // how come these two print statements display the same thing? Because they mean the same thing; Data[m] and m[Data] would both be equivalent to *(Data+m) here, they all refer to the same element. // Curiously the function still works when passing the...
while(log = 1) while(log = 2) Wrong. In c, the = operator is for assignment, not comparison. You are setting log equal to 1 and 2 there. You want the == operator for comparison: while(log == 1) Next: scanf("%s", &p); Wrong. %s is for arrays of char ending in zero...
c,pointers,casting,compiler-errors,void-pointers
This line: ptr = (struct sockaddr_in *) res->ai_addr; does not do what you think it does; it doesn't automagically make ptr be of type struct sockaddr_in *, so you're still trying to dereference a void pointer. What you need to do is printf("Port number: %u\n", ntohs(((struct sockaddr_in *) res->ai_addr)->sin_port)); ...
You did not create an array of std::list objects when you used malloc. All malloc does is allocate memory from the heap -- no objects are created. Thus attempting to use your std::list's as if they are created correctly will result in undefined behavior. You should use a container such...
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++,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...
The entire float_to_string can be reduced to (as suggested by BLUEPIXY): void float_to_str(char *str, float f, char size) { sprintf(str, "%.*f", size, f); } However, if you are interested in the bug in your code, it is in the for loop: for( i = 0; i < size; ++i )...
funcy is a pointer to a member function, so you need to call it on an instance of the class, like this: (this->*funcy)(items,i); ...
If you have intptr_t (which is an integer type), then you can cast your void* pointers to that, and then you can compare arbitrary values. intptr_t is not a required type, but it is pretty common in practice. Subtracting one intptr_t from another might still overflow, so it is not...
c,pointers,hashmap,xcode6,expected-exception
Change: typedef struct HashMap { uint8_t KEY; uint8_t VAL; } *map; with: typedef struct HashMap { uint8_t KEY; uint8_t VAL; } HashMap ; HashMap *map; ...
c,pointers,compiler-warnings,suppress-warnings,keil
It is not an irrelevant warning because the assignment has no effect. You could completely remove ptr_1 from the code without changing its behaviour. Your code is equivalent to this: void foo(char *) { char *ptr_2; bar(ptr_2); } In other words, the function parameter isn't used for anything. If your...
Since you were looking for a solution either in C/C++, I created a layer of abstraction in C++ to protect the void** const arr as follows. Please check does it meet your requirement. class array{ public: void setArray(void** key) { arr=key; } void** getArray() { return &(*arr); } private: void**...
First of all, please think twice about the program design. Do you really need a 2D array of pointers, each pointing to a struct, each struct containing a number of items? Those requirements are rather complex: if you can simplify them, your program will turn out much better. Because with...
#include <iostream> using namespace std; double* fct_returns_ptr(double *, int); // function prototype int main(void) { double test_array[] = { 3.0, 10.0, 1.5, 15.0 }; // test value int len = (sizeof test_array)/(sizeof test_array[0]); //double* ptr_result = new double(0.0); //[len] pointer to result double* ptr_result = new double[ len ] ;...
c,string,pointers,char-pointer
The purpose was to add prefix and suffix to every word in the string so I need the string before the word , the word , and after the word. ex: prefix_I_suffix have done form here comes. I prefix_have_suffix have done form here comes. You're doing a few things...
Also another way (no dynamic memory): #include<stdio.h> void try(char *); int main() { char result[100] = {0}; try(result); printf("%s",result); return 0; } void try(char *result) { strcpy(result,"try this"); } Note: When you say you got null, that doesn't mean anything - actually you had undefined behaviour there - because result...
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...
Your question is based on a false premise. Subtraction of pointers produces a ptrdiff_t §[expr.add]/6: When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral...
Why won't you just check it? emp := ExampleMapHolder{make(map[string]int)} m := emp.TheMap() m["a"] = 1 fmt.Println(emp) // Prints {map[a:1]} Playground: http://play.golang.org/p/jGZqFr97_y...
I see several possible causes. First of all, casting char* to double* and then accessing it through that pointer is undefined behavior. Most of time it works, but you are warned. Pointer misalignment. double is most likely supposed to be aligned to 8 bytes, and you read it through pointer...
In your second loop in AddArray you want d < b instead of c < d. The second loop never executes as is because d starts at zero and c will always be greater than zero after the first loop.
c++,pointers,multiple-inheritance,virtual-functions,this-pointer
Bjarne wrote: "Naturally, B::bf() expects a B* (to become its this pointer)." The compiler transforms the call into: bf__F1B((B*)((char*)pc+delta(B)), 2); Why here we need a B* pointer to be the this? Consider B in isolation: the compiler needs to be able to compile code ala B::bf(B* this). It doesn't...
§6.3.2.3/p1: A pointer to void may be converted to or from a pointer to any object type. §6.2.5/p20: A pointer type may be derived from a function type or an object type, called the referenced type. [...] A pointer type is a complete object type. "pointer to function" is an...
Simply create a normal class without static methods, ditch the singleton pattern aside, and create an instance. The burden of singleton pattern usually outweigh any benefit....
c++,pointers,pass-by-reference,undefined-behavior,const-iterator
The code is perfectly fine. You're not stripping away any constness (there's no way to do that implicitly in C++). *it gives you a const intp &. You're copying the pointer referred to by that reference into arg. Copying from something does not strip constness away. The assignment to arg...
c,pointers,segmentation-fault,scanf
In your code, stack* st; st->top=-1; you're using st uninitialized which in turn invokes undefined behaviour. You need to allocate memory to st before using it. Try something like stack* st = malloc(sizeof*st); //also, check for malloc success That said, Please see why not to cast the return value of...
c,pointers,types,pointer-arithmetic
Incrementing a pointer adds to the memory address the size of the thing the pointer points to. If d is of type int***, it is a pointer to int**. ++d will cause the pointer to move over sizeof(int**) bytes and sizeof(int**) is 4 because it is a pointer. So if...
Important: scanf(" %s", name); has no bounds checking on the input. If someone enters more than 255 characters into your program, it may give undefined behaviour. Now, you have the char array you have the count (number of char in the array), why do you need to bother doing stuffs...
That's not the correct way to a pointer from a function. Also r is local variable whose lifetime is limited to the function. Allocate memory using malloc and return it instead: int* randn(int n, int l){ int *r=malloc(n * sizeof *r); if(!r) { */ error */} int i; for (...
c++,c,pointers,segmentation-fault,binary-search-tree
Since searchSpecific may return NULL, you need to protect your code from it, and check x before accessing one of its members: tree *x=searchSpecific(root,f); if (x != NULL && x->left) ...
First, we should understand that pointers and arrays are handled the same in C or C++, at least once we've moved past the definition. Let's make sure we understand a few things. From the example you have described above, the following are equivalent (after ptr=var). var[0], *var, ptr[0], ptr. All...
c,pointers,gcc,global-variables
Some elements allow, as it's been written, GCC to assume different behaviors in terms of optimization; likely, the most impacting optimization we see is loop vectorization. Therefore, Why is the code faster? The code is faster because the hot part of it, the loops in func, have been optimized with...
sizeof(void*) generally yields the size of pointers on your architecture, although there may be architectures where pointers to specific types are smaller - since void * is guaranteed to allow a full round-trip to any data pointer (C99 §6.3.2.3 ¶1), it should be surely bigger or equal to all other...
This should work: pass the object pointer as an opaque unmanaged pointer to the callback: context.info = UnsafeMutablePointer(Unmanaged.passUnretained(myObject).toOpaque()) SCNetworkReachabilitySetCallback(reachability, callback, &context) and retrieve in the callback via: func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) { let myObject = Unmanaged<MyObject>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() } Of course this assumes that some strong...
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()...
Any time you see an expression like a[b] in C, you can mentally think that *(a + b) is happening. So, it's just "the contents of the element before the one p is pointing at right now". Since p is at t + 2, p[-1] refers to t[2 + (-1)]...
Yes, the pointer to the struct is automatically dereferenced. From the spec on selectors: The following rules apply to selectors: For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T...
I think using intptr_t is the correct intermediate here, since it's guaranteed to be large enough to contain the integral value of the void*, and once I have an integer value I can then truncate it without causing the compiler to complain. Yes, for the reason you mentioned that's...
You could template your container Qvector and make it more generic with something like : template<class Container> int upperBoundIndex(const Container &vec,int first,int last,typename Container::value_type value) { // your code } But I think you should use std::upper_bound where you even have an example to get the index. So I would...
python,c++,pointers,numpy,cython
Typed memoryviews (http://docs.cython.org/src/userguide/memoryviews.html) are your friend here. a = np.empty([r,hn]) # interpret the array as a typed memoryview of shape (r, hn) # and copy into a # I've assumed the array is of type double* for the sake of answering the question a[...] = <double[:r,:hn]>self.thisptr.H It well may not...
The valid range of indices of an array with N elements is [0, N-1]. Thus instead of for example this loop for (int i=1; i <= n; i++) ^^^^ ^^^^^^ you have to write for ( int i = 0; i < n; i++ ) As you used operator new...
c++,function,pointers,reference
Yes. There's no copy anywhere as you're either using pointers or references when you “pass” the variable from one place to another, so you're actually using the same variable everywhere. In g(), you return a reference to z, then in f() you keep this reference to z. Moreover, when you...
c++,pointers,syntax,reference,variable-assignment
string & ref1 = *it; string & ref2 = *it; Okay, so you create two references to the same string. ++it; // After this line, both ref1 && ref2 evaluates to "a" Right, because they are both references to the same string. This is the way you created them. ref2...
It seems that you mean the following #include <stdio.h> #include <string.h> char * combine_strings( char *result, const char *s1, const char *s2 ) { if ( *s1 == '\0' && *s2 == '\0' ) { *result = '\0'; return result; } else if ( *s1 == '\0' ) { *result++...
As Mark says, pointers to functions and subroutines certainly do exist in Fortran. The differences are: In C, pointers are just an address whereas in Fortran, a pointer can have additional information such as array bounds and strides, which is why an explicit interface is required when declaring a pointer...
c++,pointers,reference,unique-ptr
The issue is here: auto pos = entity.addComponent<inc::CPosition>(); ^^^^^ addComponent() returns a reference, and everything in that function is fine (no dangling reference issue as far as I can tell). But auto does not deduce a reference type unless you tell it to - so you're simply making a copy...
c,pointers,dynamic-memory-allocation,behavior,realloc
Yes, ptr2 is unaffected by realloc(), it has no connection to realloc() call whatsoever(as per the current code). However, FWIW, as per the man page of realloc(), (emphasis mine) The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and...
c++,function,pointers,constructor,ampersand
Item i2(i1); This works because it is not calling your user-defined constructor which takes a pointer, it is calling the implicitly generated copy-constructor which has the signature: Item (const Item &); If you don't want this to be valid, you can delete it (requires C++11): Item (const Item &) =...
When you passed head to the function init_List, a local copy of head is made and then memory is allocated to this local pointer. In main, head still points to NULL. You need to use pointer to pointer in function parameter. void init_List(Node **head, int data) { *head = malloc(sizeof(Node));...
You haven't actually declared any storage for the array, nor is arr actually pointing to the first element of the array (dereferencing is undefined behavior). You are missing something like: int solve[2]; int * arr = solve; or int solve[2]; int * arr = &solve[0]; Both ways will assign the...
The GUI can be updated only from the main thread. You are trying to update your dialog from another thread. Try this QMetaObject::invokeMethod(poProgressDialog, "setValue", Qt::AutoConnection, Q_ARG(qint32, *itemDeletedCounter)); instead of this : poProgressDialog->setValue(*itemDeletedCounter); ...
c,pointers,memory,memory-address
Any decent IDE that comes with debugger should allow you to view dereferenced value of an pointer. I am not familiar with CodeBlocks, but for instance Eclipse CDT does such thing pretty easily: By default it prints just *ptr, but you may set it to view as array of particular...
In C (and also C++), array[n] is equivalent to *(array+n). They mean exactly the same thing and produce exactly the same result.
There is no implicit type conversion going on on template type deduction, so your example fails to compile. Related: C++ Templates type casting with derivates In non-template code, everything is OK, e.g. First *p = &obj; works just fine. Your example has the same flavour as template <int N> void...
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....
The whole body of your template function needs to compile for the types it's instantiated with, regardless of whether or not a branch will ever be taken. To get around this issue, you can define separate functions for when T is a pointer and when it's not. Using SFINAE: template...
This is a really cool bug to run into, especially for someone who is just beginning to learn C. Understanding this seemingly strange behaviour will improve your understanding of how your programs work quite a bit. Your code does not work properly because int j and a[0] do not have...
John Bode has already given a reply about how (in effect) your second code fragment addresses the MISRA guideline. I'll address your question "Is there a way to have a pointer to a cell in an array and increment it that will satisfy MISRA?" The short answer is "no". Rule...
c,arrays,function,pointers,unsigned-char
With this *arr = ptr; you are storing a pointer to a variable with automatic storage duration. The behaviour undefined. You can dynamically allocate and return a pointer that way: void changeArray(unsigned char **arr) { unsigned char ptr[3] = {100, 101, 102}; unsigned char *p = malloc(sizeof ptr); memcpy(p, ptr,...
No, they're completely different. Say the value of tmp is 1. Their code will give *pf the value of whatever floating point number has the same binary representation as the integer 1. Your code would give it the floating point value 1.0!
It looks like you never assign any value to root. Remember, C passes arguments by value, so when you call enter(root, word); from scan(), enter() can't change the value of root. It changes its local copy of it, though, but that is not enough. The same problem occurs when you...
debugging,pointers,gcc,gdb,memory-address
There is no built-in command to do this. There is an open feature request in gdb bugzilla to have a way to show the meaning of all the known slots in the current stack frame, but nobody has ever implemented this. This can be done with a bit of gdb...
See these questions in the C FAQ List: http://c-faq.com/aryptr/aryptr1.html http://c-faq.com/aryptr/aryptr2.html http://c-faq.com/aryptr/aryptrparam.html ...
std::vector<int> vec; vector<int>* pVec = &vec; vec.reserve(10000); assert(pVec == &vec); is safe. std::vector<int> vec(1,0); int* p = &vec[0]; // some operation here assert(p == &vec[0]); is not safe. The first block is safe since the address vec will not change even when its contents change. The second block is not...
c,pointers,operators,address-operator
Why can't I use &&a Because & gives you the address of a varibale and &a is not a variable. The C 11 Draft specifies the following: 6.5.3.2 Address and indirection operators Constraints 1 The operand of the unary & operator shall be either a function designator, the result...
c++,xcode,pointers,memory-alignment,type-safety
You are not checking against a pointer, you are checking against a reference. References are not supposed to be nullptr since they must refer to an existing value. Indeed what you are doing *(AStruct*)0 is not well defined since a reference shouldn't be able to generate undefined behaviour through "dereferencing...
Preferred option: change isPrime to take a long (and pass *it to it). Secondary option: pass &*it instead of it. Your original code doesn't work because it is an iterator (which is a class) whereas the function expected long int * and there is no implicit conversion from iterator to...
c++,pointers,c++11,function-pointers
As an alternative to traditional function pointers, C++11 introduced template alias which combined with variadic templates could simplify the function pointer sintax. below, an example of how to create a "template" function pointer: template <typename R, typename ...ARGS> using function = R(*)(ARGS...); It can be used this way: void foo()...
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....
You're a layer of indirection out! A "null pointer" and "a pointer to null/zero" are two different things. At its most basic: A null pointer itself has the value zero. It doesn't point to some other object with the value zero. p == 0; // yes *p == 0; //...
There is a bug in your code: You first allocate space for a function pointer and store the address in pp. void (**pp)(void) = malloc(sizeof(void (*)(void))); Then you immediately overwrite that with the address of a local function function p: pp = &p; You call f(), which in turn calls...
c++,c,performance,loops,pointers
Theoretically, the answer to your question is the former, simpler code. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile...
c++,pointers,memory-management
It may or may not print the same value after delete operation. So simply what you are observing is an undefined behavior.
c,arrays,pointers,double-pointer
You should not do that because in this case there will be a memory leak because you already allocated memory for pointer array and the assignment will overwrite the value stored in the pointer. Write the function simpler void function(int **arr) { int *tmp = *arr; tmp[0]=1; tmp[1]=2; tmp[2]=3; tmp[3]=4;...
You mentioned that you are new to C++, it is not safe to return local variables or the addresses of local variables. You have to allocate space for your a Node in order to safely return it and in C++ that is done with new. Objects allocated with new will...
sample of option 1 #include <stdio.h> #include <stdlib.h> int COLUMNS; int sum(int len, int *array){ int i, sum = 0; for(i=0; i<len; ++i) sum += *array++; return sum; } int cmp(const void *a, const void *b){ int sum1 = sum(COLUMNS, *(int**)a); int sum2 = sum(COLUMNS, *(int**)b); return (sum1 > sum2)...
c++,pointers,visual-studio-2012
When you do this: Common = "Hello World!"; you are making the pointer Common point at a literal C-style string (and incidentally leaking the original char that you allocated via new previously). It is not valid to try to modify such a literal, so when you pass this to FindCommonStr...
You haven't assigned any memory for your pointer to point to. That means that dereferencing the pointer (*pointer) causes undefined behavior (like a crash in your case). You need to initialize the pointer before dereferencing it: int* pointer = new int; (And afterwards, delete pointer; to not leak the memory....
BTW, if you are just reading the whole file, you can write something like this: #include <string> #include <fstream> #include <streambuf> std::ifstream t("timestamp.txt"); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); (If you care about the efficiency of the code above, there is a more efficient version here: Read whole ASCII file into C++ std::string)...
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)); ...
The line about which you ask: printf ("%s", * pok); passes two arguments to printf. The first is the format string "%s". The second * pok, i.e. the value at which pok points. Since you wrote pok = & niz[10]; (with an unnecessary cast to (unsigned char *) – cast...
If you want to dynamically allocate an array of booleans, you need to do bool *arr = new bool[10]; You have to specify the array size. The syntax for static allocation is bool arr[10]; ...
Your code makes no sense, why are you passing someStruct twice? For the reference part, you should have something like: void names(someStruct &s) { // <<<< Pass struct once as a reference cout << "First Name: " << "\n"; cin >> s.firstname; cout << "Last Name: " << "\n"; cin...
Look at the signature of your 'getVip' method: Vip Store::getVip(int index) { ... } ^^^ You are returning the 'Vip' object by value, which means you are returning a COPY of the object. Calling any method on that copy will result in a modification of that copy, not of the...
c++,pointers,parameter-passing,void-pointers
It still compiles fine & crashes at runtime. Why? What is the reason? Because void* is a technique for removing all type-safety and type checking. Should I not get the compile time error? By using void* instead of the correct pointer type int*, you are expressly telling the compiler...
x is the address of arr and arr is a stack variable so you cannot pass it as a return value. If you want check to return a pointer to an array you need to allocate it with new: arr = new int[r]. Note that you will need to eventually...
It declares the parameter as a reference. The parameter becomes in/out rather than C++/C's normal in only. This updates the structure passed to the function. void fun1 (ptr_mystruct &val) { val = somevalue ; } This updates a copy of the parameter in fun2 so the caller never sees the...
In the original C language - C89/90 - calling an undeclared function is not an error. For this reason, a pre-C99 compiler will not produce any "error" due to a missing function declaration. The compiler will simply assume that function returns an int. It will also automatically and quietly "guess"...
"a" is not a character, it is a string literal. 'a' is a character literal, which is what you are looking for here. Also note that in your comparison *s == "a" it is actually the "a" which is the pointer, and *s which is the integer... The * dereferences...
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,pointers,operator-keyword
In C/C++, given a pointer p and integral value k, p[k] is evaluated as *(p+k). Either form is fine to use as long as p+k points to valid memory. If you have access to the C99 Standard, see section 6.5.2.1 Array subscripting, Paragraph 2. It says: A postfix expression followed...
VALUE is a pointer to 32 bytes (char[32]). The pointer is cast to UInt16 pointer. That means the first two bytes of VALUE are being interpreted as UInt16 (2 bytes). * will dereference the pointer. We get the two bytes of VALUE as a 16-bit number. However it has...
c,arrays,pointers,malloc,dynamic-memory-allocation
"Access violation writing location 0x00000000" is explained by the manual http://man7.org/linux/man-pages/man3/malloc.3.html#RETURN_VALUE On error, these functions return NULL. Or if you prefer http://www.cplusplus.com/reference/cstdlib/malloc/. Return Value On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the...