question
stringlengths
25
894
answer
stringlengths
4
863
Is there a canonical colorspace conversion library? I can't find any pre-existing solutions. Is CIELab conversion is too obscure?
It is not obscure, I have done it myself recently from RGB to CIELAB. Look at the source of OpenCV there is a lot of color convesrion functions. File is: ../src/cv/cvcolor.cpp Have a look at the function icvBGRx2Lab_32f_CnC3R for example. This is probably what are you looking for.
I have a c program which I can launch at command prompt. Is it possible for me the lunch this application in my another c program? If yes, how? All the google result shows me how to do that using pthread? Will that work? I suspect that I need a new process for my c program. Thank you.
It is system specific, but there is commonlyexecveor something like that and there is alwayssystem("/path/to/program");that you can use that is also system specific
I have a string"14 22 33 48". I need to insert each of the values in the string into the respective location in the array: ``` int matrix[5]; ``` so that ``` matrix[0] = 14; matrix[1] = 22; matrix[2] = 33; matrix[3] = 48; ``` How do I do this?
You can usesscanf: ``` sscanf(val, "%d %d %d %d", &matrix[0], &matrix[1], &matrix[2], &matrix[3] ); ```
I am having some problems writing to a file in unicode inside my c program. I am trying to write a unicode Japanese string to a file. When I go to check the file though it is empty. If I try a non-unicode string it works just fine. What am I doing wrong? ``` setlocale(LC_CTYPE, ""); FILE* f; f = _wfopen(COMMON_FILE_P...
You might need to add the encoding to the mode. Possibly this: ``` f = _wfopen(COMMON_FILE_PATH,L"w, ccs=UTF-16LE"); ```
Changing a Linux C++ program which gives the user limited file access. Thus the programchrootsitself to a sandbox with the files the user can get at. All worked well. Now, however, the program needs to access some files for its own needs (notthe user's) but they are outside the sandbox. I know chroot allows access...
Copy them into the sandbox or open them all beforechrooting. Seriously. If there was a way to do this, there would be a way to suborn it to allow other access and make your protection useless. The whole point of the sandbox is to prevent exactly what you're trying to achieve.
I have two variables: ``` char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE"; ``` I want to check if these two are equal... usingcharTime == bufdoesn't work. What should I use, and can someone explain why using==doesn't work? Would this action be different in C and C++?
``` char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE"; ``` C++andC(removestd::for C): ``` bool equal = (std::strcmp(charTime, buf) == 0); ``` But the true C++ way: ``` std::string charTime = "TIME", buf = "SOMETHINGELSE"; bool equal = (charTime == buf); ``` Using==does not work because it tries to compare th...
Can we use thewmain()function with Unix compilers or it'll work only on/for Windows?
The only standard signatures formainare: ``` int main(void); int main(int argc, char *argv[]); ``` However, a freestanding implementation can provide extensions/allow other signatures. But those are not guranteed to be portable.wmainlooks like a Windows/VS thing. There's not much chance this will work on a *nix/GNU ...
So I have some class starting with ``` #include <wchar.h> #include <stdlib.h> ``` and there is awmainfunction . How is it different from main function i usually use in my C/C++ programs?
"If your code adheres to the Unicode programming model, you can use the wide-character version of main, which is wmain." http://msdn.microsoft.com/en-us/library/aa299386%28VS.60%29.aspx ``` main( int argc, char *argv[ ], char *envp[ ] ) { program-statements } wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] ) { ...
i got a question about unsigned char array. How can i store an integer in the array continually? for example, i need to store 01011 to the array first. Then i need to store 101, how can i stored as 01011101 in the array? thanks for your help!
Store 01011 first. You'll get value 00001011. Then when you want to store three more bits, perform a left shift by three positions (you'll get 01011000) and make OR with 00000101, you'll get 01011101. However, doing it this way you have to know definitely that you had only five bits filled after first assignment.
Is there an option to enable the drop down menu that appears when coding in other languages such as html/vb/ect for C in Visual Studio?
You can press Ctrl+Space to produce this menu. For example, after typing "pri", press Ctrl+Space, if you're looking for printf().
i have heard from a friend of mine that the best algorithm for swapping is " (a^=b^=a^=b)" where a and b are two integers to be swapped. but when i applied this using c language it resulted in crashing. can anyone of you fine people explain the possible reason for that? please suggest the best algorithm for swapping....
this swapping trick is sometimes dangerous, I have seen a a wrong quicksort program using this swap generates wrong results. But a usual swap generates correct program. Respect to speed, the compiler sometimes generates faster code if we use a tmp variable. usetmp = a; a = b; b = tmp;
Using my c++ program how can I find out what group the current user running my program belongs to? So my program need to figure out a couple of things : The current username of the userThe group the user belongs to How can do the above 2 using c++ on a RedHat / Linux machine?
Withgetuid(2)andgetgid(2). Seecredentials(7)for more information. Usegetpwuid(3)andgetgrgid(3)for the names.
I'm trying to make a little console application that is able to deal with keystrokes as events. What I need is mostly the ability to get the keystrokes and be able to do something with them without dealing with the typical stdin reading functions. I tried to check the code of programs like mplayer, which implement th...
You could use the ncurses family of functions 'getch' as shown in the link, here's anotherlinkthat will be of help to you, by the way, it should be pointed out, ncurses is platform portable so you should be pretty ok with it if you decide to re-target to another platform which is a big plus...
I'm trying to detect "Use after free()" bugs, otherwise known as "Dangling pointers". I know Valgrind can be used to detect "Use after free" bugs on the *nix platform, but what about windows? What if I don't have the source? Is there a better program than Valgrind for detecting all dangling pointers in a progra...
The MSVC debug memory allocator already does this. When you get 0xfeeefeee from a pointer dereference you've dangled. With some luck that will bomb the program.
I have written the majority of my project in C++. However there are several "filters" or folders which need to be compiled as C and linked to the project. How can I configure this within VStudio? Thanks.
You can change the Language property by right-clicking on the individual files and settingConfiguration Properties > C/C++ > Advanced > CompileAs ToCompile As C (/TC). No such facility for the filter are present though.
What was the munch library (or program?) fromcfrontpackage? What is was used for?
Munch was used to scan the nm output and look for static constructors/destructors. See thecode(with comments) atSoftwarePreservation.com.
how can I set themousecursor position in an X window using a C program under Linux? thanks :) (like setcursorpos() in WIN) EDIT: I've tried this code, but doesn't work: ``` #include <curses.h> main(){ move(100, 100); refresh(); } ```
12.4 -Moving the Pointer Although movement of the pointer normallyshouldbe left to the control of the end user, sometimes it is necessary to move the pointer to a new position under program control.To move the pointer to an arbitrary point in a window, useXWarpPointer(). Example: ``` Display *dpy; Windo...
I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program basically chains OpenCV functions, so the main ...
You've answered your own question pretty well. Most of the expensive computations should be within the OpenCV library, and thus independent of the language you use. If you're really concerned about efficiency, you could profile your code and confirm that this is indeed the case. If need be, your custom processing fun...
I want to disable CTRL+ALT+DEL in Windows XP in my ANSI-C code. Is it possible to do it?
First of all, Trapping Ctrl-Alt-Del (Secure Attention Sequence) and disabling it are two different things. Despite misconceptions of many it is possible to disable SAS. Here are 3 ways to do it: Set HKCU/Software/Microsoft/Windows/CurrentVersion/Policies/System/DisableTaskMgr = 1Replace msgina.dll with your own or w...
I am having some problems writing to a file in unicode inside my c program. I am trying to write a unicode Japanese string to a file. When I go to check the file though it is empty. If I try a non-unicode string it works just fine. What am I doing wrong? ``` setlocale(LC_CTYPE, ""); FILE* f; f = _wfopen(COMMON_FILE_P...
You might need to add the encoding to the mode. Possibly this: ``` f = _wfopen(COMMON_FILE_PATH,L"w, ccs=UTF-16LE"); ```
I have a sequence. ``` a1 = 1 - cos(x); ai = a1 + (-1)^(i-1) * x^(2*i-2) / (2*i-2)! ``` I need to write this with and without recursion. But it has a different results.Here is my code:http://codepaste.net/q213q6
I'm going to operate under the assumption that this is homework, if I'm wrong I'll come back and edit this post or repost. Firstly, you should try to write your factorial function in a tail recursive manner. Though it probably won't make much difference in C, it's good practice. ``` int helper( int x, int acc ) { ...
I am writing a program which if I compile on a Suse 10 32-bit system without adding the-m32option and execute it on Suse 10 64-bit, it works fine. In this case, is it not required for me to add the-m32option? Can we execute programs built on 32-bit systems directly on their 64-bit counterparts without any side-effec...
There is no problems in running 32 bits executables on 64 bit OS (as long as 32 bit dynamic libraries are present and found). -m32 is there to compile 32 bits objects on a compiler configured to compile 64 bits objects by default.
When malloc is called, the size is stored adjacent to the allocated block so that free will know how much to free etc (http://c-faq.com/malloc/freesize.html). My question is, Say we have dynamically allocated memory and later in the code we increment the pointer ``` pointer++ ``` And then later, if i call a ``` f...
You need tofree()the same pointer as you received frommalloc(). Incrementing, altering or changing it is undefined behaviour, that is usually a segmentation fault. Think of the pointer you receive as a book from a library. You get home and read it. Afterwards you remove the front page and the book's back and hand it ...
If I want to make an OS X program as self-contained as possible to ease installation, what dynamic libraries can I expect everyone or most people to have? If I know that, I won't have to compile static libraries for everything.
All functions listed inSingle UNIX Specification V3are available. Obviously, all Cocoa frameworks are available as well. The exact contents depend on OS version.
I want to know how and when can I use theexit()function like the program in my book: ``` #include<stdio.h> void main() { int goals; printf("enter number of goals scored"); scanf("%d",&goals); if(goals<=5) goto sos; else { printf("hehe"); exit( ); } sos: pr...
Try usingexit(0);instead. Theexitfunction expects an integer parameter. And don't forget to#include <stdlib.h>.
In my C program I want to know if my executable is run in foreground like this ``` $./a.out ``` or like this ``` $./a.out & ```
If you are the foreground job, ``` getpgrp() == tcgetpgrp(STDOUT_FILENO) ``` orSTDIN_FILENOorSTDERR_FILENOor whichever file descriptor you're attached to your controlling terminal by. (If you're not sure,open("/dev/tty")will always get you a file descriptor to your controlling terminal, if one exists.) This is wha...
I have the following code ``` int main() { int a=6; void *p; p=&a; p++; } ``` Does the void pointer here increment by a particular value (if it is holding the address of any data type) ? In the above casepincrements by 1 even though it is pointing to an integer value. According to me the above code invo...
The code in not valid from standard C point of view. It is illegal to incrementvoid *pointers, or any other pointers toincompletetypes. Your compiler implements it as an extension, which is, of course, non-portable.
gcc 4.4.2 I have the following code: ``` char channels[] = "NumberOfChannel = [2]"; sscanf(channels, "%*[^=]= %d", &chan); ``` I am wondering what this means. As far as I can tell. It is ignoring the equals sign. ``` '^ ignore the character =' ``` Would that be correct? Many thanks,
``` %*[^=] ``` The[^=]means match a string which contains no=.This is aPOSIX extension.The*means discard the matched result. (BTW, to correctly getchanyou needsscanf(channels, "%*[^=]= [%d]", &chan);.)
I have little doubt about string reading in C. string reading functions like gets, scanf, read, fscanf , fgets... which C function can do a secure or safe string reading from any file? Or Which C function can be reliable to read a string in a file ?
An input function will be secure/safe(not allow buffer overflow) if it takes the length of the buffer as an arguments so that the function does not read more char than the buffer can hold. Of the function you've listed fgets() and read() take the buffer length as argument and can be considered safe.
I need to determin the byte size of a file. The coding language is C++ and the code should work with Linux, windows and any other operating system. This implies using standard C or C++ functions/classes. This trivial need has apparently no trivial solution.
Using std's stream you can use: ``` std::ifstream ifile(....); ifile.seekg(0, std::ios_base::end);//seek to end //now get current position as length of file ifile.tellg(); ``` If you deal with write only file (std::ofstream), then methods are some another: ``` ofile.seekp(0, std::ios_base::end); ofile.tellp(); ```
I have a client/server program in TCP written in C, and I would like to secure the exchanged data with OpenSSL, it's quite new for me and I couldn't find examples on the net... Could you point out some googd documentation on this matter please? Thank you!
Check the below links. They should be helpful. http://www.linuxjournal.com/article/4822 http://www.ibm.com/developerworks/linux/library/l-openssl.html Also refer tohttp://www.openssl.org/docs/
I stumbled across this C code today. Can anyone tell me what the 'where' keyword means: ``` *y = sy + exit->y + (where * (entry->y + esy - exit->y)); ``` Edit: Ah.. my bad. It is just a variable name. VC++ highlighted it as though it was a keyword though.
It's just a variable name... (Thewhereis highlighted as blue here only because C# supportswhereas a keyword in LINQ.)
How are file descriptors and file pointers related? When is it appropriate to use each?
A file descriptor is a low-level integer "handle" used to identify an opened file (or socket, or whatever) at the kernel level, in Linux and other Unix-like systems. You pass "naked" file descriptors to actual Unix calls, such asread(),write()and so on. AFILEpointer is a C standard library-level construct, used to r...
I have a dll with following signature in C++. It is working in c++; ``` void Decompress(unsigned char *in,int in_len,unsigned char * out, unsigned *o_len,int *e); ``` Description of parameter *in: It is byte array passed to function.in_len: Length of bytes in first parameter.*out: This would be the output as byte a...
``` static extern void Decompress( byte[] input, int in_len, byte[] output, ref int o_len, out int e); ```
How can I filter a string in c? I want to remove anything that isn't[a-z0-9_]. ``` int main(int argc, char ** argv) { char* name = argv[1]; // remove anything that isn't [a-z0-9_] printf("%s", name); } ```
``` char *src, *dst; for (src = name, dst = name; *src; src++) { if ('a' <= *src && *src <= 'z' || '0' <= *src && *src <= '9' || *src == '_') *dst++ = *src; } *dst = '\0'; ``` EDIT: Multiple small revisions. I hope to have the bugs out now.
I was curious to know how I can round a number to the nearest whole number. For instance, if I had: ``` int a = 59 / 4; ``` which would be 14.75 if calculated in floating point; how can I store the result as 15 in "a"?
The standard idiom for integer rounding up is: ``` int a = (59 + (4 - 1)) / 4; ``` You add the divisor minus one to the dividend.
In ANSI C on Windows what is the best/easiest way to transfer data between two programs running locally without needing to write/read from a file? Data will be basic text and only one program will be sending and the other receiving. Thanks.
Inter-process communication is inherently platform-dependent; "ANSI C" doesn't have anything to say about this, but you should start here for Windows: http://msdn.microsoft.com/en-us/library/aa365574(VS.85).aspx Much depends on the kinds of applications you're talking about, and the volume of data, and how tightly c...
I want to hide my console of C when I run my application. How can I make my application run in the background?
Programs withmain()by default are compiled as SUBSYSTEM:CONSOLE applications and get a console window. If you own the other processes your application is starting, you could modify them to be windowed applications by one of the following methods: Modify them to useWinMain()instead ofmain(). This is the typical appr...
Let's say I want to do something like this ``` void my_printf(char *fmt,...) { char buf[big enough]; sprintf(buf,fmt,...); } ``` What is the proper way of passing the variable number of arguments directly to a function with accepts variable arguments?
sprintfhas ava_listform calledvsprintf. Pass theva_listyou construct locally to it as the last argument. ``` void my_printf(char *fmt,...) { va_list ap; va_start(ap, fmt); char buf[big enough]; vsprintf(buf,fmt,ap); va_end(ap); } ```
I usually use pointers in the following manner ``` char *ptr = malloc( sizeof(char) * 100 ); memset( ptr, 0, 100 ) ; strncpy( ptr, "cat" , 100 - 1 ); ``` But this time instead of using "cat", I want to use it ASCII equivalent in hex. cat = 0x63, 0x61, 0x74, 0x00 I tried ``` strncpy( ptr, "0x630x61" , 100 ...
\xXXis the syntax for inserting characters in hex format. so yours would be: ``` strncpy( ptr, "\x63\x61\x74", 100 - 1); ``` You don't need to put in a\x00since having quotes automatically null-delimits the string.
Could you please help me how to format astruct timevalinstance to human readable format like "2010-01-01 15:35:10.0001"?
You need to manually append the microseconds part, since it's not in thestruct tmthatstrftime() deals with. Here's a snippet: ``` struct timeval tv; time_t nowtime; struct tm *nowtm; char tmbuf[64], buf[64]; gettimeofday(&tv, NULL); nowtime = tv.tv_sec; nowtm = localtime(&nowtime); strftime(tmbuf, sizeof tmbuf, "%Y-...
Purely for interest, I am re-learning C after ... I don't know ... 15 - 20 years. I seem to recall that variable arguments were implemented as simple macros. Can anyone remember what they were? Edit: To clarify my question, I know they had the same name as va_list etc. but can you remember the actual macro definiti...
You're thinking ofva_list,va_arg,va_start, andva_endfrom stdarg.h (link to WP article). They still work just fine. :-)
This is my warning. ``` implicit declaration of function 'exit' ``` How i can remove it. i am using linux & gcc compiler.
Add: ``` #include <stdlib.h> ``` to the top of your program.
Consider the following code: ``` int main() { int *p; ++((int){5}); //compile without err/warning &((int){5}); //compile without err/warning ++((char *)p); //Compile-time err: invalid lvalue in increment &((char *)p); //Compile-time err: invalid lvalue in unary '&' } ``` Why do th...
It is because the "cast" in a compound literal is not a cast at all - it just looks like one. A compound literal (which is the complete construction(int){5}) creates an lvalue. However a cast operator creates only an rvalue, just like most other operators. This example would be allowed (but useless, just like youri...
I have a readline-based application with a prompt, however I'd like it to not show when the input is not interactive. ``` $ ./readline-app < command-list > result $ cat result prompt> Output line 1 prompt> Output line 2 prompt> $ ``` How can I make the prompt to not print in this case?
Useisatty(3)to determine whether stdin and/or stdout are connected to a tty.
I came across this page:Plotting Tools where I found a set of tools with the name stats.pl and make-cdf. I can write my own but don't want to spend too much time when someone else has already done that. Does anyone have these tools or at least point me to a similar set of tools somewhere?
I do not know who Dave, Binju, Vijay and Dan are and I did not see a way of figuring out whatstats.plandmake-cdfcontain. There are a number of excellentstatistics related modules on CPANincludingStatistics::Descriptive,Statistics::KernelEstimationandMath::GSL::CDFto name but a few that might be relevant given the nam...
Working on a simple C program I'm stuck with an if test: ``` int line_number = 0; if ((line_number >= argv[2]) && (line_number <= argv[4])) ``` gcc says: ``` cp.c:25: warning: comparison between pointer and integer cp.c:25: warning: comparison between pointer and integer ``` What can I do to properly check the ran...
Of course it doesn't work:argvis a pointer to pointer tochar.. it's not clear what you want to do but think about thatargv[2]is third parameter andargv[4]is fifth one. But they are ofchar*type (they are strings) so if you want to parse them as integers you should do it using the functionatoi: ``` int value = atoi(arg...
This question already has an answer here:What does the C standard say about bitshifting more bits than the width of type?(1 answer)Closed5 years ago. It seems like I should be able to perform bit shift in C/C++ by more than 32 bits provided the left operand of the shift is a long. But this doesn't seem to work, at l...
A is equal to 0 because A only has 32-bits, so of course you are shifting all the bits off to the left leaving only 0 bits left. You need to make A 64-bit: ``` unsigned long long A = (1ULL << 37); ``` Or if you intend to use Visual C++: ``` unsigned __int64 A = (1ULL << 37); ```
Say you have 2 share libraries, lib1.so and lib2.so, that both have libcommon.a statically linked into them. Would the compiler complain about ambiguous symbol reference if you were to dynamically link both lib1.so and lib2.so? Or would be the compiler be smart enough to know libcommon symbols are shared between lib1 ...
There won't be a conflict because when you link to shared libraries, the linker will use the definition from the first shared library which provides the symbol and won't look further at the other shared libraries. Symbols included from the .a will be exported in both shared libraries but won't conflict.
Dynamic integer will be any number from 0 to 150. i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10. Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?Only thing is woul...
``` n + (10 - n % 10) ``` How this works. The % operator evaluates to the remainder of the division (so41 % 10evaluates to 1, while45 % 10evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple. The only issue is that this will turn 40 into 50. If you don't wan...
If 2 or more threads are waiting on an event, doesSetEventunblock one or all of them(Or some of them) ?
It depends on if it is a manual or auto-reset event. If it is a manual reset, then multiple threads can be released until it is reset. If it is auto-reset, then only one will be signaled.
I'm taking a programming languages course and we're talking about theextern "C"declaration. How does this declaration work at a deeper level other than "it interfaces C and C++"? How does this affect the bindings that take place in the program as well?
extern "C"is used to ensure that the symbols following are notmangled(decorated). Example: Let's say we have the following code in a file calledtest.cpp: ``` extern "C" { int foo() { return 1; } } int bar() { return 1; } ``` If you rungcc -c test.cpp -o test.o Take a look at the symbols names: 00000...
I am working with a C89 compiler and I'm coming across some pointer typing error. Calling code: ``` struct cpu_state_type cpu_state; //Stuff here.... foo() { print_out_cpu(&cpu_state); } ``` Print_out_cpu is defined elsewhere and the H file is #included in. ``` struct cpu_state_type { int r[12]; }; void prin...
Are you sure the prototype has the*in it? If I compile (gcc -std=c89) the following code, I get that exact error: ``` struct cpu_state_type { int r[12]; }; // note that it is the structure as the param here (not the pointer) void print_out_cpu(struct cpu_state_type c); struct cpu_state_type cpu_state; ...
Could you please help me how to format astruct timevalinstance to human readable format like "2010-01-01 15:35:10.0001"?
You need to manually append the microseconds part, since it's not in thestruct tmthatstrftime() deals with. Here's a snippet: ``` struct timeval tv; time_t nowtime; struct tm *nowtm; char tmbuf[64], buf[64]; gettimeofday(&tv, NULL); nowtime = tv.tv_sec; nowtm = localtime(&nowtime); strftime(tmbuf, sizeof tmbuf, "%Y-...
Purely for interest, I am re-learning C after ... I don't know ... 15 - 20 years. I seem to recall that variable arguments were implemented as simple macros. Can anyone remember what they were? Edit: To clarify my question, I know they had the same name as va_list etc. but can you remember the actual macro definiti...
You're thinking ofva_list,va_arg,va_start, andva_endfrom stdarg.h (link to WP article). They still work just fine. :-)
This is my warning. ``` implicit declaration of function 'exit' ``` How i can remove it. i am using linux & gcc compiler.
Add: ``` #include <stdlib.h> ``` to the top of your program.
Consider the following code: ``` int main() { int *p; ++((int){5}); //compile without err/warning &((int){5}); //compile without err/warning ++((char *)p); //Compile-time err: invalid lvalue in increment &((char *)p); //Compile-time err: invalid lvalue in unary '&' } ``` Why do th...
It is because the "cast" in a compound literal is not a cast at all - it just looks like one. A compound literal (which is the complete construction(int){5}) creates an lvalue. However a cast operator creates only an rvalue, just like most other operators. This example would be allowed (but useless, just like youri...
I have a readline-based application with a prompt, however I'd like it to not show when the input is not interactive. ``` $ ./readline-app < command-list > result $ cat result prompt> Output line 1 prompt> Output line 2 prompt> $ ``` How can I make the prompt to not print in this case?
Useisatty(3)to determine whether stdin and/or stdout are connected to a tty.
I came across this page:Plotting Tools where I found a set of tools with the name stats.pl and make-cdf. I can write my own but don't want to spend too much time when someone else has already done that. Does anyone have these tools or at least point me to a similar set of tools somewhere?
I do not know who Dave, Binju, Vijay and Dan are and I did not see a way of figuring out whatstats.plandmake-cdfcontain. There are a number of excellentstatistics related modules on CPANincludingStatistics::Descriptive,Statistics::KernelEstimationandMath::GSL::CDFto name but a few that might be relevant given the nam...
Working on a simple C program I'm stuck with an if test: ``` int line_number = 0; if ((line_number >= argv[2]) && (line_number <= argv[4])) ``` gcc says: ``` cp.c:25: warning: comparison between pointer and integer cp.c:25: warning: comparison between pointer and integer ``` What can I do to properly check the ran...
Of course it doesn't work:argvis a pointer to pointer tochar.. it's not clear what you want to do but think about thatargv[2]is third parameter andargv[4]is fifth one. But they are ofchar*type (they are strings) so if you want to parse them as integers you should do it using the functionatoi: ``` int value = atoi(arg...
This question already has an answer here:What does the C standard say about bitshifting more bits than the width of type?(1 answer)Closed5 years ago. It seems like I should be able to perform bit shift in C/C++ by more than 32 bits provided the left operand of the shift is a long. But this doesn't seem to work, at l...
A is equal to 0 because A only has 32-bits, so of course you are shifting all the bits off to the left leaving only 0 bits left. You need to make A 64-bit: ``` unsigned long long A = (1ULL << 37); ``` Or if you intend to use Visual C++: ``` unsigned __int64 A = (1ULL << 37); ```
Say you have 2 share libraries, lib1.so and lib2.so, that both have libcommon.a statically linked into them. Would the compiler complain about ambiguous symbol reference if you were to dynamically link both lib1.so and lib2.so? Or would be the compiler be smart enough to know libcommon symbols are shared between lib1 ...
There won't be a conflict because when you link to shared libraries, the linker will use the definition from the first shared library which provides the symbol and won't look further at the other shared libraries. Symbols included from the .a will be exported in both shared libraries but won't conflict.
Dynamic integer will be any number from 0 to 150. i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10. Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?Only thing is woul...
``` n + (10 - n % 10) ``` How this works. The % operator evaluates to the remainder of the division (so41 % 10evaluates to 1, while45 % 10evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple. The only issue is that this will turn 40 into 50. If you don't wan...
If 2 or more threads are waiting on an event, doesSetEventunblock one or all of them(Or some of them) ?
It depends on if it is a manual or auto-reset event. If it is a manual reset, then multiple threads can be released until it is reset. If it is auto-reset, then only one will be signaled.
This is my warning. ``` implicit declaration of function 'exit' ``` How i can remove it. i am using linux & gcc compiler.
Add: ``` #include <stdlib.h> ``` to the top of your program.
Consider the following code: ``` int main() { int *p; ++((int){5}); //compile without err/warning &((int){5}); //compile without err/warning ++((char *)p); //Compile-time err: invalid lvalue in increment &((char *)p); //Compile-time err: invalid lvalue in unary '&' } ``` Why do th...
It is because the "cast" in a compound literal is not a cast at all - it just looks like one. A compound literal (which is the complete construction(int){5}) creates an lvalue. However a cast operator creates only an rvalue, just like most other operators. This example would be allowed (but useless, just like youri...
I have a readline-based application with a prompt, however I'd like it to not show when the input is not interactive. ``` $ ./readline-app < command-list > result $ cat result prompt> Output line 1 prompt> Output line 2 prompt> $ ``` How can I make the prompt to not print in this case?
Useisatty(3)to determine whether stdin and/or stdout are connected to a tty.
I came across this page:Plotting Tools where I found a set of tools with the name stats.pl and make-cdf. I can write my own but don't want to spend too much time when someone else has already done that. Does anyone have these tools or at least point me to a similar set of tools somewhere?
I do not know who Dave, Binju, Vijay and Dan are and I did not see a way of figuring out whatstats.plandmake-cdfcontain. There are a number of excellentstatistics related modules on CPANincludingStatistics::Descriptive,Statistics::KernelEstimationandMath::GSL::CDFto name but a few that might be relevant given the nam...
Working on a simple C program I'm stuck with an if test: ``` int line_number = 0; if ((line_number >= argv[2]) && (line_number <= argv[4])) ``` gcc says: ``` cp.c:25: warning: comparison between pointer and integer cp.c:25: warning: comparison between pointer and integer ``` What can I do to properly check the ran...
Of course it doesn't work:argvis a pointer to pointer tochar.. it's not clear what you want to do but think about thatargv[2]is third parameter andargv[4]is fifth one. But they are ofchar*type (they are strings) so if you want to parse them as integers you should do it using the functionatoi: ``` int value = atoi(arg...
This question already has an answer here:What does the C standard say about bitshifting more bits than the width of type?(1 answer)Closed5 years ago. It seems like I should be able to perform bit shift in C/C++ by more than 32 bits provided the left operand of the shift is a long. But this doesn't seem to work, at l...
A is equal to 0 because A only has 32-bits, so of course you are shifting all the bits off to the left leaving only 0 bits left. You need to make A 64-bit: ``` unsigned long long A = (1ULL << 37); ``` Or if you intend to use Visual C++: ``` unsigned __int64 A = (1ULL << 37); ```
Say you have 2 share libraries, lib1.so and lib2.so, that both have libcommon.a statically linked into them. Would the compiler complain about ambiguous symbol reference if you were to dynamically link both lib1.so and lib2.so? Or would be the compiler be smart enough to know libcommon symbols are shared between lib1 ...
There won't be a conflict because when you link to shared libraries, the linker will use the definition from the first shared library which provides the symbol and won't look further at the other shared libraries. Symbols included from the .a will be exported in both shared libraries but won't conflict.
Dynamic integer will be any number from 0 to 150. i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10. Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?Only thing is woul...
``` n + (10 - n % 10) ``` How this works. The % operator evaluates to the remainder of the division (so41 % 10evaluates to 1, while45 % 10evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple. The only issue is that this will turn 40 into 50. If you don't wan...
If 2 or more threads are waiting on an event, doesSetEventunblock one or all of them(Or some of them) ?
It depends on if it is a manual or auto-reset event. If it is a manual reset, then multiple threads can be released until it is reset. If it is auto-reset, then only one will be signaled.
I'm taking a programming languages course and we're talking about theextern "C"declaration. How does this declaration work at a deeper level other than "it interfaces C and C++"? How does this affect the bindings that take place in the program as well?
extern "C"is used to ensure that the symbols following are notmangled(decorated). Example: Let's say we have the following code in a file calledtest.cpp: ``` extern "C" { int foo() { return 1; } } int bar() { return 1; } ``` If you rungcc -c test.cpp -o test.o Take a look at the symbols names: 00000...
I am currently porting our code from an alpha (Tru64) to an i386 processor (Linux) in C. Everything has gone pretty smoothly up until I looked into porting our exception handling routine. Currently we have a parent process which spawns lots of sub processes, and when one of these sub-processes fatal's (unfielded) I ha...
The glibc functionsbacktrace()andbacktrace_symbols(), fromexecinfo.h, might be of use.
Why does the below code give Seg. Fault at last line? ``` char* m=ReadName(); printf("\nRead String %s\n",m); // Writes OK char* token; token=strtok(m,'-'); ``` As said, read string prints w/o problem, but why cannot split to tokens?
strtokmodifies its first argument, hence it should be modifiable. Maybe ReadName() returns a pointer to a read-only char array.Can you show us your ReadName() function. Ifthat is the reason for seg-faullt, you can create a copy of the char array before you pass it to strtok using thestrdupfunction like: ``` char *c...
I am making a garbage collector to develop an appreciation for how they work. I can process registers as well as heap and stack memory to find potential references to allocated blocks. But processing the global data memory has eluded me. Is there a way to get the upper and lower bounds of the global memory space in...
I can't give you a direct answer off-hand here, but I can tell you that theBoehm/Demers/Weiser conservative garbage collectorwill have code (and likely docs) to show you. This will be very platform dependent, however.
What are the different types of Linked Lists which are commonly used? I know and have used the following: Singly Linked ListDoubly Linked ListCircular List What are the other kinds of lists that have been used by you or known to you?
Unrolled Linked List In computer programming, an unrolled linked list is a variation on the linked list which stores multiple elements in each node. It can drastically increase cache performance, while decreasing the memory overhead associated with storing list metadata such as references. It is related to the B-tre...
I've read that mysql_store_result() in the MySQL C API will allocate memory for each and every call to it; ``` mysql_store_result() reads the entire result of a query to the client, allocates a MYSQL_RES structure, and places the result into this structure. ``` It is really so? I'm asking because I'm about to call i...
See this link about using mysql_use_result:http://dev.mysql.com/doc/refman/5.0/en/mysql-use-result.html i use "use_result" instead of "store_result" on all select queries.
Does your editor/ide highlight thata++;in this C/C++ code as part of a comment? ``` int a=1; //some comment \ a++; printf("%d\n",a); ``` And what about this? ``` int a=1; //some comment ??/ a++; printf("%d\n",a); ```
VC6, Visual Studio 2003, 2005, 2008, 2010 all do.
In C/C++, there is a 'write() function which let me write to either file or a socket, I just pass in the file descriptor accordingly). And there is a fprintf() which allow me to do fprintf (myFile, "hello %d", name); but it only works for file. Is there any api which allows me to do both? i.e. able to let me do prin...
Sure: just usefdopenon the socket to create aFILE*stream, and usefprintfappropriately.
Using GMP on c, I have a big integer "mpz_t n" in decimal form, how can I cut it into 2 parts? In fact, these 2 parts should have the same length in binary. For example, maybe I can convert the n to a binary of 112bits, then I want to cut it into 2 56bits parts. Thanks
I would use temp = mpz_sizeinbase(n,2) to get the number of bits in your original number and then use mpz_tdiv_q_2exp(q, n, temp>>1) and mpz_tdiv_r_2exp(r, n, temp>>1) to get the upper and lower halves of your original number. Depending on how you want to handle an odd bit length, you may need to adjust the calculati...
Being perfectly satisfied with old-style Makefiles, I am looking for a simple alternative to libtool. I do not want to switch to automake, and I keep running into problems with libtool when I try to use it directly. The latest one is 'unsupported hardcode properties', and I am getting fed up with the lack of complete ...
I not sure if it would fit info your workflow but I'd recommend looking atCMake. It works on Windows, Linux and Mac and should not force you to change any of your other tools. You'll have to judge its suitability yourself though.
as in the title, and each element of the arrayivshould contain a random number between 0 and 255 . I have tried like: ``` char iv[8]; char buf[2]; int i, k; srand(time(NULL)); for (i = 0; i <8; i++){ k = rand()%256; iv[i] = (char)k; } ``` Thanks in advance.
You should useunsigned charfor the array, notchar. The former is guaranteed to be able to hold the values from 0 to (at least) 255, but the lattermaynot be able to hold numbers greater than 127.
I created a GStreamer pipeline that takes multiple input sources: camera audio/video, a logo and a screen capture video that is received as a RTP stream). It combines these sources into one video using the videomixer element. The screen capture stream however seems to lag 2 seconds behind the rest. In order to fix th...
I ended up implementing a buffer probe which enabled me to modify the timestamps of individual packets. SeePipeline Manipulation.
There's a #pragma command to link in a library from the source file rather than from the project settings. I just can't seem to remember it. Can anyone here remind me? Thanks
``` #pragma comment(lib, "library") ``` http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx
I am serializing some C structure to string and than deserializing it withstrtok(). But, unfortunately,strtok()don't detect empty fields (eg 1:2::4). Is there any alternative function?
On linux there'sstrsep. The strsep() function was introduced as a replacement for strtok(), since the latter cannot handle empty fields. However, strtok() conforms to C89/C99 and hence is more portable.
Suppose I do a ``` double d = 234.5; ``` I want to see the memory contents ofd[the whole 8 bytes] How do I do that?
``` unsigned char *p = (unsigned char *)&d; int i; for (i = 0; i < sizeof d; i++) printf("%02x ", p[i]); ```
gcc 4.4.2 c89 I have a wave file: 8000 Hz 16 bit I am wondering if there anyway I can load the raw data of this wave file into a buffer. Many thanks for any advice
Yes, you're looking for reading a binary file in C. Something like this: ``` FILE* f; char buf[MAX_FILE_SIZE]; int n; f = fopen("filename.bin", "rb"); if (f) { n = fread(buf, sizeof(char), MAX_FILE_SIZE, f); } else { // error opening file } ``` This reads a buffer ofbytes. From it you can build your data. ...
Im coding a simple c/gtk+ app connected to a mysql database. The gui and db code is done, now I need to make some reports based on database data, I thought the easier way to do this is by using an api that would let me output the data to a Excel or openoffice spreadsheet,PDF would be helpful too. The problem is dont f...
Cairo is the way: surely it is not inefficient... maybe too low level. If you report is mostly text, I'd render to the cairo context withpango, yet part of the GTK+ stack.
I see thatlwIPhas some AutoIP (aka IPv4LL, akaRFC 3927) code, but I can't tell if it does anything higher up in theZeroconfstack, namely mDNS andDNS-SD(withRFC 2782). So, does lwIP support DNS-SD service discovery? If not, would it be easy to port code from a project likeAvahithat does (assuming licensing allows it)?...
No, lwIP does not support any part of Zeroconf except AutoIP. I've not looked at Avahi but porting Apples mDNSResponder to lwIP is quite straightforward. There is one bit of nastiness where you have to pull back the pbuf headers to access the IP header to get the sender IP (I think a "proper" method for this is in the...
Are calls to signal() done across all threads in a process? Or do you have to call signal for each signal you want to catch per thread? Thanks, Chenz
According to this link on"Requirements of the POSIX signal model", The basic concept behind the POSIX signal model is thatsignal handlers are a process resources; andsignal masks are a thread resources In other words, there can only be a single signal handler (for a particular signal) defined for the process, but yo...
If we have ``` char *val = someString; ``` and then say ``` if(val){ .... } ``` what is theifstatement actually checking here?
Yourifstatement is equivalent to: ``` if (val != NULL) { ... ``` The comp.lang.c FAQ containsthis question and answerwhich goes into a bit more detail why this is true.
I can examine the optimization using profiler, size of the executable file and time to take for the execution. I can get the result of the optimization. But I have these questions, How to get the optimized C code.Which algorithm or method used by C to optimize a code. Thanks in advance.
you can get an idea of optimization using the option-fdump-tree-optimizedwith gcc . and you'll get an optimised file. you cannot run the code but using that you can get an idea of optimization . dont forget to include-O2or-O3or some other level.
I was recently editing a Unicode-encoded text file that also includes Thai characters (alongside "normal" characters). For some reason, after each sequence of Thai characters, a new line appeared. After some mucking around with C, trying to remove all newline characters, I fired up vim to inspect the file. Apparently...
This has nothing to do with the fact that you have some Thai characters in the file. The^M('carrot M') is the representation of a Microsoft (DOS) carriage return.Dos2unixthe file to get rid of these before editing it in vim.
How to design an algorithm to convert a UTF-8 string to a unicode string?
The commenters are right. Readhttp://en.wikipedia.org/wiki/Unicodeand rephrase question. UTF-8 is a ''represenation'' of unicode. You probably want to recode to some other interpretation, maybe Java Strings or Microsoft Visual C++ multibyte chracter strings...
this maybe a noobish question so sorry, is it possible to run c programmes from cmd? I am in the process of creating a programme that takes 3 command line arguments, a string seperator and 2 file names and i have conditions such as if more or less command line items are passed then print an error etc i cannot test t...
Yes, you can do that: ``` c:\> cd c:\directory\where\the\program\is c:\directory\where\the\program\is> program arg1 arg2 arg3 separator file1 file1 ```
I have one requirement in C. ``` char abc[]="hello"; char hello[]="world"; ``` Using abc whether we can get the hello variable's value in C. I know it is possible in some of the languages like Perl, Php, Bash,., Is it possible in C?
Yes you are right , this is possible in some other language but not in C , since abc is a container which resides in a location (for ex: 1000) and hello is one more container which resides in another location ( for ex : 2000 ) , so we have no contact between these two arrays , we cannot make a value ( strings ) to...
Why does the below code give Seg. Fault at last line? ``` char* m=ReadName(); printf("\nRead String %s\n",m); // Writes OK char* token; token=strtok(m,'-'); ``` As said, read string prints w/o problem, but why cannot split to tokens?
strtokmodifies its first argument, hence it should be modifiable. Maybe ReadName() returns a pointer to a read-only char array.Can you show us your ReadName() function. Ifthat is the reason for seg-faullt, you can create a copy of the char array before you pass it to strtok using thestrdupfunction like: ``` char *c...
I am making a garbage collector to develop an appreciation for how they work. I can process registers as well as heap and stack memory to find potential references to allocated blocks. But processing the global data memory has eluded me. Is there a way to get the upper and lower bounds of the global memory space in...
I can't give you a direct answer off-hand here, but I can tell you that theBoehm/Demers/Weiser conservative garbage collectorwill have code (and likely docs) to show you. This will be very platform dependent, however.