question
stringlengths
25
894
answer
stringlengths
4
863
I'm using some old C code that uses the old deprecatedIplImagetype. I'm using the new OpenCV 2.3.1 for Android, and the images I get from the camera areCvMats. I want to convert them toIplImageso I can pass it to the native function. Alternatively, I could modify the original function to accept aCvMatand convert it...
UsecvGetImage: ``` IplImage tmp; IplImage* result = cvGetImage((CvArr*) mat, &tmp); ```
Where i can get binary file of GDB debugger for BusyBox under i386 architecture. I tried to build it from source, but unsuccessful. When i run gdb on my controller - all normal, but when i start debug simple hello world c application i have the segmentation fault. I think that when i set built configuration of gdb - m...
GDB "for Busybox"? Busybox is an application (or set of applications), not an OS. Do you mean a uClibc-linked GDB (which is perhaps mildly related, or perhaps not, but definitely not what you said)? Or what? If you just mean any static-linked GDB binary you can move from one Linux-i386 system to another without needin...
Alright here's the code: ``` //in another file void **ptr; ptr = kmalloc(sizeof(void *) * 2); *(ptr+0) = tf; //type trapframe * *(ptr+1) = as; //type addrspace * func(*ptr); ``` And here is that function: ``` void func(void *ptr) { struct trapframe *parentTF = ptr[0]; struct addrspace *newAS = ptr[1]; //no...
If I'm correctly understanding what you're trying to do, it seems like you need to change this: ``` void func(void *ptr) { ``` to this: ``` void func(void **ptr) { ``` and this: ``` func(*ptr); ``` to this: ``` func(ptr); ``` Note that*(ptr+0)andptr[0]are synonymous, as are*(ptr+1)andptr[1].
Why does this equation produce two different values forein C (32-bit) and Java (64-bit)? They are off by an unexpectedly large amount. ``` int a, b, c, d; double e; a = -12806; b = 1; c = 800; d = 19209; double f = (32768 / 10.24); e = (a + (double) b / c * d) / f; ``` C produces -3.9940624237060547. Java produce...
In Java the implicit braces are a bit different: ``` int a, b, c, d; double e; a = 3; b = 4; c = 5; d = 6; e = a + (double) b / c * d; System.out.println("e=" + e); e = a + (((double) b) / c) * d; // Java: 7.8 System.out.println("e=" + e); ``` If you run this in C you will see th...
I have the following code: ``` interface ** rInterfaces[MAX_REACTANS]; _reaction->rInterfaces = (interface **)malloc(MAX_REACTANS * sizeof(interface *)); ``` I am getting an error saying: ``` error: incompatible types when assigning to type ‘struct interface **[10]’ from type ‘struct interface **’ ``` I don't ...
Judging by yourmallocyou want a pointer to a pointer to an interface. Drop[MAX_REACTANS]from your declaration. You can also drop theinterface **cast.
Hello i want to call a c Function from an objective c method how can i do that? here is my function ``` static BOOL test () { .... if(...){ return YES; }else{ return NO; } .... } ```
Just as you will in a C program: ``` -(void) myVoidMethod { BOOL res; res = test(); } ``` Don't forget to declare / include relevant header (again, just like in a C program). Also, as daknøk mentioned, Objective-C is a strict superset of C, so what works with C - works with Objective-C.
In c-strings we need to allocate reasonable size of memory. To avoid reallocations in string operations, we can use something like Stringbuilder in C# or Java or - in C - just allocate more memory for string. But still it can be a problem if we don't know the memory requirement in advance. Do we have some implemetatio...
See the article onRopesfor a data structure that keeps strings as trees. It is similar to your idea.
How to implement a program in c to calculate 2^999 ?
You need to use a big integer library which work with arbitrarily sized arrays. GMP is popular:http://gmplib.org/. If you're willing to sacrifice precision you can use adoublewhich can represent values up to about 1.8 * 10^308 by just usingpow()(2^999 = ~5.4 * 10^300).
I am writing a C program to traverse the file system tree. I am aware of ftw() but would like to do it on my own. The issue is I would like my C program to visit each node(directory/file) without having to do pathlookup(ofcourse done implicitly but want to avoid that too) for each node. Thanks Say a directory A has ...
You can avoid the repeated path lookups and the ugliness (global state and non-thread-safety) ofchdirby usingopenatandfdopendirinstead ofopendirto traverse the tree.
I'm new at kernel programming and trying to do a "Hello World" example. I added the following code to init/main.c in start_kernel() ``` #ifdef HELLO printk("Hello World"); #endif ``` Now to my question. How do i define HELLO in the boot parameters using qemu?
You need to defineHELLOat compile time, (either with-DHELLOas a compiler flag or#define HELLOsomewhere), otherwise the compiler never even sees theprintkcall and no code for it gets emitted. You can't make the C compiler get re-run at early stage boot time based on the boot parameters, which is what you'd need to do ...
I would like to create a array having 21 values between 0 to 20.I would like them to be in random and at the same time non-repeated. I know how to create a random number between 0 to 20. ``` 0 + rand()/(RAND_MAX/(20-0+1)+1) ``` But i don't know how to create those numbers such that it is not repeated comparing to p...
You probably want to use something like theFisher-Yates shuffle.
I want to insert thegetelementprinstruction in my code, like the one shown below. ``` %i1 = getelementptr inbounds [16 x i64]* @Counters, i64 0, i64 %8 ``` How can I insert that? I can insert load and store instructions by using the constructors ofLoadInstandStoreInstclasses, but the constructor forGetElementPtrInst...
According tohttp://llvm.org/doxygen/classllvm_1_1GetElementPtrInst.htmlyou can create the instruction via factory-likeGetElementPtrInst::Create()method. Alternatively, you can useIRBuilderto do all low-level stuff for you.
Why in the below written code we can not assignstrAtostrBand as the pointerpAholds address of pointerpBthen address should have been copied on assignment ofpAtopBandstrBshould have contain the value same asstrB. ``` #include <stdio.h> char strA[80] = "A string to be used for demonstration purposes"; char strB[80]; in...
You can't assign arrays in C (strB=strA). You must usestrcpyormemcpyto transfer contents of one array/pointer to an array.
While reading some question on a site I came across below question where a c question needs to be debug ``` unsigned int a, b, c; /* a and b are assume to have some values */ c = (a + b) / 2; // <- There is a bug in this st What is the bug? and how you debug it? ``` Some of the answer saying it could cause overflow(...
a+bmay overflow if the sum ofaandbis larger thanUINT_MAX, the maximum value for anunsigned int. E.g., ``` unsigned a = 1; unsigned b = UINT_MAX; printf("%u\n", (a+b)/2); ``` prints0. If you want to find the average of twounsigned ints without overflow, do ``` c = a/2 + b/2 + (a % 2 & b % 2); ``` (or(a%2 + b%2)/2...
I was working with c puzzles, and came across this question . In here , a at printf statement the pointer gets incremented once, so i thought it will be pointing to the random number ! but I cant understand why 25 is the output? could anyone please help me understand ? Many thanks in advance;) ``` void main() { ...
Youarepointing at a random piece of memory (address 5). You're then incrementing whatever happens to be stored there, and printing the result. This isundefined behaviour; your program could do anything. UPDATE:Actually, this code shouldn't even compile. You've declared it as a pointer toconst, so the compiler shou...
I would like to implement the javaArrays.binarySearchmethod forbinarySearch(double[], double), but in C language. Something similar is describedherebut for a character array, and it is not described well enough. How should I do it? Is it already implemented anywhere else (GSL library, etc)?
If you are using a C++ compiler, take a look atstd::binary_search. Update Also take a look atstdlib.h(ANSI C)bsearch. Since you are working directly with arrays, I think this is the function that best fits the job.
Stumbled on this row of c code but was unsure if it is valid or not. What does it do? What type will the variable have? ``` const VARNAME = "String of text"; ```
Curiously, I wasn't expecting this to compile, but it does. However, compiler doesn't like it too much: ``` ..\main.c:4:7: warning: type defaults to 'int' in declaration of 'VARNAME' ..\main.c:4:17: warning: initialization makes integer from pointer without a cast ``` So it does takeintas default type, and thus VARN...
I have an array of char pointers in C with a size of 10. I am trying to loop through and print each string out. Not all of the elements are populated and I believe this is causing me an error. How do I check if an element is populated. This is what I have tried. When I run my code I find that the first element is po...
errorsis not initialised so the elements can be any value, specifically may not be NULL. Change to: ``` char *errors[10] = { 0 }; /* Initialise all elements to NULL. */ ```
There is a function: ``` void some_function(int id,...); ``` question: is there a way to wrap this function? It means to get something like this: ``` void wrapped_some_function(int id,...) { //do smth some_function(id,...); } ```
With gcc,__builtin_apply_argsand__builtin_apply, documentedhere, can do it.For standard C, there's no way (what other answers suggest can work, but it isn't 100% what you ask for).But if there's a variation ofsome_functionthat getsva_list(likevprintfis a variation ofprintf), you can use it.
When declaring a string in C what is the difference between ``` char* mystring; ``` and ``` char *mystring; ```
There is no difference. The second option is commonly preferred because it makes it easier to avoid this pitfall: ``` char* str1, str2; ``` Here,str1is achar*butstr2is a plainchar. The other way of writing the declaration makes it easier to see that you have to put an extra asterisk in there: ``` char *str1, *str2;...
Is it possible to precisely estimate on paper how much RAM will be consumed for a simple algorithm (bubble sort) in C on a trivial dataset (10 integer array)? Or will compiler implementation concerns and 'byte padding' make this impossible? (Given a platform such as a 32bit x86 machine).
Bubble sort can work in-place, so it needs no memory except the array you sort. A 10 integer array takes 40 bytes, plus some small platform dependent allocation overhead.If you want a really precise estimate, you need to consider the size of the executable, memory used for process management, and more. But on x86, wh...
I was just a bit bored and was thinking that it would be cool to make an application for my to access files on a work group network from a mobile device. The thing is, I have no idea where to start. I am fairly well versed with programming in C/C++. I was wondering if there were any API's that would make my grunt a l...
Absolutely. Blackberry's website has all the tools you need to start developing for the PlayBook. For C/C++ development, you can check out:https://bdsc.webapps.blackberry.com/native/documentation QNX (the OS on the PlayBook) is a powerful RTOS and something I'd consider buying a PlayBook for, just to play around and ...
I have a doubt.. it was question in my quiz.. Like to know the answer for this question. ``` Question: int foo(int); double foo(int); double foo(double); void bar(int value){ double score = foo(value); } ``` which of the function declarations will be selected? or it is none of the above?
C doesn't support overloading (functions with the same name). If this is really a C++ question, C++ doesn't allow overloads where only the return type is different (int foo(int)anddouble foo(int)).
How do I make an HTTP connection using C? Any references or sample code out there? Further, how do I implement opening a Comet connection from client written in C? (Any additional info about opening an HTTPS connection would also be appreciated.) Thanks!
Try this, a good reference http://beej.us/guide/bgnet/ The above is tutorial for socket programming, you can use those to built an http client of your own, otherwise you can choose built in libraries like curl. If you use plain sockets then you need to encode and decode the header information along with each reques...
Mat mask = Mat::zeros(img1.rows, img1.cols, CV_8UC1) this piece of code is supposed to create a mask, I think, by using C++. What is the equivalent to creating a mask in C, like this? also, can someone explain to me what this piece of code is actually doing please?
With the C API, we would call ``` IplImage *mask = cvCreateImage(cvGetSize(img1), IPL_DEPTH_8U, 1); cvSetZero(mask); ``` The C API is easier to read IMO, and what it does is create an image with 8 bits per pixel, 1 channel (grayscale), of the same size asimg1, and then setting all its pixel values to zero.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. At the main of code, I want to crea...
There should be nothing special you need to do. If you want the main thread to stop, just don't code it to do any work (or call a sleep function). If you want the thread to be processed, code it to do something. You should be focusing on what work you want your program to do though, not on the threads.
I want to write a simple SDL OpenGL app, Codeblocks is the IDE I use. When I create a new OpenGL project, it compiles fine, but if I try to use a function from the SDL header, le wild "undefined reference error" occurs. The same goes for the other direction, if I create a new SDL project, I can use the SDL functions w...
You need to add the correct library. Headers just give the compiler sort of a index. But you need to tell the linker which libraries to actually pull in. You should find the linker options at the build settings. You need the following libraries for SDL + OpenGL libGL.so (-lGLlinker switch )libSDL.so (-lSDLlinker swit...
How can I obtain the value ofINT_MAXusing only the bitwise operators, in C? I expected~0to be1111111111(complement of1, so decimal-1) and~0 >> 1to be0111111111, which would be max, but it's still-1. Why is that and how can I obtain the value ofINT_MAXby using bit operations?
Try~0UL >> 1. The issue is that C will do a sign-extended right shift if it's dealing with a signed type. This is why you're still getting negative one -- because it's shifting in another 1 bit to match the 1 bit that was there. (That way-8>> 1 gives-4as you'd like for fast divisions by two.)
Given a two floating point Numbers A and B, which are command line arguments, I must create methods to do bitwise operations on them. Including And, Or, Not, xOr, floating Point addition etc... How can I access each bit in C? I need to access the specific 1's and 0's. Any idea how?
Here's an example using unions, as Keith suggests. ``` /* -std=c99 */ #include <stdio.h> int main(int argc, char * argv[]) { /* note, I'm assuming an int has the same size of a float here */ assert( sizeof(unsigned int) == sizeof(float) ); union { float floating; unsigned int integer; } a; a.flo...
Variations of this question have been asked, but not specific to GNU/Linux and C. I use Komodo Edit as my usual Editor, but I'd actually prefer something that can be used from CLI. I don't need C++ support; it's fine if the tool can only handle plain C. I really appreciate any direction, as I was unable to find anyt...
I don't think that a pure console refactoring tool would be nice to use.I use Eclipse CDT on linux to write and refactor C-Code.There exists also Xrefactory for Emacshttp://www.xref.sk/xrefactory/main.html if a non console refactoring tool is o.k for you as well.
I want to convert host name (computer name My Computer ->property -> Advance System Setting ->computer Name) to IP Address. Is there any way can I convert host name to IP address? I have tried following but pHostInfo coming as NULL. and hostname is my computer name. ``` struct hostent* pHostInfo; pHostInfo = gethost...
``` #include <string> #include <netdb.h> #include <arpa/inet.h> std::string HostToIp(const std::string& host) { hostent* hostname = gethostbyname(host.c_str()); if(hostname) return std::string(inet_ntoa(**(in_addr**)hostname->h_addr_list)); return {}; } ```
In Emacs, the line gets indented only after hitting return (in cc-mode). Is that normal? Can that be changed to indent automatically when it hits a new line? How do I look at variables, for exampleThere are a number of predefined styles. Take a look at the variable ‘c-style-alist’ to see a list of them.?
in all of my programming mode hooks i have this line: ``` (local-set-key [return] 'newline-and-indent) ``` if for example, you wanted this in all "c" like modes, you would add this to your .emacs file: ``` (add-hook 'c-mode-common-hook (lambda () (local-set-key [return] 'newline-and-indent))) ...
I am using GNU Make 3.81 for building a given C project. The normal behavior of GNU is to check, if the target exists and any prerequisite is newer than the target, the target commands are executed. Is it possible to rebuild the target if the prerequisites are newer than the target AND newer than a given timestamp? L...
There's no way to do it directly with make, but you could do it with the shell in the action for the rule: ``` target: prereq touch --date='Oct 2, 2011' .timestamp if [ $< -nt .timestamp ]; then \ command to rebuild target; \ fi ``` Note the use of\to make theifcomm...
On ARM architecture, unfortunately I don't know exactly what chip it is, is a 32 bit int read/write atomic? Is there any sort of guarantees about reads/writes to basic types?
It should be atomic, EXCEPT if that int is stored on a non-aligned address.
I am trying to read from a socket into a buffer until a certain character is reached usingread(fd, buf, BUFFLEN). For example, the socket will receive two lots of information separated by a blank line in one read call. Is it possible to put the read call in a loop so it stops when it reaches this blank line, then it...
A simple approach would be to read a single byte at a time until the previous byte and the current byte are new-line characters, as two consecutive new-line characters is a blank line: ``` size_t buf_idx = 0; char buf[BUFFLEN] = { 0 }; while (buf_idx < BUFFLEN && 1 == read(fd, &buf[buf_idx], 1) { if (buf_idx > 0...
By pure chance I stumbled over an article mentioning you can "enable" ASLR with-pie -fPIE(or, rather, make your application ASLR-aware).-fstack-protectoris also commonly recommended (though I rarely see explanations how and against which kinds of attacks it protects). Is there a list of useful options and explanation...
Hardened Gentoo uses these flags: ``` CFLAGS="-fPIE -fstack-protector-all -D_FORTIFY_SOURCE=2" LDFLAGS="-Wl,-z,now -Wl,-z,relro" ``` I saw about 5-10% performance drop in comparison to optimized Gentoo linux (incl. PaX/SElinux and other measures, not just CFLAGS) in default phoronix benchmark suite.
My question is in regard to the situation in the pseudo code below, for my situation is it possible to use one parallel region for the entire code or should i just seperate parallel regions because of the if and else statements ``` for loop { //some code , possible reduction here } if something ...
Yes, you can use one parallel region for the whole code. Just make sure to account for all reductions occuring in all possible execution branches.
I would like to implement the javaArrays.binarySearchmethod forbinarySearch(double[], double), but in C language. Something similar is describedherebut for a character array, and it is not described well enough. How should I do it? Is it already implemented anywhere else (GSL library, etc)?
If you are using a C++ compiler, take a look atstd::binary_search. Update Also take a look atstdlib.h(ANSI C)bsearch. Since you are working directly with arrays, I think this is the function that best fits the job.
Stumbled on this row of c code but was unsure if it is valid or not. What does it do? What type will the variable have? ``` const VARNAME = "String of text"; ```
Curiously, I wasn't expecting this to compile, but it does. However, compiler doesn't like it too much: ``` ..\main.c:4:7: warning: type defaults to 'int' in declaration of 'VARNAME' ..\main.c:4:17: warning: initialization makes integer from pointer without a cast ``` So it does takeintas default type, and thus VARN...
I have an array of char pointers in C with a size of 10. I am trying to loop through and print each string out. Not all of the elements are populated and I believe this is causing me an error. How do I check if an element is populated. This is what I have tried. When I run my code I find that the first element is po...
errorsis not initialised so the elements can be any value, specifically may not be NULL. Change to: ``` char *errors[10] = { 0 }; /* Initialise all elements to NULL. */ ```
There is a function: ``` void some_function(int id,...); ``` question: is there a way to wrap this function? It means to get something like this: ``` void wrapped_some_function(int id,...) { //do smth some_function(id,...); } ```
With gcc,__builtin_apply_argsand__builtin_apply, documentedhere, can do it.For standard C, there's no way (what other answers suggest can work, but it isn't 100% what you ask for).But if there's a variation ofsome_functionthat getsva_list(likevprintfis a variation ofprintf), you can use it.
When declaring a string in C what is the difference between ``` char* mystring; ``` and ``` char *mystring; ```
There is no difference. The second option is commonly preferred because it makes it easier to avoid this pitfall: ``` char* str1, str2; ``` Here,str1is achar*butstr2is a plainchar. The other way of writing the declaration makes it easier to see that you have to put an extra asterisk in there: ``` char *str1, *str2;...
Is it possible to precisely estimate on paper how much RAM will be consumed for a simple algorithm (bubble sort) in C on a trivial dataset (10 integer array)? Or will compiler implementation concerns and 'byte padding' make this impossible? (Given a platform such as a 32bit x86 machine).
Bubble sort can work in-place, so it needs no memory except the array you sort. A 10 integer array takes 40 bytes, plus some small platform dependent allocation overhead.If you want a really precise estimate, you need to consider the size of the executable, memory used for process management, and more. But on x86, wh...
I was just a bit bored and was thinking that it would be cool to make an application for my to access files on a work group network from a mobile device. The thing is, I have no idea where to start. I am fairly well versed with programming in C/C++. I was wondering if there were any API's that would make my grunt a l...
Absolutely. Blackberry's website has all the tools you need to start developing for the PlayBook. For C/C++ development, you can check out:https://bdsc.webapps.blackberry.com/native/documentation QNX (the OS on the PlayBook) is a powerful RTOS and something I'd consider buying a PlayBook for, just to play around and ...
I have a doubt.. it was question in my quiz.. Like to know the answer for this question. ``` Question: int foo(int); double foo(int); double foo(double); void bar(int value){ double score = foo(value); } ``` which of the function declarations will be selected? or it is none of the above?
C doesn't support overloading (functions with the same name). If this is really a C++ question, C++ doesn't allow overloads where only the return type is different (int foo(int)anddouble foo(int)).
How do I make an HTTP connection using C? Any references or sample code out there? Further, how do I implement opening a Comet connection from client written in C? (Any additional info about opening an HTTPS connection would also be appreciated.) Thanks!
Try this, a good reference http://beej.us/guide/bgnet/ The above is tutorial for socket programming, you can use those to built an http client of your own, otherwise you can choose built in libraries like curl. If you use plain sockets then you need to encode and decode the header information along with each reques...
Mat mask = Mat::zeros(img1.rows, img1.cols, CV_8UC1) this piece of code is supposed to create a mask, I think, by using C++. What is the equivalent to creating a mask in C, like this? also, can someone explain to me what this piece of code is actually doing please?
With the C API, we would call ``` IplImage *mask = cvCreateImage(cvGetSize(img1), IPL_DEPTH_8U, 1); cvSetZero(mask); ``` The C API is easier to read IMO, and what it does is create an image with 8 bits per pixel, 1 channel (grayscale), of the same size asimg1, and then setting all its pixel values to zero.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. At the main of code, I want to crea...
There should be nothing special you need to do. If you want the main thread to stop, just don't code it to do any work (or call a sleep function). If you want the thread to be processed, code it to do something. You should be focusing on what work you want your program to do though, not on the threads.
Here is what the algorithm says. ``` hash = FNV_offset_basis for each octet_of_data to be hashed hash = hash * FNV_prime hash = hash XOR octet_of_data return hash ``` but if i have a set of strings then what shall i take as the FNV_offset_basis, and what is the meaning of for each octet of data to be hashed...
From the web site referenced in the comment above, ``` 32 bit offset_basis = 2166136261 64 bit offset_basis = 14695981039346656037 ``` use the one that corresponds to the width of your hash. An octet is an 8-bit byte. If you are using text with 8-bit characters, an octet and a character are the same thing. The si...
Here is my code. ``` #include<stdlib.h> #include<stdio.h> int main(int argc,char** argv) { char a; a=9; FILE * fp; fp=fopen(argv[1],"r"); while(a!= EOF) { a=fgetc(fp); printf("\n%d",a); } } ``` The output to this is alright but at the end I am getting a weird character wit...
Besides the methods in the other answers, you can also do like this: ``` while ((a = fgetc(fp)) != EOF) { printf("%d\n", a); } ``` Now you have a few alternative solutions. :) Edit:As R.. so kindly reminds us, you also have to change the type ofatoint.
``` void myThread(void *arg) { printf("Thread ran!\n"); pthread_exit( NULL ); } int main() { int ret; pthread_t mythread; ret=pthread_create(&mythread,NULL,myThread,NULL); if (ret != 0) { printf( "Can’t create pthread (%s)\n", strerror(errno ) ); exit(-1); } ret...
Becausemainreturns immediately, before the thread has had a chance to execute - try addingsleep(1000);beforereturn 0;and you'll probably find that it works. If you'd likemainto wait until the thread finishes, trypthread_join(but then you might as well not have a thread at all). ``` pthread_join(mythread, 0); return ...
How to check in c , linux if a file has been updated/changed . I want to check a file for update before opening the file and performing extraction/ i/o operations from it.
Look at theman pageforstat(2). Get thest_mtimemember of thestruct statstructure, which will tell you the modification time of the file. If the current mtime is later than a prior mtime, the file has been modified. An example: ``` int file_is_modified(const char *path, time_t oldMTime) { struct stat file_stat; ...
I capture a raw image from a grayscale camera. When I transfer the image to OpenCV's IplImage and usecvSaveImage("image.jpg",image), the image is saved with a size of around 160K. Whereas, if I usefwritefunction in C to save the image buffer in.pgmformat, the saved image size is 1.4M. My question is: DoescvSaveImage...
I believeEmbedded JPEGmay be what you are looking for.
Does anyone know of a c/c++ compiler that is easily usable with windows? I have a bit of experience with gcc, but I would like to take a crack at developing some code like this on a windows machine. Many of the compilers I have seen look a bit complex, or are not for windows. Thanks in advance.
Usually on windows the mentality is a bit different. Rather than worrying about a compiler, you worry about getting a good IDE that does all that for you. As a result, Visual Studio is the best option.
I want to assign some value (say 2345) to a memory location(say 0X12AED567). Can this be done? In other words, how can I implement the following function? ``` void AssignValToPointer(uint32_t pointer, int value) { } ```
The fact that you are asking this question kind of indicates that you're in over your head. But here you go: ``` *(int *)0x12AED567 = 2345; ```
I have a code to send data to serial port. I just want to make sure that it is sending the data properly. I checked the function's return value and the number of bytes written and it is success. Is there any other way to actually see the data whatever i am writing? ``` if(WriteFile(m_hSerialComm, pszBuf, dwSize, &dw...
There are several ways to test your software. If you have two serial ports then connect them with a cable and listen on the other port with a terminal application such as the one you mentioned. Otherwise, you could loop back on the same port by connecting pins 2 and 3 together. A hardware-free option would be to use v...
I am learning about piping and shell in a Systems class. I'm messing around withstrace. I am running it on some program calleddpipe. In thestracelog, I see the following: ``` pipe([3, 4]) pipe([5, 6]) ``` What do those integers represent? I under that piping is basically used in shell to route the output of one com...
They're the file descriptors returned bypipe(2,3p). See thepipe(2)man page for more details.
I have userspace sysctl calls made to sysctl tables configured on a 2.6.24 kernel. I have migrated the sysctl code to 2.6.35 kernel. I'm seeing warning msgs sayg that 'deprecated sysctl warning' when i make sysctl() calls from userspace. The same is workinng on 2.6.24. Does anyone have any idea on this. Also, sysctl ...
Thesysctl()system call has long been considered deprecated; indeed the man page has said this for some time: Or rather... don't call it: use of this system call has long been discouraged, and it is so unloved that it is likely to disappear in a future kernel version. Remove it from your programs now; use the/pr...
I have a linux app programmed in C which uses gdk for image stuff. The images are sent to a remote server through FTP (with libcurl). Currently I'm saving the images first to a local hard disk with gdk_pixbuf_save, but this seems kinda useless step. How difficult would it be to save the images directly on the remote ...
There is agdk_pixbuf_save_to_bufferthat can store data to agcharbuffer. I wasn't able to quickly find the CURL API associated with FTPputrequests; hopefully you'll be familiar enough with CURL to know how toputa file using a buffer as contents.
I have a function header in a library that looks like this: ``` void deepCopy(CList ** clone, CList * cl, void * (* data_clone) (void * d)); ``` I am having tremendous difficulty in passing it the deep_clone function properly. This is what I am trying currently ``` CList *ys2 = &ys; void (*dc) (void *) = &data_clo...
The function is not expecting "a pointer to a pointer to a function", it's expecting simply a pointer to a function. ``` deepCopy(..., &data_clone); ``` should suffice.
In a header file a definition is given by ``` static void (*foo[CONST]) (void); ``` What is its meaning ?
It's meaning is an array withCONSTamount of elements of function pointers with signaturevoid f(void); These things get used most often for callbacks, for example the functionatexit.
What I want to do is pass some settings to my module from httpd.conf, something like: ``` <Location /path> SetHandler mymodule-handler # based on this, the module will kick in and "try" to read settings MyCustomStringSetting "AStringValue" MyCustomIntegerSetting 2012 # more </Location> ``` How can I get "ASt...
Here is a complete example (with source) from "Apache: The Definitive Guide": http://docstore.mik.ua/orelly/linux/apache/ch15_04.htm The example module mod_reveal implements two commands, RevealServerTag and RevealTag. In the server configuration, these two new commands can be used: ``` <VirtualHost :9000> Documen...
I want to write a function in C language which returns the 2 dimension array to my main function.
A function that returns a dynamically allocated two dimensional array for theinttype. ``` int ** myfunc(size_t width, size_t height) { return malloc(width * height * sizeof(int)); } ``` It has to be deleted withfreeonce it is not used anymore. EDITThis only allocates thespacefor the array which could be access...
I already have around 10 elements in enum which I am using. I wanted to know the maximum so that I could code properly.
Anenumcan hold at least1023enumeration constants in a conforming implementation (see §5.2.4.1 "Translation limits" of ISO/IEC 9899:1999). So that gives you a lower bound. Since the type of an enumeration constant isint(see §6.4.4.3 "Enumeration constants" of ISO/IEC 9899:1999), the upper bound would beINT_MAX + 1(ass...
I'm usingPeter Deutsch's implementation of MD5to implement a simple password check. I use it this way: ``` md5_state_t md; char *in = "Hello World"; char *out[16]; md5_init(&md); md5_append(&md, in, strlen(in)); md5_finish(&md, out); printf("In: %s\n", in); printf("Out: %s\n", out); ``` Problem is, that I get a r...
An MD5 hash is a binary blob of 16 bytes. You cannot print that as a string. Print it e.g. in a hex representation: ``` md5_state_t md; char *in = "Hello World"; char out[16]; int i; md5_init(&md); md5_append(&md, in, strlen(in)); md5_finish(&md, out); printf("In: %s\n", in); printf("Out: "); for(i = 0; i < 16: i+...
What is the practice on comparing a pthread_t variable to int. I display a list of all thread ids and I take in input from the user specifying which thread to kill, using the id. So how do I compare the input from the user to all of the pthread_t variables.
What is the practice on comparing a pthread_t variable to int. You don't. The typepthread_tis opaque: it need not be an integer. You should instead use thepid_tas returned bygettid.
I'm learning ODBC, and my application needs to use multiple connections concurrently. Should I be allocating a single environment, and then multiple connections from this? Or an environment for each connection? Many thanks!
I'm not sure there is anything to be gained from creating multiple environments unless you are going to change something at the environment level e.g., call SQLSetEnvAttr with different arguments on each environment handle.
I've got a folder in linux, which is contained several shared object files (*.so). How I can find function in shared object files using objdump and bash functions in linux? For instance, the following example is found me functionfunc1in mylib.so: ``` objdump -d mylib.so | grep func1 ``` But i want to findfunc1in fo...
nmis simpler thanobjdump, for this task.nm -A *.so | grep funcshould work. The-Aflag tellsnmto print the file name.
I am compiling some legacy C code with the purpose of migrating it to Java.I don't want to fix the C code, I just want to run it, in order to compare numerical results. I get this gcc 4.6.1 compilation error:expected void** but argument is of type char**Written 20 years ago, this code did not care about pointer types...
What version of gcc are you trying to compile with? gcc 3 supported a-traditionalflag which would tell it to behavelike a K&R C compiler, but this option isn't included in gcc 4. You probably need to run gcc 3 somehow, like installing an OS that included it in a VM. I've read that RHEL 4 used gcc 3, you could try old...
When we perform any operation on unsigned short int it gets promoted to unsigned int even on a machine in which both data types have same size. What is the purpose of such a promotion ? How does it help ? Isn't it just a change of name (since both have same size) ?
Roughly, because that's the way Dennis Ritchie decided it should be back in the early 1970s when he first set out the rules for C (or, at least, first set out the rules for C with support forunsignedinteger types, but that was already becauseshortwas promoted toint).
I have some problem with SSE on ubuntu linux system. example source code onmsdn(sse4)use sse4.1 operation on linux ``` gcc -o test test.c -msse4.1 ``` then error message: ``` error: request for member 'm128i_u16' in something not a structure or union ``` How can I use this example code? Or any example code can us...
The title of the code sample is "Microsoft Specific". This means that those functions are specific to the microsoft implementation of c++, and aren't cross-platform.Here are some Intel-specific guides to SSE instructions.Here is gcc documentation concerning command-line flags for specific assembly optimizations, inclu...
I've used: ``` sprintf(hex, "%02x", (unsigned int) buffer[0] & 0xff); ``` to get hexadecimal representation of binary file. After that I save this representation to txt file. Now I' d like to execute inverse operation. How can I create binary file from my hex data?
sscanf()will let you do the inverse ofsprintf() ``` int output; int we_read_an_integer = sscanf(inputString, "%02x", &output); ``` Repeat as necessary.
I have a program (in C) that runs in the command line, and I am looking to have it accept strings of arbitrary length from users. If I were programming in C++, I would probably use the getline() function in the string library, but I can't seem to find a C equivalent. Do I just need to read characters in blocks of X ...
You can usefgetswithsscanf. Note thatgetlineis now present in the current POSIX:2008 standard. http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
I want my child process to send a signal to the parent process without destroying it. The only way I know to send a signal is to use kill(getppid(),SIGUSR1), however this is killing my parent process. How do I send a signal without killing it? I'm using a signal handler which runs but once it finishes, the parent proc...
It is killing your parent process because you're not installing a signal handler forSIGUSR1in it.
I am trying to find a profiling tool with which I can find out, how much time is spend on each line of code in a C/C++ program. I am working on Linux platforms (Ubuntu, Gentoo, SL) mainly with gcc. I use gprof but sometimes I need the "per line" information. Any suggestions? Thank you!
On linux you can useoprofile. This is a sample based profiler which runs on almost any platform and supports the performance monitoring registers if they are available. On x86 it works with both AMD and Intel. You can use it as standalone program wich will give you an annotated source, but there is a plugin available...
I am writing code that involved a for loop that makes calculations at each index. The smallest of these calculations is stored in a variable and I use MPI_Allreduce at the end of the program to determine the global minimum across all processes. However, I need a way of knowing which process has the smallest value, i...
You can use theMPI_MINLOCoperator in the reduce operation to receive the rank of the process with the minimal value (more specifically, the lowest ranked process that has a minimal value). Seehttp://www.netlib.org/utk/papers/mpi-book/node114.html#SECTION005103000000000000000
Programs like apache2 and mysql install on various machines throughout the world. How do they ensure they know the uid or gid of the restricted rights user they wish to run as? I want my program to run as a service with a user who has least privileges through init.d. I assume services started in init.d are initial...
Usually there's a configuration file which specifies the user the service is to use. Then the service can usegetpwnam(3)and retrieve the UID. ``` struct passwd *getpwnam(const char *name); struct passwd { char *pw_name; /* Login name (username) */ char *pw_passwd; /* Encrypted password */ uid_t p...
When i try to include SDL, it prints an error: ``` error: SDL.h: No such file or directory ``` My system is Mac OSX Lion and i´ve installed SDL. I use this: ``` #include "SDL.h" ```
Specify the include directory of theSDL.hheader togccwith the option-I. For example: ``` gcc -I/usr/include/SDL -c test.c ```
With gcc and gfortran I can generate a list of preprossesor macros defined by the compiler using (edited to reflect ouah's answer) ``` gcc -E -dM - < /dev/null ``` and ``` gfortran -cpp -E -dM /dev/null ``` respectively (on Linux at least). How can I do the same with the Intel compilers icc and ifort? I know that...
Use this with the Intel compiler: ``` icc -E -dM - < /dev/null ``` Note that withgcc, the-Eoption is also required if you want to use the-dMpreprocessor option.
I was asked by an interviewer that how would I implementtail(yes, the one in linux shell). My answer was, first seek to the end of the file, then read characters one-by-one forward, if encounters a\n, means one line is down, blah blah blah. I assume my answer is correct. Then I found this problem, which seek should I...
Useseekgwhen using the C++ IOstreams library.seekpis no use here, since it sets the put pointer. Usefseekwhen using the C stdio library. Uselseekwhen using low-level POSIX file descriptor I/O. The difference between the various seek functions is just the kind of file/stream objects on which they operate. On Linux,se...
I have a quick question. I've been playing around with bit manipulation in c/c++ for a while and I recently discovered that when I compare 2UL and 10UL to a regular unsigned int they seem to return the same bit. For example, ``` #define JUMP 2UL #define FALL 10UL unsigned int flags = 0UL; this->flags |= FALL; //t...
Of course.10ulis 1010 in binary and 2 is 10. Therefore, doingx |= 10sets the second bit too. You probably wanted to use0x10and0x2as your flags. These would work as you expect. As an aside: a single digit in the hex notation represent 4 bits, not 8.
I want to assign a string like:"22 33"to a variable likechar*av[129]. How can i do that in C/C++?
``` strcpy(av[0], "22 33"); ``` IFyou knowav[0]is long enough (length of string you want to put in plus one for theNUL). Otherwise, usestrncpy.
I have a program (in C) that runs in the command line, and I am looking to have it accept strings of arbitrary length from users. If I were programming in C++, I would probably use the getline() function in the string library, but I can't seem to find a C equivalent. Do I just need to read characters in blocks of X ...
You can usefgetswithsscanf. Note thatgetlineis now present in the current POSIX:2008 standard. http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html
I want my child process to send a signal to the parent process without destroying it. The only way I know to send a signal is to use kill(getppid(),SIGUSR1), however this is killing my parent process. How do I send a signal without killing it? I'm using a signal handler which runs but once it finishes, the parent proc...
It is killing your parent process because you're not installing a signal handler forSIGUSR1in it.
I am trying to find a profiling tool with which I can find out, how much time is spend on each line of code in a C/C++ program. I am working on Linux platforms (Ubuntu, Gentoo, SL) mainly with gcc. I use gprof but sometimes I need the "per line" information. Any suggestions? Thank you!
On linux you can useoprofile. This is a sample based profiler which runs on almost any platform and supports the performance monitoring registers if they are available. On x86 it works with both AMD and Intel. You can use it as standalone program wich will give you an annotated source, but there is a plugin available...
I am writing code that involved a for loop that makes calculations at each index. The smallest of these calculations is stored in a variable and I use MPI_Allreduce at the end of the program to determine the global minimum across all processes. However, I need a way of knowing which process has the smallest value, i...
You can use theMPI_MINLOCoperator in the reduce operation to receive the rank of the process with the minimal value (more specifically, the lowest ranked process that has a minimal value). Seehttp://www.netlib.org/utk/papers/mpi-book/node114.html#SECTION005103000000000000000
Programs like apache2 and mysql install on various machines throughout the world. How do they ensure they know the uid or gid of the restricted rights user they wish to run as? I want my program to run as a service with a user who has least privileges through init.d. I assume services started in init.d are initial...
Usually there's a configuration file which specifies the user the service is to use. Then the service can usegetpwnam(3)and retrieve the UID. ``` struct passwd *getpwnam(const char *name); struct passwd { char *pw_name; /* Login name (username) */ char *pw_passwd; /* Encrypted password */ uid_t p...
When i try to include SDL, it prints an error: ``` error: SDL.h: No such file or directory ``` My system is Mac OSX Lion and i´ve installed SDL. I use this: ``` #include "SDL.h" ```
Specify the include directory of theSDL.hheader togccwith the option-I. For example: ``` gcc -I/usr/include/SDL -c test.c ```
With gcc and gfortran I can generate a list of preprossesor macros defined by the compiler using (edited to reflect ouah's answer) ``` gcc -E -dM - < /dev/null ``` and ``` gfortran -cpp -E -dM /dev/null ``` respectively (on Linux at least). How can I do the same with the Intel compilers icc and ifort? I know that...
Use this with the Intel compiler: ``` icc -E -dM - < /dev/null ``` Note that withgcc, the-Eoption is also required if you want to use the-dMpreprocessor option.
I was asked by an interviewer that how would I implementtail(yes, the one in linux shell). My answer was, first seek to the end of the file, then read characters one-by-one forward, if encounters a\n, means one line is down, blah blah blah. I assume my answer is correct. Then I found this problem, which seek should I...
Useseekgwhen using the C++ IOstreams library.seekpis no use here, since it sets the put pointer. Usefseekwhen using the C stdio library. Uselseekwhen using low-level POSIX file descriptor I/O. The difference between the various seek functions is just the kind of file/stream objects on which they operate. On Linux,se...
I have a quick question. I've been playing around with bit manipulation in c/c++ for a while and I recently discovered that when I compare 2UL and 10UL to a regular unsigned int they seem to return the same bit. For example, ``` #define JUMP 2UL #define FALL 10UL unsigned int flags = 0UL; this->flags |= FALL; //t...
Of course.10ulis 1010 in binary and 2 is 10. Therefore, doingx |= 10sets the second bit too. You probably wanted to use0x10and0x2as your flags. These would work as you expect. As an aside: a single digit in the hex notation represent 4 bits, not 8.
I want to assign a string like:"22 33"to a variable likechar*av[129]. How can i do that in C/C++?
``` strcpy(av[0], "22 33"); ``` IFyou knowav[0]is long enough (length of string you want to put in plus one for theNUL). Otherwise, usestrncpy.
I am writing code that involved a for loop that makes calculations at each index. The smallest of these calculations is stored in a variable and I use MPI_Allreduce at the end of the program to determine the global minimum across all processes. However, I need a way of knowing which process has the smallest value, i...
You can use theMPI_MINLOCoperator in the reduce operation to receive the rank of the process with the minimal value (more specifically, the lowest ranked process that has a minimal value). Seehttp://www.netlib.org/utk/papers/mpi-book/node114.html#SECTION005103000000000000000
Programs like apache2 and mysql install on various machines throughout the world. How do they ensure they know the uid or gid of the restricted rights user they wish to run as? I want my program to run as a service with a user who has least privileges through init.d. I assume services started in init.d are initial...
Usually there's a configuration file which specifies the user the service is to use. Then the service can usegetpwnam(3)and retrieve the UID. ``` struct passwd *getpwnam(const char *name); struct passwd { char *pw_name; /* Login name (username) */ char *pw_passwd; /* Encrypted password */ uid_t p...
When i try to include SDL, it prints an error: ``` error: SDL.h: No such file or directory ``` My system is Mac OSX Lion and i´ve installed SDL. I use this: ``` #include "SDL.h" ```
Specify the include directory of theSDL.hheader togccwith the option-I. For example: ``` gcc -I/usr/include/SDL -c test.c ```
With gcc and gfortran I can generate a list of preprossesor macros defined by the compiler using (edited to reflect ouah's answer) ``` gcc -E -dM - < /dev/null ``` and ``` gfortran -cpp -E -dM /dev/null ``` respectively (on Linux at least). How can I do the same with the Intel compilers icc and ifort? I know that...
Use this with the Intel compiler: ``` icc -E -dM - < /dev/null ``` Note that withgcc, the-Eoption is also required if you want to use the-dMpreprocessor option.
I was asked by an interviewer that how would I implementtail(yes, the one in linux shell). My answer was, first seek to the end of the file, then read characters one-by-one forward, if encounters a\n, means one line is down, blah blah blah. I assume my answer is correct. Then I found this problem, which seek should I...
Useseekgwhen using the C++ IOstreams library.seekpis no use here, since it sets the put pointer. Usefseekwhen using the C stdio library. Uselseekwhen using low-level POSIX file descriptor I/O. The difference between the various seek functions is just the kind of file/stream objects on which they operate. On Linux,se...
I have a quick question. I've been playing around with bit manipulation in c/c++ for a while and I recently discovered that when I compare 2UL and 10UL to a regular unsigned int they seem to return the same bit. For example, ``` #define JUMP 2UL #define FALL 10UL unsigned int flags = 0UL; this->flags |= FALL; //t...
Of course.10ulis 1010 in binary and 2 is 10. Therefore, doingx |= 10sets the second bit too. You probably wanted to use0x10and0x2as your flags. These would work as you expect. As an aside: a single digit in the hex notation represent 4 bits, not 8.
I want to assign a string like:"22 33"to a variable likechar*av[129]. How can i do that in C/C++?
``` strcpy(av[0], "22 33"); ``` IFyou knowav[0]is long enough (length of string you want to put in plus one for theNUL). Otherwise, usestrncpy.
Why this code does not work? ``` int main(){ char *str ="abcde"; scanf("%s",str); printf("%s",str); } ``` but this works? ``` int main(){ char str[] ="abcde"; scanf("%s",str); printf("%s",str); }` ```
In the first code, you declare a pointer, which points to astring literal:"abcde".This might be a constant, and you will not be able to change it. The second code is declaring an array and filling it with['a','b',c','d','e','\0'], and is not a constant - so you can change it.