FAQ Database Discussion Community


`&` in function parameter list

c++,pointers,memory-address
I saw this in some code and I'm confused about one thing: struct mystrct {...}; typedef mystrct* ptr_mystrct; void fun1(ptr_mystrct &val) {...} void fun2(ptr_mystrct val) {...} main() { mystrct foo; ptr_mystrct ptr_foo = &foo; fun1(ptr_foo); fun2(&foo); //this works fine fun1(&foo); //this is NOT valid (compiler error) } What is the...

Properly casting a `void*` to an integer in C++

c++,pointers,casting
I'm dealing with some code that uses an external library in which you can pass values to callbacks via a void* value. Unfortunately, the previous person working on this code decided to just pass integers to these callbacks by casting an integer to a void pointer ((void*)val). I'm now working...

compiler's detail of this pointer, virtual function and multiple-inheritance

c++,pointers,multiple-inheritance,virtual-functions,this-pointer
I'm reading Bjarne's paper: Multiple Inheritance for C++. In section 3, page 370, Bjarne said that "The compiler turns a call of a member function into an "ordinary" function call with an "extra" argument; that "extra" argument is a pointer to the object for which the member function is called."...

allocating space to list pointers using malloc not working

c++,pointers
class graph { int v; list<int> *adj; void dfsutil(int v,bool visited []); public: graph(int v) { this->v=v; //adj = new list<int>[v]; adj = (list<int> *)malloc(v*sizeof(list<int>)); } void addedge(int v,int w); void dfs(int v); }; void graph::addedge(int v,int w) { adj[v].push_back(w); } void graph::dfsutil(int v,bool visited[]) { list<int>::iterator i; cout<<v<<" ";...

Pointer Array in C? [duplicate]

c,arrays,pointers
This question already has an answer here: Negative array indexes in C? 5 answers Pointers are a difficult topic for sure, but I have come across this snippet and I just can't figure out what the p[-1] is: #include <stdio.h> int main(void) { int t[10] = { 1, 2,...

Pointer parameter was set but never used warning

c,pointers,compiler-warnings,suppress-warnings,keil
I have the following function: void foo(char *ptr_1) { char *ptr_2; bar(ptr_2); ptr_1 = ptr_2; } And get this warning: parameter "ptr_1" was set but never used I understand that the warning is technically true, but is irrelevant at the same time. I could suppress it with: (void)(ptr_1) But is...

Why is a pointer to NULL-charater not converted to false

c++,pointers
I thought the pointer pointed to NULL can be converted to 0. So I wrote the following program: #include <iostream> #include <regex> #include <string> #include <cstdlib> bool is_strtoi(const std::string& str) { char *p; std::strtol(str.c_str(), &p, 10); return *p == '\0'; } bool is_strtoi1(const std::string& str) { char *p; std::strtol(str.c_str(), &p,...

How much bytes will an int*** be moved forward when incremented? [duplicate]

c,pointers,types,pointer-arithmetic
This question already has an answer here: If you add 1 to a pointer, does it really add 1, or does it add 4 or 32? [duplicate] 2 answers I know that on incrementing a pointer variable it points to the next location of it's type i.e. int main()...

Does C language specify any implicit initialization for void pointers only?

c,pointers,initialization,language-lawyer,void-pointers
Here is my code: int main() { int *p; void *x; printf("%p\n", p); printf("%p\n", x); return 0; } which will print: koraytugay$ ./a.out 0x7fff53b35ad0 0x0 koraytugay$ ./a.out 0x7fff5803fad0 0x0 koraytugay$ ./a.out 0x7fff512c9ad0 0x0 koraytugay$ ./a.out 0x7fff55213ad0 0x0 koraytugay$ ./a.out 0x7fff52dbdad0 0x0 Is there any explanation to this behaviour in the...

Passing Pointers through a Function Then Getting Giberish

c++,function,pointers
I've got the following code, and it seems to be printing gibberish. However, when I change the size of the array from "r" to 5000, it works perfectly. Can anyone explain this behavior and show me how to fix it? I've done a lot of research on this, but can't...

pointer to pointer dynamic array in C++

c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

Segmentation fault when using if statement with pointers (BST tree)

c++,c,pointers,segmentation-fault,binary-search-tree
I'm trying to implement a binary search tree in C, more specifically looking for the predecessor. However, whenever I try to run the program I get the segmentation vault. Here's the code in question: #include <stdio.h> #include <stdlib.h> struct tree { int a; tree *left; tree *right; tree *prev; }*root=NULL;...

Are pointers dereferenced by default in golang struct methods?

pointers,go
I'm confused by golang methods on structs. I've following along in a tutorial in which they have: func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } From my understanding p is pointer and you would need to dereference the pointer before retrieving a...

Call template function for the value of a pointer out of a template function, in C++

c++,templates,pointers,c++11
I am trying to call a template function for the pointer that was given as template parameter in my calling function. My code is: template <> struct serialize_helper<std::string> { // not important code... } }; template <class T> inline void serializer(const T& obj, StreamType::iterator& res) { if(std::is_pointer<T>::value) { //THIS doesn'...

Shared dereferenced pointer value displays different results (when applying implicit copy constructor). Why?

c++,pointers,copy-constructor
The output of this piece of code is 21 I am unable to explain it to myself. My thinking (what I learned) is that an implicit copy constructor is called (triggered by the assignment) and all elements are copied bit by bit. However this does not apply to external elements,...

Pointer Referring to an Array

c++,arrays,pointers
Recently, I've been trying to strengthen my skills with pointers, and I ran into the following issue: I have the following piece of code, but I run into a runtime error. I tried looking up some stuff about iterating through a pointer that represents an array, but I couldn't find...

Is it safe to compare to pointer of std::vector to check equality?

c++,pointers,c++11,vector
at a time, I created a pointer point to a std::vector, then I did some push_back, reserve, resize operation to that vector, after such operations, is it safe to compare the pointer to the address of that vector to check whether the pointer point to that vector, because there might...

Private members of objects in an array not-modifiable

c++,pointers
I know there's a lot of literature on this, but I still can't figure it out. Let me start with a general description of the problem, and I'll post an MCVE. Description: Basically I have an array of objects - I can get the values of their private members, but...

Confusion regarding types, overflows and UB in pointer-integral addition

c++,pointers,c++11
I used to think that adding an integral type to a pointer (provided that the the pointer points to an array of a certain size etc. etc.) is always well defined, regardless of the integral type. The C++11 standard says ([expr.add]): When an expression that has integral type is added...

Print addresses of all local variables in C

debugging,pointers,gcc,gdb,memory-address
I want to print the addresses of all the local and global variables which are being used in a function, at different points of execution of a program and store them in a file. I am trying to use gdb for this same. The "info local" command prints the values...

Size of a pointer in C [duplicate]

c,pointers,sizeof
This question already has an answer here: Get size of pointer in C 3 answers How can I find the size of the type "pointer?" For example, if I want to know the size of an integer, I can use "sizeof(int)". What is the equivalent for a pointer? Is...

Unexpected performance with global variables

c,pointers,gcc,global-variables
I am getting a strange result using global variables. This question was inspired by another question. In the code below if I change int ncols = 4096; to static int ncols = 4096; or const int ncols = 4096; the code runs much faster and the assembly is much simpler....

Trouble with a recursive algorithm and pointers

c++,pointers,recursion,struct,allocation
So I'm trying to make an algorithm that starts at the first "room" and then recursively goes outward and starts deleting all rooms from the outside in. A room is a struct with 4 "doors" (pointers to rooms): North, South, East, and West. The function takes two arguments: pointer to...

Under Xcode 6.3, NULL C++ reference address evaluates as non-zero

c++,xcode,pointers,memory-alignment,type-safety
Similar to this question: XCode 6.3 Warning : Comparison of address of 'myObject' not equal to null pointer is always true with C++, I found that previously working code for evaluating null pointers stopped working: struct AStruct { int x, y; char *name; }; AStruct& GetStruct() { return *(AStruct*)0; }...

Looking into dynamic variables created using pointers?

c,pointers,memory,memory-address
I was wondering if there is a tool in any IDE which can be used to "look" into dynamically allocated variables in C. If for example I use the code below, it is not possible to use the watches (CodeBlocks) to track the variables, only the adresse the pointer is...

memory content not erased after deleting my pointer (on a simple example) [duplicate]

c++,pointers,memory-management
This question already has an answer here: Can a local variable's memory be accessed outside its scope? 16 answers Here is a simple of example of a question I have: I create a pointer of integer (value 5), I print the pointer (hence the address) of the memory case...

copy data from txt file to char pointer in c++

c++,string,pointers
I am trying to get fingerprint data (which I created and stored as a text file in another code) which I have to compare with a new fingerprint in this code. The problem is that the fingerprint API requires the fingerprint data to be passed as char pointer. I'm using...

How to store result of type char in pointer?

c,pointers
I want to store result of type char in pointer which I'm passing as argument of function. Like this: #include<stdio.h> void try(char *); int main() { char *result; try(result); printf("%s",result); return 0; } void try(char *result) { result="try this"; } But I'm getting result : (null) Could someone tell me...

C++, Use [] notation on pointer?

c++,arrays,pointers,operator-keyword
I just noticed I can use [] on a pointer and it works, but I was wondering, if this is good to use it. int a[]={1,2,3,4}; int *p=&a[1]; std::cout << p[0]; // returns 2; std::cout << p[-1]; // returns 1; std::cout << p[1]; // returns 3; I always learned, you...

Questions on C pointers

c,arrays,pointers
In the below code, I made an integer array and tried printing it with the function DisplayIntArray in order to try to understand how pointers work. Some questions are embedded in the comments. /*========================================================== * pointer tests *========================================================*/ #include <stdio.h> void DisplayIntArray(char *Name, int *Data, int lenArray) { /* Display...

C++ template using pointer and non pointer arguments in a QVector

c++,qt,templates,pointers
I'm trying to avoid having to use "nearly" the same code twice. I have the following template function, which searches for the provided value in a QVector and returns the index to the element. template<class tVec,class tVal> int upperBoundIndex(const QVector<tVec> &vec,int first,int last,tVal value) { //code here } Searching for...

Program to reverse a string in C without declaring a char[]

c,string,pointers,char
I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

converted string failed to contain correct values of float

c,pointers,char
I am facing problem in converting float to char*. I have written a function that will put integer part of float in string and then decimal values. I need it for two places of decimal. But something is horribly wrong. Either it ouputs integer value or just 1 place after...

Can assignment from a const_iterator dereference cause undefined behaviour?

c++,pointers,pass-by-reference,undefined-behavior,const-iterator
This code is a simplified test for something I am trying to do for real elsewhere. I have a function which takes a "ref-to-ptr" argument and modifies it to return a pointer from a list of pointers. #include <iostream> #include <list> using namespace std; typedef int* intp; typedef std::list<intp> intplist;...

Why I cannot use “fgets” to read a string to an element of my Struct?

c,pointers,memory-management,struct,fgets
I'm trying to create a program almost like "bank" using struct, but when the program should have read the string (variable "nome" that is name in portuguese) it totally ignore the "fgets" that I used. This is the part that I was talking about : printf("\nNome: \n"); fgets(vet[cont+1].nome, sizeof(vet[cont+1].nome), stdin);...

Allocate a new bool array pointer

c++,arrays,pointers
I'm curious how you go about allocating a new boolean array pointer in c++. I did some looking around but couldn't find anything that is similar to how I've learned to allocate new pointers. To allocate a new int pointer I have learned to do int * intPointer = new...

Taking address of temporary

c++,pointers
I am trying to assign the return value of my function to a node, which is a pointer. I have tried it both with and without '&' but non of them seem to work. I am currently getting the error in the title. Without the '&' get a "cannot convert...

modern c++ alternative to function pointers

c++,pointers,c++11,function-pointers
I've been using function pointers till now, like this format in c++. I do have some uses now and then and I'm wondering is there anything else introduced in c++11/14 as their alternative. #include <iostream> using namespace std; void sayHello(); void someFunction(void f()); int main() { someFunction(sayHello); return 0; }...

Passing buffers in C with MISRA compliance

c,arrays,pointers,misra
MISRA is frustrating our developers. We are getting MISRA errors about "Do not apply pointer arithmetic to pointer" and "pointer does not point to array". We are using the syntax of: uint8_t const * p_buffer to pass a buffer to a function that writes the buffer to a SPI bus....

Parameters to use in a referenced function c++

c++,pointers,reference
I am very confused as to what kind of variables I would put into my function here: names. I am doing a practice problem in a C++ book, because I am learning C++ and am on References and pointers right now, and cannot find a solution. Just for background information,...

Can I sort an array of pointers in order to remove duplicates?

c,pointers,undefined-behavior
Let's say I defined a structure and created a few instances of it. I have an array of pointers to these instances but some pointers point to the same instances of my structure. I want to remove duplicates in the array so I sort it by qsort() function. Here's my...

Malloc confusion

c,pointers,malloc
Hi after going through answer here 1: Do I cast the result of malloc? I understood that one of the reason why we do not cast malloc is that casting malloc is redundant But what I am still trying to figure out is the warning that will be suppressed when...

Access violation on try to fill dynamic array (large number of items)

c,arrays,pointers,malloc,dynamic-memory-allocation
I have the following C code: int dimension; double *AtS; ... AtS=(double*)malloc(sizeof(double)*dimension); for (i=0; i<dimension; i++) { AtS[i]=0.0; } While dimension is ~6-8 millions it works fine, but when it about 300 millions it fails with access violation. The following message in debug: Unhandled exception at 0x012f1077 in mathpro.exe: 0xC0000005:...

Port C# Code to Java

java,c#,pointers,struct,pointer-arithmetic
Following problem: I have a c# program doing some de/encryption in a very low level way. I used a tool, to convert most of the c# code to Java, which worked for most of the things but when it comes to such low level parts, the tool fails. The following...

Initializing, constructing and converting struct to byte array causes misalignment

c,arrays,pointers,struct,memcpy
I am trying to design a data structure (I have made it much shorter to save space here but I think you get the idea) to be used for byte level communication: /* PACKET.H */ #define CM_HEADER_SIZE 3 #define CM_DATA_SIZE 16 #define CM_FOOTER_SIZE 3 #define CM_PACKET_SIZE (CM_HEADER_SIZE + CM_DATA_SIZE +...

binary tree code does not work properly

c,pointers
I made a tree structure, read words from file and registered them to the tree. But the enter() does not work properly. I debuged with gdb and set a break point line 42. Then I entered print *node print *root. (gdb) print node $9 = (struct node *) 0x603250 (gdb)...

Swift 2 - UnsafeMutablePointer to object

swift,pointers,swift2
If I have a method like: func someMethod(contextPtr: UnsafeMutablePointer<Void>) how do I get the object from the contextPtr? func someMethod(contextPtr: UnsafeMutablePointer<Void>){ let object:MyObject = contextPtr.memory } gives: 'Void' is not convertible to 'MyObject' What's the secret sauce More detail: What I'm actually doing here is setting up a global callback...

In C language, What is the difference between extern buffer[] and extern *buffer?

c,arrays,pointers
I read the below piece of information in a microsoft article; https://support.microsoft.com/en-us/kb/44463 The text below presents an example of a common programming mistake, that is, confusing an array and a pointer declaration: Consider an application divided into several modules. In one module, declare an array as follows: signed char buffer[100];...

2D array, sort rows by sum

c,arrays,sorting,pointers
There is 2D array with pointers from user, filled with random numbers, program count sum of every row. I need to sort array by sum of every row and print it. For example if we have array:1 2 2 (sum=5)2 9 9 (sum=20)2 1 6 (sum=9) output should be:1 2...

How to pass pointer to struct to a function?

c,function,pointers,struct
I am instantiating the struct within the main() function and I am passing a pointer to this structure over to a function. I would like to then pass this pointer to the original struct to another function, how would I do this? I am now lost in pointerception. struct coords...

Program not compiling after casting pointer

c,pointers,casting,compiler-errors,void-pointers
Here is my code: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> int main (void) { struct addrinfo hints; memset (&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_CANONNAME; struct addrinfo *res; getaddrinfo ("example.com", "http", &hints, &res); printf ("Host: %s\n",...

Why cant set pointers in functions

c++,function,pointers
I have noticed that if i create a pointer in a function, it won't let me set a value to it. for example: int func() { int* pointer; *pointer = 0 //error I get: "Exception: STATUS_ACCESS_VIOLATION" return *pointer; } I get that not letting you set a pointer in the...

Function pointer to singleton class instance function

c++,oop,pointers,singleton
What I'm trying to do is create a function pointer to a single class instance function. I want to do this so I can do something like this: C->member_method(); instead of: Config::inst()->member_method(); but I'm not sure how to go about it. Here is my singleton class: class Config { private:...

modifying double pointer to an integer array

c,arrays,pointers,double-pointer
void function(int **arr); int main() { int *array; array=calloc(4, sizeof(int)); function(&array); return0; } void function(int **arr) { int *tmp; tmp=calloc(4, sizeof(int)); tmp[0]=1; tmp[1]=2; tmp[2]=3; tmp[3]=4; } I want to assign tmp to arr. how can I do it?...

Does realloc() invalidate all pointers?

c,pointers,dynamic-memory-allocation,behavior,realloc
Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

Although maps are always reference types, what if they're returned from a non-pointer receiver?

pointers,dictionary,go
Supposedly maps are reference types in Go, so when returning them from functions, you don't need to pass as a pointer to the map in order for the changes to be visible outside the function body. But what if said map is returned from a method on a non-pointer struct?...

String manipulation code using char ** pointer gives unexpected result

c,string,pointers,char-pointer
I was trying to implement a string parsing code for that I need substring of the given string so I deed the following: The header file is : test.h #ifndef header_file #define header_file #include<stdio.h> #include<string.h> int increment(char **); #endif The source files : main.c test.c test.c : Case1 :test.c #include"test.h"...

Is there a way to restrict a pointer from being modified by specific functions?

c,pointers
This builds off of my previous question: Is this an appropriate use of const qualifiers in C? In Vector.h: typedef struct _Vector Vector; Vector* vector_init(const UInt32 size); void* vector_get(const Vector *v, UInt32 idx); void vector_add(Vector *v, void* const elem); void vector_set(Vector *v, const UInt32 idx, void* const elem); ...etc In...

Using [] on pointers in C?

c,pointers,indexing
Right now I'm looking over some C code and they have some pointer syntax that I'm confused about. So first they declared a pointer like so: int32_t *p_tx_buf=NULL; Then later on they wrote: p_tx_buf = malloc(...math... ); The stuff in the middle is just math to calculate the size of...

create ndarray out of c++ pointer

python,c++,pointers,numpy,cython
I created a module in c++ and need to use the results in python. Already wrote a wrapper and it is working with this code a = np.empty([r, hn]) for i in xrange(r): for j in xrange(hn): a[i,j]=self.thisptr.H[i*hn+j] return a The code is working, but I think there should be...

Pointers and Character Arrays

c,arrays,string,pointers
Below is the program to copy the one string to another. I would expect the following program to give me a warnig or an error but it works just. #include<stdio.h> #include<stdlib.h> #include<string.h> void strcp(const char *source,char *dest) { while(*source!='\0') { *dest++=*source++; } // *dest='\0'; } int main(void) { char source[]="This...

Porting C endianness & pointers black magic to Swift

c,swift,pointers,endianness
I'm trying to translate this snippet : ntohs(*(UInt16*)VALUE) / 4.0 and some other ones, looking alike, from C to Swift. Problem is, I have very few knowledge of Swift and I just can't understand what this snippet does... Here's all I know : ntohs swap endianness to host endianness VALUE...

void pointer in function parameter

c++,pointers,parameter-passing,void-pointers
Consider following program: #include <iostream> void f(void* a) { std::cout<<"(void*)fun is called\n"; std::cout<<*(int*)a<<'\n'; } int main() { int a=9; void* b=(int*)&a; f(b); return 0; } If I change the function call statement like this: f(&b); It still compiles fine & crashes at runtime. Why? What is the reason? Should I...

C++ - Why does 2 local references to the same object stay in sync?

c++,pointers,syntax,reference,variable-assignment
I would like to understand what's going on here. Obviously, there's some aspect of references or assignment operators that I am not getting right. Objective: Within a function, I want to work with 2 local reference variables to various elements of the same list: one is the iterated over and...

Program immediately terminates with segfault when using scanf

c,pointers,segmentation-fault,scanf
When I use gets() or fgets() instead of scanf(), the program does execute completely but prints segmentation fault(core dumped) in the end! I don't understand why am I getting segfault in both the cases. Here is the code for converting an infix to postfix exp using stacks. #include<stdio.h> #include<stdlib.h> #include<string.h>...

Functions with pointer arguments in C++

c++,function,pointers,constructor,ampersand
I'm having some difficulties in understanding some aspects of functions with pointers. Here is the code I'm running: #include <iostream> using namespace std; class Item { public: Item(Item * it) { data = it->data; } Item(int d) { data = d; } void printData() { cout << data << endl;...

Initializing a pointer to a struct with malloc [duplicate]

c,pointers,linked-list
This question already has an answer here: How do I modify a pointer that has been passed into a function in C? 5 answers This might be a question with a very simple solution but I can't get my head around it... I'm trying to implement linked list for...

Why can't I use `&&a` in C?

c,pointers,operators,address-operator
int main(int argc, char * argv[]) { int a = 10; int * sp = &a; int * * dp1 = &sp; int * * dp2 = &&a; // NG int * * dp3 = &(&a); // NG int * * dp4 = &((int *) &a); // NG } $...

c++: Pointers and address

c++,pointers
#include <iostream> using namespace std; void test_func(char *data,int length) { cout<<"data:"<<data<<endl; cout<<"length:"<<length<<endl; void *addr=data; cout<<"*addr:"<<addr<<endl; cout<<"Address of data:"<<&data<<endl; cout<<"data again:"<<*(&data)<<endl; } int main() { char msg[]="Hello world!"; test_func(msg,6); return 0; } I was trying some other program where I came accrross void *addr=data. so I tried to understand it by...

Add Array Program Not Working

c,arrays,pointers
I am learning C and I just went over the pointers section. The book asked to write a program that adds two Arrays together into one array by passing a pointer to a function. I went through the code and it all looks ok to me, but for some reason...

Getting a Expected identifier or '(' issue in Xcode 6.1

c,pointers,hashmap,xcode6,expected-exception
I'm quite new to C. I've tried other links but no dice. I'm using Xcode 6.1 and I get the following issues: Parse Issue: Expected identifier or '(' Semantic Issue: Unexpected type name 'map' Here's my code: //hashmap.h #ifndef __HashMap__hashmap__ #define __HashMap__hashmap__ void map_init(); void map_insert(uint8_t, uint8_t); uint8_t map_getVal(uint8_t); #endif...

Pointer arithmetic; Must do it twice initally

c,pointers,pointer-arithmetic
I have a piece of code here that I'm a bit confused about. It seems that if I use: p = &j, it takes two increments just to begin traversing a[]: #include <stdio.h> int main(void) { int a[4] = {5,2,6,4}; int j = a[0]; int *p; p = &j; printf("*p...

What does (unsigned char*)&niz[10] mean?

c,pointers
Can anyone explain me what does this program do? #include int main () { unsigned char niz[20000]; unsigned char pok; pok = (unsigned char)&niz[10]; printf("%s",*pok); return 0; } When I run progam it says: warning: format %s expects argument of type char *,but argument 2 has type int [-Wformat=] printf("%s",*pok);...

double* android ndk crash

c++,pointers,android-ndk
I'm facing a peculiar problem with the android ndk. I'm trying to read a previously stored set of bytes in an unsigned char* readBytes (previous allocated and read from file). The data needs to be interpreted as double. unsigned char* svDataOffset=(unsigned char*)(readBytes+byteCounter); unsigned char* chars=(unsigned char*)(svDataOffset+2); //offset of 2 is...

passing a pointer through a function c

c,function,pointers
I'm trying to exit a while loop within a function but I don't think i'm writing the pointer correctly, c is new to me and reading examples online is confusing. I would appreciate feed back on what I'm writing incorrectly. int logOn(int *log); int main(void) { int log; log =...

function returns pointer to array

c++,arrays,pointers,rvalue
i wrote this c++ code to make a function returns a pointer to an array of double, in such way i use it as rvalue. i got a weird error message because i couldn't understand what's wrong with it. here is the code with the error message #include <iostream> using...

Array of constant pointers to functions

c,function,pointers,constants,ansi
I want to make an array of constant pointers to functions. Something like this: #include <stdio.h> #include <stdlib.h> int f( int x); int g( int x ); const int ( *pf[ ] )( int x ) = { f, g }; int main(void) { int i, x = 4, nf...

Functions and pointers in C

c,function,pointers
I am trying to assign the return value of a function to variable, the problem is that this return value is an array, I understand that it will return a pointer, but as you can see below I just couldn't do the proper assignment, I've looked at many questions and...

How to allocate memory to struct pointer using malloc.h header?

c,pointers,struct,malloc,dynamic-memory-allocation
#include<stdio.h> #include<malloc.h> #include<stdlib.h> struct student { char name[25]; int age; }; int main() { struct student *c; *c =(struct student)malloc(sizeof(struct student)); return 0; } What is the wrong with this code? I tried times by alternating this code to allocate memory to struct pointer. But this error comes when compiling:...

Dynamically creating a 2D array of pointers using malloc in C

c,arrays,pointers,malloc
This is a structure that I am using: struct nodeList//a node structure { int jump; int config; int level; int shifts[200]; int shift_diff[200]; struct nodeList *next; }; I want to create a 2D array of pointers that can be used to reference such a structure variable, ie, any element of...

assigning from a pointer value

c,pointers
I saw the following piece of code in an opensource AAC decoder, static void flt_round(float32_t *pf) { int32_t flg; uint32_t tmp, tmp1, tmp2; tmp = *(uint32_t*)pf; flg = tmp & (uint32_t)0x00008000; tmp &= (uint32_t)0xffff0000; tmp1 = tmp; /* round 1/2 lsb toward infinity */ if (flg) { tmp &= (uint32_t)0xff800000;...

Is a pointer to function pointer convertible to a void pointer and vice versa?

c,pointers,function-pointers
void f(void); void (*pf)(void) = f; void *p = &pf; (*(void (**)(void))p)(); I tried to find the part in the C standard (draft) document that states about such conversion. But I failed to do so in my last 30 minutes. How is the conversion between a void pointer and a...

combining 2 strings in another string alphabetically

c,string,pointers,recursion
I want to write a recursive function that combines 2 string into one string that is in alphabetic order , the 2 strings are only small letters and in ascending alphabetical order . Example : s1: "aegiz" s2: "abhxy" s3: "aabeghixyz" I am still new to recursive functions and to...

(Dangling?) Reference returned from function does not “work”

c++,pointers,reference,unique-ptr
I followed V. Romeo's Tutorial on entity management (on GitHub & Youtube). I then tried to rewrite the classes CEntity, CComponent and for testing CPosition(mostly from memory from Romeo's video/code). The problem i encounter is that, in my main i create a CEntity on the stack & add a component....

Visual Studio C++ access violation when modifying a pointer passed into a function

c++,pointers,visual-studio-2012
I want to implement a simple function that gets a string as a char pointer and modifies the string in a function. The requested function must be void then I have to modify the primary string passed into my function. I got an access violation error and googled it but...

passing arguments via reference and pointer C++

c++,function,pointers,reference
I am looking at a code snippet and I have this sequence. class MyVariable { .... CustomType z; .... } A.cpp calling a function f ( & myVariable) In an included file I do have this : B.h void f ( MyVariable * myVariable); B.cpp f( MyVariable * myVariable){ CustomType...

C Program: Update unsigned char pointer array with function

c,arrays,function,pointers,unsigned-char
I have a function to update an unsigned char* and cannot find where my bug is. I'm not sure if I need to allocate memory, or if I am pointing to the wrong memory space somewhere. I tried to follow a similar structure as posted here, but have not had...

function pointer is not a function or function pointer

c++,function,pointers
I have following problem: void MyClass::LoopFunction(vector<Item>& items,void (MyClass::*funcy)(vector<Item>&,int)) { for(SInt32 i = 0; i < 50; i++) { funcy(items,i); } } It says: Called object type 'void(MyClass::*)(vector<Item>&,int)' is not a function or function pointer Can anyone help me to find a solution for this?...

How to call a non-class member function with pointers as parameters with QtConcurrent::run?

c++,qt,pointers,qtconcurrent
I want to call a recursive non-class member function used to erase a given folder with all of its files using Qt 4.8 for Embedded Linux: bool removeFiles(const QString & dirName, Interface::ProgressDialog* const poProgressDialog, qint32* const itemDeletedCounter) { bool result = true; try { QDir dir(dirName); if (dir.exists(dirName)) { Q_FOREACH...

Error when using pointer to derivative class as template argument

c++,templates,pointers
I have encountered a problem when giving as a template pointer argument a pointer to the derivative class instead of the base class. E.i. the following code: class First{}; class Second : public First {}; template<First* ptr> class Third {}; Second obj; int main(){ Third<&obj> obj2; } when compiled returns...

How exactly do pointers in Fortran differ from C/C++ pointers?

c++,c,pointers,fortran
It might be useful to have both C/C++ programmers and Fortran programmers compare and contrast pointers in these two languages. In trying to explain to C/C++ programmers how Fortran pointers differ, I usually say pointers to functions or subroutines do not exist. I then try to make the argument that...

Conversion between a void pointer and a pointer to function pointer

c,pointers,function-pointers
I know void * and function pointers cannot be safely converted either way. My question is the below code. #include <stdio.h> #include <stdlib.h> void f(void *); void g(void) { printf("hello world\n"); } int main(void) { void (*p)(void) = g; void (**pp)(void) = malloc(sizeof(void (*)(void))); pp = &p; f(pp); free(pp); //segfault...

How to compare pointer and integer? [duplicate]

c,pointers,char
This question already has an answer here: How do I properly compare strings in C? 3 answers I'm trying to check if pointer is pointing at some char. Like this: #include<stdio.h> #include<string.h> #define a 3 int func(char *); int main() { char *s="a"; int type; type=func(s); printf("%d",type); return 0;...

How to make a function return a pointer to array struct

c,arrays,pointers,struct
I'm working on a function in C that should return a pointer to an array struct. The struct is struct corr{ char nome[128]; char cognome[128]; char password[10]; float importo; }; typedef struct corr correntista; The function that return a pointer to this struct is correntista *max_prelievo(FILE *fcorrentisti, FILE *fprelievi){ correntista...

C/C++: What's faster: a for loop, or incrementing a pointer

c++,c,performance,loops,pointers
I am wondering which of the following code segments would be fastest, assuming that the goal is to read from the elements of type T in amount numElements pointed to by somePointer and do something with them. I'm specifically interested in the efficiency of the looping structure itself, not what's...

Error while trying to update array element

c,arrays,pointers,struct,typedef
I am working on an embedded platform which does not have debugging features. So it is hard to say what is the error source. I have defined in header file: typedef struct cm_packet { CM_Header Header; //header of packet 3 bytes uint8_t *Data; //packet data 64 bytes CM_Footer Footer; //footer...

Difference between the use of pointers for array and single data point?

c++,arrays,pointers
#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; // let us have array address in pointer. ptr = var; for (int i = 0; i < MAX; i++) { cout << "Address of var[" << i...

C++ operator overloading for wrapper class

c++,pointers,operator-overloading,wrapper
I'm using a class called Pointer, which is some kind of a wrapper around a real pointer I guess. I think this line of code in this class enables me to get the real pointer: operator const T* () const; What does this mean exactly? How can I call this?...

Among the following constant pointers, which are said to be undefined behaviors?

c,pointers
int const *ptr; int *const *ptr; int **const ptr; int const **ptr; I know that whatever is followed by the keyword const cannot be re-written (here I cannot re-write *ptr, *ptr, ptr, **ptr respectively). But I am not sure about the behaviors of the pointers before the keyword const and...

Passing iterator's element to a function: wrong type of pointer

c++,pointers,stl,iterator
I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...