question
stringlengths
25
894
answer
stringlengths
4
863
If *get_ii() returned heap memory, rather than stack memory, would this problem be eliminated? ``` 01 int *get_ii() 02 { 03 int ii; // Local stack variable 04 ii = 2; 05 return ⅈ 06 } 07 main() 08 { 09 int *ii; 10 ii = get_ii(); // After this call the stack is given up by the...
Yes. Allocating from the heap would work here. Make sure that somewhere you release it again otherwise you'll leak memory. Often smart-pointers help with this kind of "don't forget" logic.
Although I wouldn't have written it myself, what is the expected result of the following statement whereA(guaranteed to zero or positive integer) is greater than 1? return A || 1; In many languages, I would expectAto be returned, unless the value ofAis zero, in which case 1 would be. I don't have my C book to hand,...
The standard says The||operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. See section 6.5.14 of thestandard.
I am porting a large project to Windows, and I'm stuck on unistd.h. I doubt this code is using a great deal of unistd's functionality, so I think I could be able to provide some sort of replacements for it. Meanwhile, I need to figure out what features of the header the code is using. Is there any tool that will tell...
Comment #include "unistd.h" lines. See everything that is not compiled. As requested :)
``` HWND hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_READONLY | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL, 0, 0, width, height, hWnd, (HMENU)IDC_MAINEDIT, GetModuleHandle(NULL), NULL); ``` Well, that's how I create an (readonly) edit (textbox) control...
Creating a Rich Edit Control(on MSDN)
This question already has answers here:Closed13 years ago. Possible Duplicate:c difference between malloc and calloc Please explain the significance of this statement, Another difference between the malloc() and calloc() functions is that the memory allocated by malloc( ) function contains garbage values, w...
Fromhttp://wiki.answers.com/Q/Is_it_better_to_use_malloc_or_calloc_to_allocate_memory malloc()is faster, sincecalloc()initializes the allocated memory to contain all zeros. Since you typically would want to use and initialize the memory yourself, this additional benefit ofcalloc()may not be necessary.
My project is made out of lots of bits and pieces of older code. How do I know how many lines of code were actually used? Can Klocwork provide me this answer? I've noticed that Klocwork holds the number of line (SLOC) in the project - but is it the number of actual lines used - or can it include "dead code" areas? ...
I haven't used klocwork, but it should be able to find unreachable code. A static analysis tool (Klocwork) can only find code that can never possibly be reached, it won't find code that never is reached in practice. There are other tools that you can run to determine the code coverage at run time, as the product is p...
Anyone know of a decent C99 fenv.h implementation for MS compilers? I imagine this wouldn't be difficult to do; I'm just looking to save some time.
I don't know of any implementations and I doubt any exists. Although Visual Studio has the_controlfp()function and a number of related preprocessor pragma's (float_control(),fenv_access(),fp_contract(), I don't think you can use them to create a conformingfenv.himplementation. Sad as it is, Visual Studio is not a C99...
my code is a mix up of different bits and pieces from older code. I would like to erase all never used functions in order to keep the code simple. Is Klocwork the tool? How do I do it? Thanks, Moshe.
You could use the-por-pgoptions togccto cause code to be added to the prologue and epilogue of every function so that a profile database is written when the program executes. The toolprofis used to analyze the output from-pandgproffor -pg. These tools produce reports showing what functions were used, how many calls, a...
I got a situation where the client got 'C' program which does encryption of columns at client application side. And the same is now to be used in DataWarehousing project in one of the script component which supports C#. Is there a way this C program can be compiled to dll and imported into C# [or] do we need to re-w...
If the client's code is already in a DLL, you can use all routines from it using P\Invoke in C#. Here is atutorial.
This question already has answers here:Compilation error: stray ‘\302’ in program, etc(12 answers)Closed8 months ago. I am working on a simple project in Objective-C in Xcode, and I'm getting some stray/ errors about the following line of code: ``` if(celsius < −273.15) { NSLog(@"It is impossible to convert temp...
− != - Your minus, isn't a minus.
Within the Windows XP Pro RGui, can't compile inline C code. Get error:'sh' is not recognized as an internal or external command Clearly there is a configuration error, but can't find a way to resolve it either in R documentation or via googling. Must be a simple solution! The same R code works fine on linux: the in...
You need the RTools collection as described in detail inAppendix D of the R Installation and Administrationmanual.
Let's say I have:sample.c ``` int main (...) { char str*; get s through user input test(str); return 0; } void test (str) { copy str to new file change file permissions on new file close file } ``` There's no possibility of a race condition here since I have no threads in my main() method...
There is a kind of race condition in that the user can exchange "new file" immediately before you change permissions of "new file". This is (was?) an often used security exploit. I just see that Neil Butterworth had a related idea.
Why would you ever want to use alloca() when you could always allocate a fixed size buffer on the stack large enough to fit all uses? This is not a rhetorical question...
It could be useful if the size of the buffer varies at runtime, or if you only sometimes need it: this would use less stack space overall than a fixed-size buffer in each call. Particularly if the function is high up the stack or recursive.
If *get_ii() returned heap memory, rather than stack memory, would this problem be eliminated? ``` 01 int *get_ii() 02 { 03 int ii; // Local stack variable 04 ii = 2; 05 return &ii; 06 } 07 main() 08 { 09 int *ii; 10 ii = get_ii(); // After this call the stack is given up by the...
Yes. Allocating from the heap would work here. Make sure that somewhere you release it again otherwise you'll leak memory. Often smart-pointers help with this kind of "don't forget" logic.
Although I wouldn't have written it myself, what is the expected result of the following statement whereA(guaranteed to zero or positive integer) is greater than 1? return A || 1; In many languages, I would expectAto be returned, unless the value ofAis zero, in which case 1 would be. I don't have my C book to hand,...
The standard says The||operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. See section 6.5.14 of thestandard.
I am porting a large project to Windows, and I'm stuck on unistd.h. I doubt this code is using a great deal of unistd's functionality, so I think I could be able to provide some sort of replacements for it. Meanwhile, I need to figure out what features of the header the code is using. Is there any tool that will tell...
Comment #include "unistd.h" lines. See everything that is not compiled. As requested :)
``` HWND hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_READONLY | ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL, 0, 0, width, height, hWnd, (HMENU)IDC_MAINEDIT, GetModuleHandle(NULL), NULL); ``` Well, that's how I create an (readonly) edit (textbox) control...
Creating a Rich Edit Control(on MSDN)
This question already has answers here:Closed13 years ago. Possible Duplicate:c difference between malloc and calloc Please explain the significance of this statement, Another difference between the malloc() and calloc() functions is that the memory allocated by malloc( ) function contains garbage values, w...
Fromhttp://wiki.answers.com/Q/Is_it_better_to_use_malloc_or_calloc_to_allocate_memory malloc()is faster, sincecalloc()initializes the allocated memory to contain all zeros. Since you typically would want to use and initialize the memory yourself, this additional benefit ofcalloc()may not be necessary.
My project is made out of lots of bits and pieces of older code. How do I know how many lines of code were actually used? Can Klocwork provide me this answer? I've noticed that Klocwork holds the number of line (SLOC) in the project - but is it the number of actual lines used - or can it include "dead code" areas? ...
I haven't used klocwork, but it should be able to find unreachable code. A static analysis tool (Klocwork) can only find code that can never possibly be reached, it won't find code that never is reached in practice. There are other tools that you can run to determine the code coverage at run time, as the product is p...
Anyone know of a decent C99 fenv.h implementation for MS compilers? I imagine this wouldn't be difficult to do; I'm just looking to save some time.
I don't know of any implementations and I doubt any exists. Although Visual Studio has the_controlfp()function and a number of related preprocessor pragma's (float_control(),fenv_access(),fp_contract(), I don't think you can use them to create a conformingfenv.himplementation. Sad as it is, Visual Studio is not a C99...
my code is a mix up of different bits and pieces from older code. I would like to erase all never used functions in order to keep the code simple. Is Klocwork the tool? How do I do it? Thanks, Moshe.
You could use the-por-pgoptions togccto cause code to be added to the prologue and epilogue of every function so that a profile database is written when the program executes. The toolprofis used to analyze the output from-pandgproffor -pg. These tools produce reports showing what functions were used, how many calls, a...
I got a situation where the client got 'C' program which does encryption of columns at client application side. And the same is now to be used in DataWarehousing project in one of the script component which supports C#. Is there a way this C program can be compiled to dll and imported into C# [or] do we need to re-w...
If the client's code is already in a DLL, you can use all routines from it using P\Invoke in C#. Here is atutorial.
This question already has answers here:Compilation error: stray ‘\302’ in program, etc(12 answers)Closed8 months ago. I am working on a simple project in Objective-C in Xcode, and I'm getting some stray/ errors about the following line of code: ``` if(celsius < −273.15) { NSLog(@"It is impossible to convert temp...
− != - Your minus, isn't a minus.
What does the address in a pointer refer to, real address location in main memory or virtual address. Can it be configured. And if it refers to virtual address , does Memory manager needs to convert this address to real address everytime it is accessed
This depends on your system and OS. For a typical windows/linux user space application, the address is a virtual memory address. User space applications have no way of accessing the memory using physical addresses - that's one of the abstractions the OS gives each process. The MMU(Memory management unit) does this t...
How do I call the lstat system call in linux/c, not the lstat wrapper around it (lstat(3))? There is no SYS_lstat for syscall(SYS_lstat...
If you're using the syscall directly, you need to make sure your definition ofstruct statand the kernel's definition agree. Also if you're on a 32-bit machine you should probably never use the deprecatedlstatsyscall but instead thelstat64one, since the former will fail on large files. These and numerous other issues a...
Is there any method to remove the duplicate elements in an array in place in C/C++ in O(n)? Suppose elements area[5]={1,2,2,3,4}then resulting array should contain{1,2,3,4}The solution can be achieved using two for loops but that would be O(n^2) I believe.
If, and only if, the source array is sorted, this can be done in linear time: ``` std::unique(a, a + 5); //Returns a pointer to the new logical end of a. ``` Otherwise you'll have to sort first, which is (99.999% of the time)n lg n.
``` char *names[] = { [3] = "foo", [1] = "bar", [0] = "man"}; int i; for (i=0; i<sizeof(names)/sizeof(char); i++) { puts(names[i]); } ``` What are the function of the brackets in the above declaration? Also, why does the resulting loop iterate 3 times instead of 4 and produce this outpu...
The following definition shows how you can use designated initializers to skip over elements of the array that you don't want to initialize explicitly: ``` static int number[3] = { [0] = 5, [2] = 7 }; ``` The array number contains the following values: number[0] is 5; number[1] is implicitly initialized to 0; number...
i tried with the following code , but i can't understand why it's giving me wrong answer. i am computing the 2's complement and adding with another no. ``` #include <stdio.h> int add(int a, int b) { while (a) { a = (a & b) << 1; b = a^b; } return b; } int sub(int a, int b) // add a with ...
i used a different add() function as suggested by NullUserException, it works now: ``` int add(int a,int b) { int x; x = a^b; while(a&b) { b = ((a&b)<<1); a = x; x = a^b; //b=(a^b); } return x; } ```
I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here
Consider using achar. Yeah, it's 8-bits, but you can use the bit shift operators (<<and>>) to store values in the other 4 bits. Edit:Per the comments below, anunsigned charis, in fact, preferable overcharto avoid issues with the sign bit.
I need to port an existing game written for the iPhone to Flash. The iPhone game is mainly written in pure C rather than Objective C. I'm wondering if there are any good tools for converting the C code to Actionscript directly, or in general if anyone has some advice on how to do this porting in an efficient way give...
Take a look atAlchemy. This might be what you want, but I suspect you will have issues simply compiling on different compilers since the user-input differs immensely between a flash game and an iphone game.
I am writing a C UNIX program that is threaded and shares one variable across all threads. What would be the easiest way to acquire a lock on this variable? I can't find any small libraries just for locking in UNIX. Any suggestions how to do this? Thanks, Boda Cydo.
There'spthread_mutex_lock, if you're already using pthreads. Quick example, wherecounteris the shared variable andmutexis a mutex variable of typepthread_mutex_t: ``` /* Function C */ void functionC() { pthread_mutex_lock( &mutex ); counter++; pthread_mutex_unlock( &mutex ); } ```
I'm trying to call an objective-C function from a C function but the code keeps crashing in objc_msgSend. My objective-C class is a singleton and I'm using the following code. ``` void c_function(int arg0, const char *arg1) { [[objc_class instance] testFunction:arg0 Arg1:arg1]; } ``` The gdb shows the cras...
There's nothing wrong with your code as there are no special rules for calling objc methods from c functions. If there is a crash in objc_msgSend, then refer tohttp://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html. The same thing would have happened if the objc line w...
Can a process 'foo' write to file descriptor 3, for example, in such a way that inside a bash shell one can do ``` foo 1>f1 2>f2 3>f3 ``` and if so how would you write it (in C)?
You can start your command with: ``` ./foo 2>/dev/null 3>file1 4>file2 ``` Then if you ls -l /proc/_pid_of_foo_/fd you will see that file descriptors are created, and you can write to them via eg.: ``` write(3,"abc\n",4); ``` It would be less hacky perhaps if you checked the file descriptor first (with fcntl?).
I wrote a program in python (using standard python libraries) long ago. Now I need to write the same program in standard C due to the lack of python support for that device. Please suggest me programs or conversion method to convert that python code into C code. Thanks in advance.
Shedskincould do the trick: Shed Skin is an experimental compiler, that can translate pure, but implicitly statically typed Python programs into optimized C++. It can generate stand-alone programs or extension modules that can be imported and used in larger Python programs.
What does the address in a pointer refer to, real address location in main memory or virtual address. Can it be configured. And if it refers to virtual address , does Memory manager needs to convert this address to real address everytime it is accessed
This depends on your system and OS. For a typical windows/linux user space application, the address is a virtual memory address. User space applications have no way of accessing the memory using physical addresses - that's one of the abstractions the OS gives each process. The MMU(Memory management unit) does this t...
How do I call the lstat system call in linux/c, not the lstat wrapper around it (lstat(3))? There is no SYS_lstat for syscall(SYS_lstat...
If you're using the syscall directly, you need to make sure your definition ofstruct statand the kernel's definition agree. Also if you're on a 32-bit machine you should probably never use the deprecatedlstatsyscall but instead thelstat64one, since the former will fail on large files. These and numerous other issues a...
Is there any method to remove the duplicate elements in an array in place in C/C++ in O(n)? Suppose elements area[5]={1,2,2,3,4}then resulting array should contain{1,2,3,4}The solution can be achieved using two for loops but that would be O(n^2) I believe.
If, and only if, the source array is sorted, this can be done in linear time: ``` std::unique(a, a + 5); //Returns a pointer to the new logical end of a. ``` Otherwise you'll have to sort first, which is (99.999% of the time)n lg n.
``` char *names[] = { [3] = "foo", [1] = "bar", [0] = "man"}; int i; for (i=0; i<sizeof(names)/sizeof(char); i++) { puts(names[i]); } ``` What are the function of the brackets in the above declaration? Also, why does the resulting loop iterate 3 times instead of 4 and produce this outpu...
The following definition shows how you can use designated initializers to skip over elements of the array that you don't want to initialize explicitly: ``` static int number[3] = { [0] = 5, [2] = 7 }; ``` The array number contains the following values: number[0] is 5; number[1] is implicitly initialized to 0; number...
i tried with the following code , but i can't understand why it's giving me wrong answer. i am computing the 2's complement and adding with another no. ``` #include <stdio.h> int add(int a, int b) { while (a) { a = (a & b) << 1; b = a^b; } return b; } int sub(int a, int b) // add a with ...
i used a different add() function as suggested by NullUserException, it works now: ``` int add(int a,int b) { int x; x = a^b; while(a&b) { b = ((a&b)<<1); a = x; x = a^b; //b=(a^b); } return x; } ```
I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here
Consider using achar. Yeah, it's 8-bits, but you can use the bit shift operators (<<and>>) to store values in the other 4 bits. Edit:Per the comments below, anunsigned charis, in fact, preferable overcharto avoid issues with the sign bit.
I need to port an existing game written for the iPhone to Flash. The iPhone game is mainly written in pure C rather than Objective C. I'm wondering if there are any good tools for converting the C code to Actionscript directly, or in general if anyone has some advice on how to do this porting in an efficient way give...
Take a look atAlchemy. This might be what you want, but I suspect you will have issues simply compiling on different compilers since the user-input differs immensely between a flash game and an iphone game.
I am writing a C UNIX program that is threaded and shares one variable across all threads. What would be the easiest way to acquire a lock on this variable? I can't find any small libraries just for locking in UNIX. Any suggestions how to do this? Thanks, Boda Cydo.
There'spthread_mutex_lock, if you're already using pthreads. Quick example, wherecounteris the shared variable andmutexis a mutex variable of typepthread_mutex_t: ``` /* Function C */ void functionC() { pthread_mutex_lock( &mutex ); counter++; pthread_mutex_unlock( &mutex ); } ```
I'm trying to call an objective-C function from a C function but the code keeps crashing in objc_msgSend. My objective-C class is a singleton and I'm using the following code. ``` void c_function(int arg0, const char *arg1) { [[objc_class instance] testFunction:arg0 Arg1:arg1]; } ``` The gdb shows the cras...
There's nothing wrong with your code as there are no special rules for calling objc methods from c functions. If there is a crash in objc_msgSend, then refer tohttp://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html. The same thing would have happened if the objc line w...
``` char *names[] = { [3] = "foo", [1] = "bar", [0] = "man"}; int i; for (i=0; i<sizeof(names)/sizeof(char); i++) { puts(names[i]); } ``` What are the function of the brackets in the above declaration? Also, why does the resulting loop iterate 3 times instead of 4 and produce this outpu...
The following definition shows how you can use designated initializers to skip over elements of the array that you don't want to initialize explicitly: ``` static int number[3] = { [0] = 5, [2] = 7 }; ``` The array number contains the following values: number[0] is 5; number[1] is implicitly initialized to 0; number...
i tried with the following code , but i can't understand why it's giving me wrong answer. i am computing the 2's complement and adding with another no. ``` #include <stdio.h> int add(int a, int b) { while (a) { a = (a & b) << 1; b = a^b; } return b; } int sub(int a, int b) // add a with ...
i used a different add() function as suggested by NullUserException, it works now: ``` int add(int a,int b) { int x; x = a^b; while(a&b) { b = ((a&b)<<1); a = x; x = a^b; //b=(a^b); } return x; } ```
I need to store a value between 0-15 in C , 4 bits are enough for this. How can I just have a variable of 4 bits? Space is a constraint here
Consider using achar. Yeah, it's 8-bits, but you can use the bit shift operators (<<and>>) to store values in the other 4 bits. Edit:Per the comments below, anunsigned charis, in fact, preferable overcharto avoid issues with the sign bit.
I need to port an existing game written for the iPhone to Flash. The iPhone game is mainly written in pure C rather than Objective C. I'm wondering if there are any good tools for converting the C code to Actionscript directly, or in general if anyone has some advice on how to do this porting in an efficient way give...
Take a look atAlchemy. This might be what you want, but I suspect you will have issues simply compiling on different compilers since the user-input differs immensely between a flash game and an iphone game.
I am writing a C UNIX program that is threaded and shares one variable across all threads. What would be the easiest way to acquire a lock on this variable? I can't find any small libraries just for locking in UNIX. Any suggestions how to do this? Thanks, Boda Cydo.
There'spthread_mutex_lock, if you're already using pthreads. Quick example, wherecounteris the shared variable andmutexis a mutex variable of typepthread_mutex_t: ``` /* Function C */ void functionC() { pthread_mutex_lock( &mutex ); counter++; pthread_mutex_unlock( &mutex ); } ```
I'm trying to call an objective-C function from a C function but the code keeps crashing in objc_msgSend. My objective-C class is a singleton and I'm using the following code. ``` void c_function(int arg0, const char *arg1) { [[objc_class instance] testFunction:arg0 Arg1:arg1]; } ``` The gdb shows the cras...
There's nothing wrong with your code as there are no special rules for calling objc methods from c functions. If there is a crash in objc_msgSend, then refer tohttp://www.sealiesoftware.com/blog/archive/2008/09/22/objc_explain_So_you_crashed_in_objc_msgSend.html. The same thing would have happened if the objc line w...
Can a process 'foo' write to file descriptor 3, for example, in such a way that inside a bash shell one can do ``` foo 1>f1 2>f2 3>f3 ``` and if so how would you write it (in C)?
You can start your command with: ``` ./foo 2>/dev/null 3>file1 4>file2 ``` Then if you ls -l /proc/_pid_of_foo_/fd you will see that file descriptors are created, and you can write to them via eg.: ``` write(3,"abc\n",4); ``` It would be less hacky perhaps if you checked the file descriptor first (with fcntl?).
I have a function, foo(), that allocates memory and returns it. Is it standard practice for me to free it at the end of my main function? ``` char* foo(){ char * p; p = malloc(sizeof(char) * 4); /* edit - thanks to msg board */ p[0] = 'a'; p[1] = 'b'; p[2] = 'c'; p[3] = '/0'; /* edit: thanks to the msg board. ...
Freeing at the end ofmain()would be the correct thing to do, yes. You might think about null terminating that string, though. A more idiomatic design is do to all the memory management "at the same level", so to speak. Something like: ``` void foo(char *p) { p[0] = 'a'; p[1] = 'b'; p[2] = 'c'; p[3] = '\0';...
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed13 years ago.Improve this question I'm trying to figure out how to do this. Essentially I have points A and B which I know the location of. I then have point...
D = C ± (B-A) / |B-A| * |C-D| If B=A there is no solution as the line AB degenerates to a point and parallelety of a line to a point is not defined. Explanation (B-A) / |B-A| is a direction vector of unit length. Multiplication by the length |C-D| results in the proper offset vector. Edits: changed + to ± to provi...
I have looked at some resources to tell me how->and.are different, but they seem to do the same thing. Does->act like a dot operator on a struct?
.is used when you have a struct, and->is used when you have a pointer to a struct. The arrow is a short form for dereferencing the pointer and then using.:p->fieldis the same as(*p).field.
I have some difficulties grasping some concepts. Grateful for help. Let's say you have the following piece of code: ``` int *intPtr; // creates a pointer int count = 10; // initiates an intiger variable intptr = &count; // ?? ``` The&operator gives the address to a variable, in this case the integercount. The add...
count refers to the VALUE of the variable. You don't want to assign the value of count to intptr, you want to assign the address of count. Thus the & operator is used. If you do intptr = count, you'd be pointing to memory address 10 in this case, which is sure to be in system memory, not your application memory and...
I have the following code: ``` NSInteger index1 = (stop.timeIndex - 1); //This will be -1 index1 = index1 % [stop.schedule count]; // [stop.schedule count] = 33 ``` So I have the expression -1 % 33. This should give me 32, but is instead giving me 3... I've double checked the values in the debugger. Does anyone ha...
In C, the modulus operator doesn't work with negative numbers. (It gives a remainder, rather than doing modular arithmetic as its common name suggests.)
This question already has answers here:How can I suppress "unused parameter" warnings in C?(13 answers)Closed4 years ago.The community reviewed whether to reopen this question6 months agoand left it closed:Original close reason(s) were not resolved What is the best/neatest way to suppress a C compiler (for example GC...
(void) variablemight work for some compilers. For C++ code, also seeMailbag: Shutting up compiler warningswhere Herb Sutter recommends using: ``` template<class T> void ignore( const T& ) { } ... ignore(variable); ```
I have looked after, without luck, a free C/C++ API for Windows that can be used in a project I am about to start. There are libraries for Java and C# but the fact is there is no one for C/C++. I need an API that can be integrated in a vs project and we cannot use libraries that run in servers ( as CGI scripts or what...
if you want to generate QRcodes have a look atlibqrencodeit works with cygwin on windows (not sure about VS). If you want to decode QRcodes have a look atzxing
I am trying to overload some operators: ``` /* Typedef is required for operators */ typedef int Colour; /* Operators */ Colour operator+(Colour colour1, Colour colour2); Colour operator-(Colour colour1, Colour colour2); Colour operator*(Colour colour1, Colour colour2); Colour operator/(Colour colour1, Colour colour2...
C does not support operator overloading (beyond what it built into the language).
Is there a way to set environment variables in Linux using C? I triedsetenv()andputenv(), but they don't seem to be working for me.
I'm going to make a wild guess here, but the normal reason that these functions appear to not work is not because they don't work, but because the user doesn't really understand how environment variables work. For example, if I have this program: ``` int main(int argc, char **argv) { putenv("SomeVariable=SomeValue...
as in the title, it doesn't appear to generate an event unless another key/button is pressed at the same time. thanks, james
Running xev and pressing shift gives me this: ``` KeyPress event, serial 34, synthetic NO, window 0x5a00001, root 0xf7, subw 0x0, time 1739516541, (174,173), root:(1021,367), state 0x10, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: ...
I was reading the jemalloc's realloc function and noticed that all the non-static functions(at least the ones I've seen) in jemalloc is wrapped with JEMALLOC_P macro and JEMALLOC_P is: #define JEMALLOC_P(s) s Why would they need such a thing?
From the jemallocconfigurescript: ``` AC_DEFINE_UNQUOTED([JEMALLOC_P(string_that_no_one_should_want_to_use_as_a_jemalloc_API_prefix)], [${JEMALLOC_PREFIX}##string_that_no_one_should_want_to_use_as_a_jemalloc_API_prefix]) ``` I'd guess that it is intended to provide a prefix for all of the jemalloc functions. You'll...
Okay, this one seems to me a bit weird. Any help would be greatly appreciated. I recently implemented code that I foundhereto get the MAC address. The funny thing is that is prints to the console (in addition to the MAC address) something like the following: ``` <CFData 0x317df0 [0xa03e9ee0]>{length = 6, capacity = ...
The culprit is line 185 ofGetPrimaryMACAddress.c: ``` CFShow(MACAddressAsCFData); // for display purposes only; [...] ``` Remove this line and that extra output tostderrgoes away.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Have a look atAStyle. It's a command line based formatter/beautifier. It doesn't handle Fortran though it works with C, C++, C# and Java
Where can I find an A* implementation in C? I was looking around but it seems my google-fu is not strong enough. I've started writing my own implementation, but then I remembered Stack Overflow and I thought I should ask here first. It seems a bit complicated to write arealA* implementation - I was tempted to just wr...
Your google-fu is indeed weak, young padawan :-) Try googling forastar c. Thefirstandsecondlinks are actual code implementations (the first under a liberal MIT licence, no idea about the second).
how do I do this in C#? ``` int a,b,c; sscanf(astring,"%d %d %d",&a,&b,&c); ``` minimal code and dependencies is preferable, is there some built in regex stuff? I'm using c# 4.0
If like scannf you are willing to assume that users will give completely correct data then you can do the following. ``` string astring = ...; string[] values = astring.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); int a = Int32.Parse(values[0]); int b = Int32.Parse(values[1]); int c = Int32.Parse(v...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
OpenSceneGraphhas a GLU style tesselator, seehttp://www.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00854.html#_detailsfor details. Visualization Libraryalso provides a tesselator, seehttp://www.visualizationlibrary.com/documentation/classvl_1_1_tessellator.htmlfor further information. Both librari...
This question already has answers here:float to int unexpected behaviour(6 answers)Closed6 years ago. What will be the behavior and output of the following code if i accidentally code so in C/C++, ``` float a = 12.5; printf("%d\n", a); printf("%d\n", *(int *)&a); ```
Rubish and more rubish. You would get something meaningful if you did the following though ``` printf("%d\n", (int)a); ```
This question already has answers here:Closed13 years ago. Possible Duplicate:Why is this C code causing a segmentation fault? ``` char* string = "abcd"; ``` now when i try to change some character of this string i get segmentation fault ``` *string = 'p'; ``` or ``` string[0] = 'p'; string[0] = 52; ``` Can som...
If you writechar* string = "abcd";the string "abcd" is stocked into the static data part of your memory and you can't modify it. And if ou writechar* string = 'p';, that's just wrong. First, you try to declare a variable with the same name (string) and, worse, you try to assign a char value to a char pointer variable...
I want to write a cross-plattform wrapper for some OS specific (Linux/MacOSX/Windows) calls to get the number of cores of the CPU etc. My idea was to put all of them in single functions with static variables, so stuff like the number of cores that does not change will be processed only once. ``` int getNumCPUCores() ...
Anintis a handful of bytes (four or eight on most modern platforms). Unless you have millions of static variables or static variables of some really huge type, you don't need to worry about it.
Is there a free way to statically link a dll? I've tried dll to lib but $999 is too expensive. What are alternatives since I want to have 1 nice exe instead of 1 exe + 1 DLL. Thanks
I'm not certain it can even be done. There are some issues that would need to be treated very delicately. Resources in the DLL? LIB files wouldn't hold those, so you'd have to export them as well and then reintegrate them into the final EXEWho calls DLLMain, and when? Lou Franco's idea would skirt all of those issue...
Is it better to have lots of DLL dependencies or better to static link as mich as possible? Thanks
No, it is not bad practice to ship with lots of DLLs; it is bad practice, though, to put them in %System32%. Actually, it is usually good to use DLLs instead of statically linking; for one thing, you can easily swap out just the DLL that you need to update, rather than having to replace the entire binary, and for anot...
I am stuck with the problems like, reading text from a specific location (x=10, y=5) on the console window. Where can I find a detail tutorial on Win32 API Console mode programming in C?
You'd need to use ReadConsoleOutput(). Beware of the ambiguity in a coordinate like (10, 5). It could be relative from the console window upper-left corner. Or from the screen buffer. You'd probably need to make the buffer size the same as the window size to avoid this. SetConsoleScreenBufferSize(). These consol...
Normally, if a pointer is freed twice, it's a double free. For example, ``` char *ptr; ptr=malloc(5 * sizeof(*ptr)); free(ptr); free(ptr); ``` The above code is considered as double free. Is the following considered as double free as well? ``` char *ptr; char *ptr1; ptr=malloc(5 * sizeof(*ptr)); ptr1=ptr; free(ptr)...
Yes. The library doesn't care what name you gave a varaible in your source code (it's long gone by the time the code is executed). All that matters is the value, and in this case the values passed tofree()would be the same.
In OSX, I'm used to simply doing ``` ./configure make ``` But in MSVC when I do Project from existing code and try to compile I get hundreds of errors. I'm trying to compile GLU from the Mesa3D library. How could I do this in MSVC? Thanks
Still fighting with glu ? :) In windows\VC8\mesa you have a .sln. Find it, open it, compile it, done.
Are there macros or builtins that can return the length of arrays at compile time in GCC? For example: ``` int array[10]; ``` For which: ``` sizeof(array) == 40 ???(array) == 10 ``` Update0 I might just point out that doing this in C++ is trivial. One can build a template that returns the number inside[]. I was ...
``` (sizeof(array)/sizeof(array[0])) ``` Or as a macro ``` #define ARRAY_SIZE(foo) (sizeof(foo)/sizeof(foo[0])) int array[10]; printf("%d %d\n", sizeof(array), ARRAY_SIZE(array)); 40 10 ``` Caution: You can apply thisARRAY_SIZE()macro to a pointer to an array and get a garbage value without any compiler w...
I have read that use ofstrlenis more expensive than such testing like this: We have a stringx100 characters long. I think that ``` for (int i = 0; i < strlen(x); i++) ``` is more expensive than this code: ``` for (int i = 0; x[i] != '\0'; i++) ``` Is it true? Maybe the second code will not work in some situation...
``` for (int i=0;i<strlen(x);i++) ``` This code is callingstrlen(x)every iteration. So ifxis length 100,strlen(x)will be called 100 times. This is very expensive. Also,strlen(x)is also iterating overxevery time in the same way that your for loop does. This makes it O(n^2) complexity. ``` for (int i=0;x[i]!='\0';i++)...
is it possible to program a tool that sends music to iPhone/iPod without putting the songs in iTunes? the tool can work with "iTunes SDK" andit is not attended to go against Apple rules the idea is to not "cache" the songs as iTunes in libraryes, just upload it directly to the iPhone/iPod from file server this help ...
Yes, there is a way to achieve that - a player called MediaMonkey does that. I seem to remember that still requires iTunes to be installed on the machine, but you never need to add your tracks to iTunes after installing it. As tohowit's done - that I don't know, but the MediaMonkey guys might be willing to share.
It is possible to fetch the zend resources (zend_fetch_resource) without knowing the type of the fetching resource? If so, how? Note: I am writing PHP extension.
Yes, you can. zend_fetch_resourcewon't work because it receives the the types of resources that are acceptable and fails if the found one is not one of those. Just use ``` void *zend_list_find(int id, int *type); ``` From the resource zval you can extract the id withZ_RESVAL(zval). The argumenttypewill be filled w...
How can compile-time static asserts be implemented in C (not C++), with particular emphasis on GCC?
C11 standard adds the_Static_assertkeyword. This isimplemented since gcc-4.6: ``` _Static_assert (0, "assert1"); /* { dg-error "static assertion failed: \"assert1\"" } */ ``` The first slot needs to be an integral constant expression. The second slot is a constant string literal which can be long (_Static_assert(0...
I came across this code in Stephen G Kochan's book, Programming in c. Is this possible? ``` float absolute_value(x) float x; { ----- ----- } ``` So, as you can see, the argument x is declared after it's used it the method arguments. This throws an obvious compilation error in G++. So, which C compiler support...
That's the old style K&R format. It's not actually declaring the argumentx, rather defining its type. By default, things wereintunless otherwise specified. Back when C was a much simpler language, not that far removed from my beloved BCPL, this was how you gave function arguments their types. None of these prototype ...
I'm using GLUTess to tesselate polygons. Sometimes it crashes with a null pointer issue and I have no way of knowing why since I just link to glu32.lib . Is there a way to see the source and get the exact line it crashes on? Thanks
Is there a way to see the source and get the exact line it crashes on? You can build program on linux. If issue persists, AND if corresponding *.so contains debugging info (and if you have source code in your distribution), then you'll be able to find line number. Do not expect source of glu to be easy to understand,...
I would like to develop a bot for Empathy, but I don't know how to get started. I've read the Telepathy wiki, but I think it's very bad documented, does anybody know any nice tutorial? Better if it uses Python or C bindings. Thank you.
You should check the telepathy-python repository's examples directory. They have quite a few listed there:http://git.collabora.co.uk/?p=telepathy-python.git;a=tree;f=examples;h=8cede34dfe79d02dc5ce229bd2aa97934f3587c1;hb=HEAD I also found this PDF that shows some examples with VoIP:http://raphael.slinckx.net/files/te...
Is there a way to round floating points to 2 points? E.g.:3576.7675745342556becomes3576.76.
``` round(x * 100) / 100.0 ``` If you must keep things floats: ``` roundf(x * 100) / 100.0 ``` Flexible version using standard library functions: ``` double GetFloatPrecision(double value, double precision) { return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision)); } ```
Would a very small/simple command line program, programmed in standards compliant C99, and statically compiled on FreeBSD work if executed on Linux ? (I would test this myself but I do not currently have a separate HDD to test on Linux.)
No, not in general, because the syscall interface is different. However, FreeBSD has a good Linux compatibility layer where you can run Linux binaries (that are compiled against the Linux syscall interface) on FreeBSD. There is such a layer available for both i386 and amd64 binaries. SeeChapter 10: Linux Binary Compa...
The expected output of the following C program is to print the array elements. But when actually run, it doesn't do so. ``` #include<stdio.h> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main() { int d; for(d=-1;d <= (TOTAL_ELEMENTS-2);d++) p...
TOTAL_ELEMENTSis unsigned. -1, when converted to unsigned, is a really huge number, which is not less than 6. Thus, your loop never runs.
I found out that the following code gets accepted by Visual C++ 2008 and GCC 4.3 compilers: ``` void foo() { } void bar() { return foo(); } ``` I am a bit surprised that it compiles. Is this a language feature or is it a bug in the compilers? What do the C/C++ standards say about this?
It's a language feature of C++ C++ (ISO 14882:2003) 6.6.3/3 A return statement with an expression of type “cv void” can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller. C (ISO 9899:1999) 6.8.6.4/1 A return statement with an express...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Take a look atMPI.
It's common for compilers to provide aswitch to warn when code is unreachable. I've also seen macros for some libraries, that provideassertions for unreachable code. Is there a hint, such as through a pragma, or builtin that I can pass to GCC (or any other compilers for that matter), that will warn or error during co...
gcc 4.5 supports the__builtin_unreachable()compiler inline, combining this with-Wunreachable-codemight do what you want, but will probably cause spurious warnings
How do I define macros on a per-project, or per file level in a C project using autotools? Presently I have this:mount_cpfs_CPPFLAGS = -DFUSE_USE_VERSION=28, but I'm not sure that this is the "portable" way to define a C macro.
Consider using generated header files withAC_DEFINE.
I have my own, very fast cos function: ``` float sine(float x) { const float B = 4/pi; const float C = -4/(pi*pi); float y = B * x + C * x * abs(x); // const float Q = 0.775; const float P = 0.225; y = P * (y * abs(y) - y) + y; // Q * y + P * y * abs(y) return y; } float cosine(fl...
A simple cubic approximation, the Lagrange polynomial for x ∈ {-1, -½, 0, ½, 1}, is: ``` double acos(x) { return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966; } ``` It has a maximum error of about 0.18 rad.
I'm working on implementing bezier handles into my application. I have points and I need to figure out weather the current direction of the new point is clockwise or counter clockwise. This is because my bezier interpolation algorithm calculates the handles from right to left. Therefore no matter what it interpolates...
You have your original angle, the last known angle (since I'm sure you're redrawing the handle as it's being dragged), and the current angle. I'd take a look at the last known handle angle on the last redraw and compare whether the new angle, relative to that is > 180 degrees or < 180 degrees. If it's 0 - 180 degree...
This applies to several cases in my application: I have 3 or 4 functions that belong together, one is a starting function that creates and frees the required memory structures and calls the other functions as appropriate. The other functions also call themselves repeatedly. Only the starting functions is called from ...
Definitely go for a class here. That's what objects and classes are designed for.
I follow this PJLIB (https://trac.pjsip.org/repos/wiki/Getting-Started/Autoconf). But i cant get this up yet, always its giving undefined reference, can anyone please have a look kindly. Stackoverlow source code gets broken please find from here details:http://gist.github.com/5765529 ``` [sun@example mysip]$ gcc my...
You are not linking with the library. You need something like: ``` gcc myapp.c -lpjlib ``` but exactly what you need I don't know - it will be described in the library's documentation.
I'm using GLUTess to tesselate polygons. Sometimes it crashes with a null pointer issue and I have no way of knowing why since I just link to glu32.lib . Is there a way to see the source and get the exact line it crashes on? Thanks
Is there a way to see the source and get the exact line it crashes on? You can build program on linux. If issue persists, AND if corresponding *.so contains debugging info (and if you have source code in your distribution), then you'll be able to find line number. Do not expect source of glu to be easy to understand,...
I would like to develop a bot for Empathy, but I don't know how to get started. I've read the Telepathy wiki, but I think it's very bad documented, does anybody know any nice tutorial? Better if it uses Python or C bindings. Thank you.
You should check the telepathy-python repository's examples directory. They have quite a few listed there:http://git.collabora.co.uk/?p=telepathy-python.git;a=tree;f=examples;h=8cede34dfe79d02dc5ce229bd2aa97934f3587c1;hb=HEAD I also found this PDF that shows some examples with VoIP:http://raphael.slinckx.net/files/te...
Is there a way to round floating points to 2 points? E.g.:3576.7675745342556becomes3576.76.
``` round(x * 100) / 100.0 ``` If you must keep things floats: ``` roundf(x * 100) / 100.0 ``` Flexible version using standard library functions: ``` double GetFloatPrecision(double value, double precision) { return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision)); } ```
Would a very small/simple command line program, programmed in standards compliant C99, and statically compiled on FreeBSD work if executed on Linux ? (I would test this myself but I do not currently have a separate HDD to test on Linux.)
No, not in general, because the syscall interface is different. However, FreeBSD has a good Linux compatibility layer where you can run Linux binaries (that are compiled against the Linux syscall interface) on FreeBSD. There is such a layer available for both i386 and amd64 binaries. SeeChapter 10: Linux Binary Compa...
The expected output of the following C program is to print the array elements. But when actually run, it doesn't do so. ``` #include<stdio.h> #define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0])) int array[] = {23,34,12,17,204,99,16}; int main() { int d; for(d=-1;d <= (TOTAL_ELEMENTS-2);d++) p...
TOTAL_ELEMENTSis unsigned. -1, when converted to unsigned, is a really huge number, which is not less than 6. Thus, your loop never runs.
I found out that the following code gets accepted by Visual C++ 2008 and GCC 4.3 compilers: ``` void foo() { } void bar() { return foo(); } ``` I am a bit surprised that it compiles. Is this a language feature or is it a bug in the compilers? What do the C/C++ standards say about this?
It's a language feature of C++ C++ (ISO 14882:2003) 6.6.3/3 A return statement with an expression of type “cv void” can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller. C (ISO 9899:1999) 6.8.6.4/1 A return statement with an express...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Take a look atMPI.