question
stringlengths
25
894
answer
stringlengths
4
863
I am looking through the source code fora project that relays Windows Event Log data to a syslog installation, in order to try to consolidate things on a network that I manage. The program that does this needs adjustment for our application, which I am perfectly willing to do, so I dropped in the GNU build system and...
It's not a Windows thing, it's definedin that project... ``` /* Ignored Events Structure */ struct EVENT_LIST { char source[50]; BOOL wild; int id; }; ```
I have tried to output following but got confused, ``` float f=3.4; char *cp; cp=(char *)&f; printf("%d\n",*cp); ``` normalized number I have calculated IEEE 754 std is, ``` 0 10000000 10110011001100110011001 ``` that's why I assumed at cp now value has, ``` 10011001 ``` after convert to 2's compleme...
That's becausefis being rounded up: ``` 3.4 = 10110011001100110011001 100110011001... (repeating 1001) ``` rounds up to: ``` 3.4 = 10110011001100110011010 ^ ``` when stored into single-precision floating-point. Now when you extract out the last 8 bits, you're actually getting10011010i...
When I read in a file and then output to a new file, the output is garbled, and I am trying to figure out why. I am trying to run the following code ``` #include<stdio.h> #include<stdlib.h> int main(int argc ,char *argv[]) { int c; FILE *of; FILE *f; of=fopen(argv[2],"w"); f=fopen(argv[1],"r"); ...
``` while(c=getc(f)!=EOF) ``` needs parentheses, ``` while( (c=getc(f)) != EOF) ``` the precedence of!=is higher than that of the assignment=.
For large files or other files that are not necessarily text, how can i compress them and what are the most efficient methods to check for data corruption? any tutorials on these kinds of algorithms would be greatly appreciated.
For compression, LZO should be helpful. Easy to use and library easily available. For data corruption check, CRC cahttp://cppgm.blogspot.in/2008/10/calculation-of-crc.html
I am having trouble understanding this code: ``` static long long _be_decode_int(const char **data, long long *data_len) { char *endp; long long ret = strtoll(*data, &endp, 10); *data_len -= (endp - *data); *data = endp; return ret; } ``` I have changedstrtollto_strtoi64because I am programming o...
It's a "result parameter" -- you don't have to put anything into the pointer, and after the function returns it will point to the character after the number. EDIT: this is also why you are passing &endp and not just endp -- the function needs a "pointer to the pointer" so it can fill in the pointer value
While I can write a whole image to a file with ``` cvSaveImage("image.png", img); ``` how can I write only a given rectangle from the image I'm working on to a file?
There'sMatconstructor: ``` Mat(const Mat& m, const Rect& roi); ``` So just use it! Or if you usec(notc++) interface than you have to set ROI (Region Of Interest): http://nashruddin.com/OpenCV_Region_of_Interest_(ROI)/ Your code should look like this: ``` cvSetImageROI(img, rect);//rect is a ROI cvSaveImage("imag...
Does the output of the code given below depends on the compiler or it is guaranteed to be same for all the compilers? ``` int main() { int i=5; i=i/3; printf("%d\n",i); return 0; } ```
Yes, the behaviour of your example is well-defined. However, in the case of negative values, it is less clear. Pre-C99, whether integer division was rounded towards zero or towards negative infinity was left as implementation-defined: If either operand is negative, whether the result of the/operator is the larges...
I am using OpenSSL for a cuda project. I just imported all the project from win to linux (Eclipse) I solved all the dependencies except this annoying error: Invalid arguments ' Candidates are: int BN_set_word(bignum_st *, ?) ' for this line: ``` BN_set_word(two, 2); ``` and the function itself says in the bn.h ...
Sounds like you forgot to#include <openssl/bn.h>.
I have a string and I want to remove all the punctuation from the beginning and the end of it only, but not the middle. I have wrote a code to remove the punctuation from the first and last character of a string only, which is clearly very inefficient and useless if a string has 2 or more punctuations at the end. He...
Iterate over the string, use isalpha() to check each character, write the characters which pass into a new string.
How I can convert Java Object into C struct? I know that I can translate the data with XML but I need more quick and easy way to do this? What are the possible solutions?
Data serialisation is the buzz word here. For a quiet impressive list of techniques you might like to read here:http://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats
I want to get the last modified date of a file in C. Almost all sources I found use something along this snippet: ``` char *get_last_modified(char *file) { struct tm *clock; struct stat attr; stat(file, &attr); clock = gmtime(&(attr.st_mtime)); return asctime(clock); } ``` But theattrdoesn't ev...
On OS X,st_mtimespec.tv_secis the equivalent ofst_mtime. To make this portable, do ``` #ifdef __APPLE__ #ifndef st_mtime #define st_mtime st_mtimespec.tv_sec #endif #endif ``` and then usest_mtime.
``` #include<stdio.h> union node { int i; char c[2]; }; main() { union node n; n.c[0] = 0; n.c[1] = 2; printf("%d\n", n.i); return 0; } ``` I think it gives512output becouse c[0] value stores in first byte and c[1] value stores in second byte, but gives1965097472. Why ?. I compiled th...
Your union allocates four bytes, starting off as: ``` [????] [????] [????] [????] ``` You set the least two significant bytes: ``` [????] [????] [0x02] [0x00] ``` You then print out all four bytes as an integer. You're not going to get512, necessarily, because anything can be in those most significant two bytes. I...
I'm trying to find out my DNS server address by reading it from resolv.h's _res struct. According to man 3 resolver the setup code should be. ``` #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h> extern struct state _res; ``` and then I just read out whatever I need. My problem is that trying to...
You shouldn't declare_resyourself -resolv.hincludes the right declaration (despite what the man page implies).
I have the following code: ``` double dtemp = (some value) printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5, dtemp); ``` It prints out: ***Hand washing: cost per kg/item: 0.00, cost: 0.00. And when I change the constant 5 into a double variable holding 5, it prints (according to the input): **...
fconversion specifier requires adoublewhen used withprintffunctions and your are passing anint. Passing anintis undefined behavior which means anything can happen.
I have a C function that reads a stream of characters from aFILE*. How might I create aFILE*from a string in this situation? Edit: I think my original post may have been misleading. I want to create aFILE*from a literal string value, so that the resultingFILE*would behave as though there really was a file somewhere...
Standard C provides no such facility, but POSIX defines thefmemopen()function that does exactly what you want.
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)C - why is strcpy() necessary(4 answers)Closed9 years ago. Using pointers string can be initialized to other characters but when once string has been defined it cannot be initialized to other characters.What is the ...
You've definedstr1as an array, and arrays aren't assignable. You can, however, copy other data into the array, for example: ``` char str1[] = "hello"; strcpy(str1, "bye"); ```
Why this code is not running? Why str1 is not assigned to str2 ?? I know i have an option of using strcpy but i wish to know the reason why this is not working?? ``` #include<stdio.h> int main() { char str1[]="hello"; char str2[10]; str2=str1; printf("%s",str2); return 0; } ``` Whereas if I use pointers than it work...
str2is a static array. You can't just reassign it like a pointer. As for your pointer example,q=sreassignsqto point to the same space thatsis pointing to. However, the pointer reassignment doesnotcopy the value. For static arrays, usestrcpy()to copy the value. For pointers, usestrdup().
``` #include<stdio.h> int main() { int c; return 0; } // on Intel architecture #include <stdio.h> int main() { int c; return 0; }// on AMD architecture ``` /* Here I have a code on the two different machines and I want to know the 'Is the size of the data types dependent on the machine ' */
see here:size guarantee for integral/arithmetic types in C and C++ Fundamental C type sizes are depending on implementation (compiler) and architecture, however they have some guaranteed boundaries. One should therefore never hardcode type sizes and instead use sizeof(TYPENAME) to get their length in bytes.
I have to find the value of ( 1+sqrt(3) )^n where n < 10^9.As this number can be very large we have to print the ans%1000000007. I have written the following function for this. ``` double power(double x, int y) { double temp; if( y == 0) return 1; temp = power(x, y/2); if (y%2 == 0) retu...
You can't do that. You could usefmod, but sincesqrt(3)cannot be exactly represented, you'd get bogus values for large exponents. I'm rather confident that you actually need integer results ((1 + sqrt(3))^n + (1 - sqrt(3))^n), so you should use integer math, exponentiation by squaring with a modulo operation at each s...
Maybe I am misunderstanding the use of theP99library but what advantages does it provide over C11 (mainly concerned about multithreading) if anything more than being an emulator. Speed? Efficiency? Or just backwards compat?
The main advantage it provides over C11 is that it works with C99 compilers. C11 support doesn't really exist yet. It also provides many features that aren't in C11.
I looked around for a SVD library to be used in a C-code for Xcode. I foundsvdcmp.c(from the Numerical Recipes in computing) but its very very slow. I have found other SVD libraries such asSVDLIBCandCLAPACK. But they have to be compiled by the terminal. Is there a way of compiling them in Xcode? Or there might be anot...
in xcode you can include/add the accelerate/accelerate.h framework to your project. than you have access to CLAPACK which is the c version available. gdesvd_ is the function you are looking for.
When I took a class on ANSI-C in my university, I was taught a method to shorten a lot of repeating code. Basically, it's a declaration at the start using the # sign that you can use to assign a name and the code it should replace. Can anyone help me remember what this method was called, and it is possible to implemen...
You're probably thinking ofmacros. For example: ``` #define INCREMENT(x) x++ ``` However, macros are literally expanded to- meaning unless they're aggressively parenthesised, they can produce unexpected behaviour.
Consider these twoCfunctions with different headers but the same body differing only in how they return their results (via stack or pointer):T f1(int x)andvoid f2(int x, T *ret)wheresizeof(T) >= 16. Is there any performance penalty when callingf1over callingf2or the compiler likegcc -O2optimizes both calls into the si...
There would be a performance penalty from what I see. For f1, the function is going to have to create a object of type T, and then it's returning a copy of that since you didn't specify that it should be returned from reference or pointer (but then the function would have to allocate memory for it). But as for f2, yo...
I am looking through the source code fora project that relays Windows Event Log data to a syslog installation, in order to try to consolidate things on a network that I manage. The program that does this needs adjustment for our application, which I am perfectly willing to do, so I dropped in the GNU build system and...
It's not a Windows thing, it's definedin that project... ``` /* Ignored Events Structure */ struct EVENT_LIST { char source[50]; BOOL wild; int id; }; ```
I have tried to output following but got confused, ``` float f=3.4; char *cp; cp=(char *)&f; printf("%d\n",*cp); ``` normalized number I have calculated IEEE 754 std is, ``` 0 10000000 10110011001100110011001 ``` that's why I assumed at cp now value has, ``` 10011001 ``` after convert to 2's compleme...
That's becausefis being rounded up: ``` 3.4 = 10110011001100110011001 100110011001... (repeating 1001) ``` rounds up to: ``` 3.4 = 10110011001100110011010 ^ ``` when stored into single-precision floating-point. Now when you extract out the last 8 bits, you're actually getting10011010i...
When I read in a file and then output to a new file, the output is garbled, and I am trying to figure out why. I am trying to run the following code ``` #include<stdio.h> #include<stdlib.h> int main(int argc ,char *argv[]) { int c; FILE *of; FILE *f; of=fopen(argv[2],"w"); f=fopen(argv[1],"r"); ...
``` while(c=getc(f)!=EOF) ``` needs parentheses, ``` while( (c=getc(f)) != EOF) ``` the precedence of!=is higher than that of the assignment=.
For large files or other files that are not necessarily text, how can i compress them and what are the most efficient methods to check for data corruption? any tutorials on these kinds of algorithms would be greatly appreciated.
For compression, LZO should be helpful. Easy to use and library easily available. For data corruption check, CRC cahttp://cppgm.blogspot.in/2008/10/calculation-of-crc.html
I am having trouble understanding this code: ``` static long long _be_decode_int(const char **data, long long *data_len) { char *endp; long long ret = strtoll(*data, &endp, 10); *data_len -= (endp - *data); *data = endp; return ret; } ``` I have changedstrtollto_strtoi64because I am programming o...
It's a "result parameter" -- you don't have to put anything into the pointer, and after the function returns it will point to the character after the number. EDIT: this is also why you are passing &endp and not just endp -- the function needs a "pointer to the pointer" so it can fill in the pointer value
While I can write a whole image to a file with ``` cvSaveImage("image.png", img); ``` how can I write only a given rectangle from the image I'm working on to a file?
There'sMatconstructor: ``` Mat(const Mat& m, const Rect& roi); ``` So just use it! Or if you usec(notc++) interface than you have to set ROI (Region Of Interest): http://nashruddin.com/OpenCV_Region_of_Interest_(ROI)/ Your code should look like this: ``` cvSetImageROI(img, rect);//rect is a ROI cvSaveImage("imag...
Does the output of the code given below depends on the compiler or it is guaranteed to be same for all the compilers? ``` int main() { int i=5; i=i/3; printf("%d\n",i); return 0; } ```
Yes, the behaviour of your example is well-defined. However, in the case of negative values, it is less clear. Pre-C99, whether integer division was rounded towards zero or towards negative infinity was left as implementation-defined: If either operand is negative, whether the result of the/operator is the larges...
I am using OpenSSL for a cuda project. I just imported all the project from win to linux (Eclipse) I solved all the dependencies except this annoying error: Invalid arguments ' Candidates are: int BN_set_word(bignum_st *, ?) ' for this line: ``` BN_set_word(two, 2); ``` and the function itself says in the bn.h ...
Sounds like you forgot to#include <openssl/bn.h>.
I have a string and I want to remove all the punctuation from the beginning and the end of it only, but not the middle. I have wrote a code to remove the punctuation from the first and last character of a string only, which is clearly very inefficient and useless if a string has 2 or more punctuations at the end. He...
Iterate over the string, use isalpha() to check each character, write the characters which pass into a new string.
How I can convert Java Object into C struct? I know that I can translate the data with XML but I need more quick and easy way to do this? What are the possible solutions?
Data serialisation is the buzz word here. For a quiet impressive list of techniques you might like to read here:http://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats
I want to get the last modified date of a file in C. Almost all sources I found use something along this snippet: ``` char *get_last_modified(char *file) { struct tm *clock; struct stat attr; stat(file, &attr); clock = gmtime(&(attr.st_mtime)); return asctime(clock); } ``` But theattrdoesn't ev...
On OS X,st_mtimespec.tv_secis the equivalent ofst_mtime. To make this portable, do ``` #ifdef __APPLE__ #ifndef st_mtime #define st_mtime st_mtimespec.tv_sec #endif #endif ``` and then usest_mtime.
``` #include<stdio.h> union node { int i; char c[2]; }; main() { union node n; n.c[0] = 0; n.c[1] = 2; printf("%d\n", n.i); return 0; } ``` I think it gives512output becouse c[0] value stores in first byte and c[1] value stores in second byte, but gives1965097472. Why ?. I compiled th...
Your union allocates four bytes, starting off as: ``` [????] [????] [????] [????] ``` You set the least two significant bytes: ``` [????] [????] [0x02] [0x00] ``` You then print out all four bytes as an integer. You're not going to get512, necessarily, because anything can be in those most significant two bytes. I...
I'm trying to find out my DNS server address by reading it from resolv.h's _res struct. According to man 3 resolver the setup code should be. ``` #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h> extern struct state _res; ``` and then I just read out whatever I need. My problem is that trying to...
You shouldn't declare_resyourself -resolv.hincludes the right declaration (despite what the man page implies).
I am new to raw socket, and I am playing around with ip header. I noticed thatip->ip_hl = sizeof(struct ip) >> 2 //works fine;howeverip->ip_hl = hton(sizeof(struct ip) >> 2) //will not work; what i dont understand is that why not convert all the numbers to network order instead of host order in this case? what's the...
htonsis for 16-bit values.htonlis for 32-bit values. As forhton(no suffix), I'm not even sure that exists. The header length occupies only one byte (actuallypartof one byte). You don't need to flip any bytes to get it into the right form. Accordingly, there is no macro likehtonsorhtonlfor 8-bit values.
I am a beginner, trying to code C on a Mac. I am using Learn C the Hard way By Zed but when I tried running the C code on my Mac it would not run. I have installed Xcode from the mac Appstore but when I try to run my code using the command "make" or "gcc" the terminal responds command not found. Am I doing something w...
Install the Command line tools via xcode. You just go into preferences and then downloads. XCode 4.3 Command Line Tools If you still have troubles after updating xcode or installing command line tools try this install after: https://github.com/kennethreitz/osx-gcc-installer Good Luck!
I'm trying to write a program that handles detection of various objects. The objects have an origin, width, height, and velocity. Is there a way to set up a data structure/algorithm so that every object isn't checking with every other object? Some sample code of the problem I'm trying to avoid: ``` for (int i = 0; i...
You can use aquadtreeto quickly find all rectangles that intersect with another rectangle. If you need to handle non-rectangular shapes, you can first find objects whosebounding boxesintersect. Some common uses of quadtrees...Efficient collision detection in two dimensions...
It is possible From C/C++ in Ubuntu 10.04 Linux to sound the built in bell (buzzer, really) while have a sound card installed? If so, how? The goal, of course is to squawk the sounder if something is wrong with the sound card. In the best of all possible worlds, a backup speaker where my code can "say", "The sound ...
You can raise an audio/alarm character in ascii... examplecout << "\a"This will make the buzzer normally used in post tests to sound.
The problem is the following: There is a CIF video file that is supposed to be processed by the OpenCV. Unfortunately, I am not able to read frames from this video. The following code ``` cv::VideoCapture cap = cv::VideoCapture("foreman.cif"); if(!cap.isOpened()) { std::cout << "Open file error" << std::endl; ...
I don't think openCV can read raw YUV streams directly.You can use memcoder to convert it to an avi, compressed or not.Or you can use regular c/c++ to read the data blocks, copy them into an image and use cvCvtColor() to convert YUV->BGR
Is there any way to communicate with the serial port via xml messaging? I mean I want send/receive a structured packet from high level (java) which parsing by the Embedded device (C). Is there any way to do that?? If xml messaging is not possible any other alternative way to send structured packet over serial port. T...
Please have a look at SLIP and SLIPMUX to send packet oriented protocols (wich XML files basically are) over serial line. More details in this question:sending packets over serial comms java
I have an embedded board (beagleboard-xm) that runs ubuntu 12.04, I would like to read one GPIO input if it is logic 1 or 0. How can I implementcat /sys/class/gpio/gpio139/valuein C? (valuefile stores 0 or 1)I open the file by: ``` FILE *fp; fp = fopen("/sys/class/gpio/gpio139/value", "rb"); ``` what do I need to do...
If you want to read one character, try this: ``` int value = fgetc(fp); /* error checking */ value = value - '0'; ```
I use webkitgtk to add features to wxWebview and I have got a problem. I can Add a filename to soup_cookie_jar_text_new but not full path to cookie. the library uses current working directory and I want to point to my directory. something like ``` SoupCookieJar* cookie = soup_cookie_jar_text_new("/path/to/cookies/coo...
Sorry friends. There was something wrong with passing the path. So this line of code works perfectly! ``` SoupCookieJar* cookie = soup_cookie_jar_text_new("/path/to/cookies/cookie.txt", FALSE); ```
I'm not sure if the following code can cause redundant calculations, or is it compiler-specific? ``` for (int i = 0; i < strlen(ss); ++i) { // blabla } ``` Willstrlen()be calculated every time wheniincreases?
Yes,strlen()will be evaluated on each iteration. It's possible that, under ideal circumstances, the optimiser might be able to deduce that the value won't change, but I personally wouldn't rely on that. I'd do something like ``` for (int i = 0, n = strlen(ss); i < n; ++i) ``` or possibly ``` for (int i = 0; ss[i];...
I have come to know from book that for declaring a structure variable it is necessary a precedingstructkeyword, but without that precedingstructin my Bloodshed\DevC++ compiler variable can be declared without any error like following, ``` struct stype { int ival; float fval; double dval; }; ``` ...
In C it is obligatory (or you can use a typedef). In C++ not.
I've found the following macro in a utility header in our codebase: ``` #define CEILING(x,y) (((x) + (y) - 1) / (y)) ``` Which (with help fromthis answer) I've parsed as: ``` // Return the smallest multiple N of y such that: // x <= y * N ``` But, no matter how much I stare at how this macro is used in our codeb...
Say you want to allocate memory in chunks (think: cache lines, disk sectors); how much memory will it take to hold an integral number of chunks that will contain theXbytes? If the chuck size isY, then the answer is:CEILING(X,Y)
``` int first[] = {1, 4}; int second[] = {2, 3, 7}; arrayOfCPointers[0] = first; arrayOfCPointers[1] = second; NSLog(@"size of %lu", sizeof(arrayOfCPointers[0]) / sizeof(int)); ``` I want to have an array of sub arrays. Each sub array needs to be a different size. But I need to be able to find out the size of each ...
You need tostorethe size somewhere. The language does not do so for bare C arrays. All you have is the address of the first element.
I found a bug in code (the if statement should have had "==" instad of "=") and I have few questions. Example code: ``` int i = 5; if (i = MyFunction()) // MyFunction() returns an int; this is where bug was made { // call A() } else { // call B() } ``` From what I gather it should always call A().1. Is my assu...
No, it will only callA()if the assignment is considered true, i.e. non-zero.Yes, this is standard. It's not a very good way to write the code since the risk of confusion is large. Some people flip comparisons, writing the constant to the left, to avoid the risk: ``` if( 12 == x ) ``` but of course this wouldn't hav...
The input given to following program is 10 10 10 10 But the output is 0 20 Why ? ``` /* scanf example */ #include <stdio.h> int main () { short int a, b, c, d, e, f; a=b=c=d=e=f=0; scanf("%d %d",&a,&b); scanf("%d %d",&e,&d); c=a+b; f=d+e; printf("%d %d\n",c,f); return 0; } ```...
The correctscanfformat specifier forshort intis%hd, not plain%d. You are experiencing the results ofundefined behavior.
The following question was asked in a recent microsoft interview. What is the difference between the two declarations? ``` int p=*(int*)i; int p=*(int*)&i; ``` I think in the first oneiis a pointer and in the second oneiis a variable.Is there anything else?
The first is taking the value contained ini, treating it as a pointer, and retrieving whateverintvalue is at that address (if possible). The second takes the address ofi, casts it to pointer to int, and retrieves the value at that address. Ifiis anint, it's equivalent top=i;. If it's not, it's going to take the first...
I'm using Qt creator 2.4. I need to use a string sayhi"world"in my code. I have tried to useQstringandstd::stringand I know/is the escape sequence character but the IDE doesn't understand it as an escape sequence and gives errors when I write: ``` "hi/"world/"" ``` I can use any string format that can be converted i...
Use it like this: ``` QString output = "Hi \"world\"!"; ```
there's a function that I want to test the time of: function() I am not sure how to do this in C, here's the pseudocode of what I want to do: ``` int main() { int startTime = getTime(); function(); int endTime = getTime(); print endTime - startTime; } ``` How is this done in C?
Unfortunately there is no way to do this using ANSI C. However, you can do it usinggettimeofday, a POSIX function: ``` #include <sys/time.h> struct timeval tv; struct timeval start_tv; gettimeofday(&start_tv, NULL); // call your function here double elapsed = 0.0; gettimeofday(&tv, NULL); elapsed = (tv.tv_sec - ...
What's the best practice for exiting C code on discovery of an error back to R? Package guidance says don't useexit(), which makes sense (as you kill everything), but how do you exit to R and indicate an error has occurred. Obviously you could have an error flag in the return vector, but is there a better way?
You're looking forerror(). It's described inSection 6.2ofWriting R Extensions... and you should listen to your subconscious more often. ;-)
The main function goes like this: ``` void main( int argc, char** argv ){ // validate that an input was specified if( argc != 2 ) { printUsage(); return; } if( !strcmp(argv[1], "train") ) learn(); else if( !strcmp(argv[1], "test") ) recognize(); else { printf("...
Why doesn't my console wait for an input in VS2010 and Windows7? Because you don't instruct it to wait for input. Trysystem("pause");orgetchar()or something like that.
I tried to look for a specific function, e.g fstatfs, but I found the following code, it does almost nothing, I checked __set_errno macro, it's merely setting error number. ``` int __fstatfs (int fd, struct statfs *buf) { __set_errno (ENOSYS); return -1; } ``` So a set of core library are implemented in ASM, but...
I guess that the call is OS-dependent, so what you're seeing is just a stub. There seems to be some kind of alias inio/sys/statfs.h, and a candidate for the Linux implementation is insysdeps/unix/sysv/linux/fstatfs64.cfile.
I had this problem on an exam yesterday. I couldn't resolve it so you can imagine the result... Make a recursive function:int invertint( int num)that will receive an integer and return it but inverted, example:321would return as123 I wrote this: ``` int invertint( int num ) { int rest = num % 10; int div = num ...
``` int invertint( int num ) { int i ; for(i=10;num/i;i*=10); i/=10; if(i == 1) return num; return( (num % 10) * i + invertint( num / 10 ) ); } ```
I know that there is a flag that can be used in makefile to include a header file in all the files which are being compiled, just like there is a -D flag to include a define. What flag is exactly for including header files. I don't remember know.
In your compile command, you can use the-includeoption: ``` gcc -o main -include hello.h main.cpp ```
This question already has answers here:Closed11 years ago. Possible Duplicate:Most effective way for float and double comparison In my program some double variables take values of the form1.00000001. Equality check of these variables with1obviously fails. I wanted to know how can I reduce the precision of double ty...
You should almost never check floating point values for exact equality, expecially when they comes from comutation. You should check the absolute value of the difference from the compare value being less than a certain epsilon. The "precision" of the double is given by the internal number representation and you can't ...
I am trying to link a static library that I created, but I get this error. ``` libmine.a: could not read symbols: Archive has no index; run ranlib to add one ``` I tried to doranlib libmine.abut nothing changed, it still gives the same error. How can I solve this problem?
To see the symbols in an archive, use nm. ``` nm -s libmine.a ``` <output> The entry points to the subroutines should be labled "T" as in ``` 00000000 T _sub1 00000019 T _sub2 ``` What switches did you use in "ar" to make the static library? I usually use "ar -r" as in ``` ar -r libmine.a mine.o yours.o ``` If ...
i have such code (copy paste from wiki). Its multiplication of those big numbers what u see in code. My gmp version is 5.0.5. ``` #include <stdio.h> #include <gmp.h> int main() { mpz_t x; mpz_t y; mpz_t result; mpz_init(x); mpz_init(y); mpz_init(result); mpz_set_str(x, "7623234234234234...
At first it looked fine, so I had to run it myself and print out your other two variables. yis set to 0 because you have a letter "i" in the middle of your number, so it can't parse it.
There are about 50 files that need to be opened in my program for reading and i renamed all of them from 1.txt to 50.txt hoping i can pass the filename through a loop that increments the file number, but i don't know how / don't think it is possible to pass an integer to the char or is there a better way to workaround...
There is a relatively straightforward way to do it - in C, usesprintffunction, like this: ``` char filename[100]; sprintf(filename, "%d.txt", i); ``` In C++, useostringstream: ``` ostringstream oss; oss << i << ".txt"; ```
Are there any examples for how to output a raw sound buffer on Mac OS X?Something likepa_simple_write()for pulseaudio orwaveOutWrite()from WINAPI.
You need to create anAudioQueue. Next you need toallocate a buffer. Once allocated, you then fill it with data andenqueue it. Finally you callAudioQueueStart. You can then immediately callAudioQueueStoppassing false as the last parameter. The above won't work very well, though, if you need to play multiple sounds...
I am trying to link a static library that I created, but I get this error. ``` libmine.a: could not read symbols: Archive has no index; run ranlib to add one ``` I tried to doranlib libmine.abut nothing changed, it still gives the same error. How can I solve this problem?
To see the symbols in an archive, use nm. ``` nm -s libmine.a ``` <output> The entry points to the subroutines should be labled "T" as in ``` 00000000 T _sub1 00000019 T _sub2 ``` What switches did you use in "ar" to make the static library? I usually use "ar -r" as in ``` ar -r libmine.a mine.o yours.o ``` If ...
i have such code (copy paste from wiki). Its multiplication of those big numbers what u see in code. My gmp version is 5.0.5. ``` #include <stdio.h> #include <gmp.h> int main() { mpz_t x; mpz_t y; mpz_t result; mpz_init(x); mpz_init(y); mpz_init(result); mpz_set_str(x, "7623234234234234...
At first it looked fine, so I had to run it myself and print out your other two variables. yis set to 0 because you have a letter "i" in the middle of your number, so it can't parse it.
There are about 50 files that need to be opened in my program for reading and i renamed all of them from 1.txt to 50.txt hoping i can pass the filename through a loop that increments the file number, but i don't know how / don't think it is possible to pass an integer to the char or is there a better way to workaround...
There is a relatively straightforward way to do it - in C, usesprintffunction, like this: ``` char filename[100]; sprintf(filename, "%d.txt", i); ``` In C++, useostringstream: ``` ostringstream oss; oss << i << ".txt"; ```
Are there any examples for how to output a raw sound buffer on Mac OS X?Something likepa_simple_write()for pulseaudio orwaveOutWrite()from WINAPI.
You need to create anAudioQueue. Next you need toallocate a buffer. Once allocated, you then fill it with data andenqueue it. Finally you callAudioQueueStart. You can then immediately callAudioQueueStoppassing false as the last parameter. The above won't work very well, though, if you need to play multiple sounds...
I am baffled in the difference of this two in xcode, ABS(A) and abs(int). Cant seem to find ay explanation online as well. Which should I use? I am actually working on an accelerometer. Using ABS(A) and abs(int) gives me two different values. Using abs(int) would result in an inf value at times, while ABS(A) would giv...
abs()works on int, meaningabs(-10.123)would return10, whileABS()is a macro fromNSObjCRuntime.hwhich returns a value whose type is the type of the argument.
As I was debugging and optimizing one of my C/C++-projects, I often disabled and enables the profiling flags-p -g -pgand some optimization flags in my Makefile to have a better look at whats happening. However,GNU makedid not detect this change and did not do a recompile. How to properly rebuild a whole software pro...
As a suggested tweak to Stefan's above response, you can factor out build configuration into a separate file. Instead of somehow force-including this file in your code, you can list the name of this configuration file as a prereq (i.e. to the right of the colon) for all makefile rules you use to build code.
If have an enumeration like so: ``` typedef enum { ValueOne = /* some arbitrary number, NOT necessarily 0 */, ValueTwo = /* another number, NOT necessarily consecutive */ } MyEnumeration; ``` I was wondering if there is any way to get an array out of it and access a value at a specific index without doing th...
No. You will have to write the code for both the enum and the array, or use some technique to auto-generate code to reduce the maintenance burden. This article may of be some interest to you:The New C: X Macros.
I have 2 projects in a VS2010 solution. Project A generates an exe, Project B generates a DLL. The Project B DLL is used both by Project A in the solution, as well as a 3rd party program. In release mode, Project A works normally. But when I run Project A in debug mode, it tells me it is trying (and not succeeding)...
If your trying to debug project A, check if it is set as default project and check for the debug commandline or options.
I'm getting a warning by the gcc compiler and the program aborts if the following code is executed I couldn't get why? Would be great help if someone clarified it. ``` #include<stdio.h> #include<stdarg.h> int f(char c,...); int main() { char c=97,d=98; f(c,d); return 0; } int f(char c,...) { va_list li; ...
Arguments to variadic functions undergodefault argument promotions; anything smaller than anint(such aschar) is first converted to anint(andfloatis converted todouble). Sova_arg(li,char)is never correct; useva_arg(li,int)instead.
We are on designing a software in C(just C) need buffer structure in some part of that. But I do know how to choose a good one? Actually our program is open source and we need an open source and efficient buffer and queue library in C to implement this part. Thanks for your helps.
you can use this container library : https://github.com/jacob-navia/ccl its from eccentric genius jacob navia (if you are not regular at comp.lang.c you will not understand it). But the thing is the library is quiet efficient and unusually "EXCELLENT" manual. The Documentation will surely buy c coders. It has most ...
sincememcpyshould be highly optimized nowadays, does it still make sense to optimize the copy of Ipv6 addresses using explicit loop unrolling ? ``` #include <netinet/in.h> struct in6_addr IP_1; struct in6_addr IP_2; ; ; IP2.__in6_u.__u6_addr32[0] = IP1.__in6_u.__u6_addr32[0]; IP2.__in6_u.__u6_addr32[1] = IP1.__in6_u...
You should just doIP2 = IP1;, and let the compiler deal with it.
I have seen this on a program that I am tinkering: ``` static const void *method() { // other code return anotherMethod(param1,param2); } ``` For what I understand, this will return a pointer to a function. Now based onthis, I am trying to figure it what thestatic const voidare applied to: ``` int f(void); int *f...
No, the function will return aconst void*and thestaticrestricts the visibility of the function to file scope.
In thiscprogram ``` #include<stdio.h> int main() { #if UnDefinedSymbolicConstant==0 printf("UnDefinedSymbolicConstant is equal to 0\n "); #else printf("UnDefinedSymbolicConstant is not equal to 0\n"); #endif return 0; } ``` UnDefinedSymbolicConstantha...
Yes, this is specified by the standard in 6.10.1: After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0
Example: ``` $ objdump Logger.cpp.o -t 00000000 g F .text 00000000 .hidden __sti___10_Logger_cpp_0b2ae32b ```
It means that the visibility of the symbol is hidden:https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/CppRuntimeEnv/Articles/SymbolVisibility.html Reasons for changing the visibility of symbols include: Less risk of symbol collision.Smaller binaries.Reduced start-up time because th...
I have the following macro: ``` ‎#define GTR(type) \‎ type type##_gtr(type a, type b) \‎ ‎{ \‎ ‎ return a > b ? a : b;\‎ ‎}‎ ``` I understand that it generates functions, but ifGTR(unsigned int)expands outsidemain(), how do I call the generated function?_gtr(a, b)does not work...
You would have to writeunsigned int_gtr(a,b)so it would not work for that type with the macro definition you have created. The reason is that the preprocessor simply replaces thetypeparameter and joins it to the text after the ##. You could do something like create a typedef for unisgned int so there were no spaces ...
I have the following macro: ``` #define testMethod(a, b) \ if (a.length > b.length) \ return a; \ return b; ``` When I try to call it with: ``` NSString *s = testMethod(@"fir", @"sec"); ``` I get an error: "Excepted ";" at end of declaration" Why?
ifis a statement, not an expression. It can'treturna value like that. You probably mean: ``` #define testMethod(a, b) ((a).length > (b).length ? (a) : (b)) ``` The extra parenthesis around the arguments on the right side are common, and are there to protect you against unexpected precendence-related incidents. Als...
This question already has answers here:Closed11 years ago. Possible Duplicate:Left shifting with a negative shift count On a 16-bit compiler, why does32<<-3or32>>-1result in 0? what is the major reason for such a behaviour
From K&R: The shift operators << and >> perform left and right shifts of their left operand by the number of bit positions given by the right operand, which must be non-negative
In theK&R bookthere is a question as following: Write a program that converts uppercase to lower and vice versa, depending on the name it is invoked with? In the solution given, it says that when the program is invoked with the namelower, the program convertslowertoupper. In the solution programargv[0]is compared wi...
Consider this test code: ``` #include <stdio.h> int main(int argc, char** argv) { printf("ARGV[0] = %s\n", argv[0]); } ``` If I compile it as "test_argv", and run it, I get whatever I typed to run the program: ``` % ./test_argv ARGV[0] = ./test_argv % test_argv ARGV[0] = test_argv % /tmp/test_argv ARGV[0] = /tmp/...
I have this code: ``` #include<stdio.h> int main() { int a=10; switch(a) { case '1': printf("ONE\n"); break; case '2': printf("TWO\n"); break; defalut: printf("NONE\n"); } ...
defalutis just a label in your program that you can jump to withgoto. Having an editor that highlights keywords could have made this error easier to spot. I should also note that your program may have some logic errors. The character'1'is not the same as1, and the same with'2'and2.
In a dynamically created array of structs, what does every entry of the struct get initialized to? Details:If we create a dynamic array of floats like so: ``` float* arr = ( float* ) malloc ( 100 * sizeof ( float ) ); ``` then the array can be populated by anything (see here). But I am having trouble wrapping my he...
``` typedef struct { float x = 123.456; } foo; ``` You cannot have default values in structure types. This is not valid C code. Objects allocated bymallochave an indeterminate value.
I have this code: ``` #include <stdio.h> #include <unistd.h> int main() { while(1) { fprintf(stdout,"hello-out"); fprintf(stderr,"hello-err"); sleep(1); } return 0; } ``` The output ishello-errhello-errhello-errhello-errhello-errhello-er...
You need tofflushstdoutbecause usuallystdoutis line buffered and you don't issue a new line character in your program. ``` fprintf(stdout,"hello-out"); fflush(stdout); ``` stderris not fully buffered by default so you don't need tofflushit.
I have a small FPGA that needs to communicate with a C program running on a Ubuntu Machine via ethernet. The FPGA is too small to use TCP etc. I can send frames and pick them up in wireshark using just the MAC address of the ethernet port but to communicate with the C I need to use a RAW Socket however in creating the...
If you usePF_PACKETinstead ofPF_INETthen your0x55aavalue is your protocol number: ``` #include <sys/socket.h> #include <netpacket/packet.h> packet_socket = socket(PF_PACKET, SOCK_RAW, ntohs(0x55aa)); ```
Ok, I have the code done in a way that works great and uses the increment ++ and decrement -- operators. ``` unsigned int atob(const char* input) { int i = 0; while (input[i] == '0' || input[i] == '1') i++; unsigned result = 0; unsigned currentBit = --i; while ((*input == '0') || (*input == '1...
Here you go: ``` unsigned int atob(const char* input) { unsigned result = 0; while ((*input == '0') || (*input == '1')) { result = (result << 1) | (*input++ - '0'); } return result; } ``` Saves some stack space too :)
I have generated a pdf file external to my app, and once that is complete, I want to open my app and pass it the appropriate file path for use. I've looked at theCocoa Scripting Guide, but I'm not sure if this is what I need. All I really want is to pass the path of the pdf as an argument via the command line. Can ...
I assume you want to run it from a shell script of some sort? If so, you should be able to use theopencommand (manpage) to start it: ``` $ open /Applications/MyApp.app --args /path/to/file.pdf ```
Can anyone help me in the following question please? Define a macro which has the following prototype:F(A, B, C, D)After using this macro asF(name, float, a, b), you should be able to use the variablesname.aandname.b. Make sure that your implementation is reusable, i.e you can useFmore than once in the same block.Als...
Here: ``` #define F(name, type, var1, var2) struct {\ type var1 ;\ type var2 ;\ } name ``` That should work.
I can only use bitwise operations and pointer arithmetic to solve this problem. I am converting from binary to unsigned int. The function I am writing is: ``` unsigned int atob(const char* nptr); ``` atob("101") should return 5, atob("11000") should return 24, atob("11$") should return 3, and atop("") should return...
``` unsigned bits2val(char *bits) { unsigned val; for (val = 0; *bits; bits++) { if (*bits == '1') val = (val << 1) | 1; else if (*bits == '0' ) val <<= 1; else break; } return val; } ```
I am using C to open a file for reading. I have this code : ``` fp = fopen("./settings.cfg","r"); if (fp != NULL) printf("OK"); else printf("ERROR"); ``` but I always get an error. The file is located in the folder where the executable resides. I have tried writing only "settings.cfg". What might be the pro...
Tryperror()to have the library itself tell you what, if anything, is wrong. ``` fp = fopen("./settings.cfg", "r"); if (fp != NULL) printf("OK\n"); else perror("fopen"); ```
I have a Linked List and I want to implement a function: Random_Shuffle_List (struct node **Headptr)- which outputs a list such that every single node is randomly moved from its original position. Please help me with an efficient algorithm to achieve this.
I would recommend the naïve approach: Build a pointer array pointing at each node.Shuffle the array. This is way, way easier than randomizing a linked structure."Re-thread" the list by stepping through the nodes in the array's order. This uses a relatively tiny bit of extra memory, of course, but I think it's more "...
I couldn't find anything on this, but probably its just because I don't know how to search, because i don't know how to call it. I tried to compile some C-Code and got the following error: ``` /path/to/file.h:55:32: error: path/to/include.h: No such file or directory ``` I know the error and i know that the problem...
It's the number of the character within line55. This might also be referred to as "column number" (see comment) but I find that slightly misleading, as e.g. a tab character will generally take up more than one column in your editor, but still count as only one character for the compiler.
I am gettingremote certficate mismatcherror for a few cases from a peer and I am unable to track the issues from server side. After doingint ret = SSL_accept(ssl), is there a way that I can get the certificate name and its details from server (C++ binary) during SSL handshake and print that? Is there any SSL API tha...
You can useSSL_get_certificatewith the SSL session structure (which is returned in the SSL_Accept) to retrieve the X509 structure that owns the certificate served to the client. Later you can extract with some X509 specific functions the CN of the certificate: ``` X509_NAME_oneline(X509_get_subject_name(certificate),...
I wrote a process explorer using C with GUI interface. I want to add a graph to show the CPU status. Which library or functions can help me to do that?
You can useCairo, it's a simple 2D graphics library written in C.
Assume that I have some C code for a portable, non-visual library. The code relies mostly on CRT (there is no QT/DirectX/WinAPI etc. dependencies). Is there a way I could use this code in a C# application? I know about Managed C++ and that'snotan acceptable way for me. I thought of a C/C++ to C# converter that I cou...
Why not temporarily compile the C++ as managed C++, to get a .net assembly, then use Reflector to decompile it into pure C#?
can anyone suggest a openCV method which extract connected components in a 8bit single channel frame? is it cvBlobs suitable for this? In addition to this i want to use it in C code.
It seems thatcvFindContoursfunction can help you.
I have this code: ``` if(S_ISDIR(fileStat.st_mode)){ (*ls)[count++] = strdup(ep->d_name); ep = readdir(dp); } else{ (*ls)[count++] = strdup(ep->d_name); ep = readdir(dp); } ``` How can i append the string "DIR" to obtain something like: ``` if(S_ISDIR(fileStat.st_mode)){ (*ls)[count++] = "DIR "strdup(...
There are several ways of achieving this: you could usestrcat, or if you need to make multiple modifications you could usesnprintf. ``` size_t len = strlen(ep->d_name); // You need five characters for "DIR: ", and one more for the terminating zero: (*ls)[count] = malloc(len+6); strcpy((*ls)[count], "DIR: "); // ...
I'm implementing right now some syscalls from unistd.h and fcntl.h (open, read, close, e.t.c) Some of the require special flags and macros (O_CREAT, O_RDWR) Is there a way to include only the flags and macros without the function definitions from unistd.h and fcntl.h? Thanks
Perhaps the-imacrosoption togccis what you are looking for. -imacros FILEExactly like `-include`, except that any output produced by scanning FILE is thrown away. Macros it defines remain defined. This allows you to acquire all the macros from a header without also processing its declarations.
Given an arbritary unix socket address, am I able to get the number of connections on it via a POSIX api call? Or would I have to walk though the /proc filesystem?
I'll assume you mean the number of current connections on a port, not the total connection count over the lifetime of a socket fd which was my first thought. I'm afraid the most portable method is popen("netstat -n", "r") and try to parse it. POSIX gives us very little in the area of system/network administration tool...
I don't understand why this program print "klmnop" and not just "klm". b is an array of size 2! This is the code: ``` struct S { int i1; int i2; char b[2]; }; int main() { char a[] = "abcdefghijklmnop"; struct S* s = a + 2; printf("[%s]\n" , s->b); return 0; } ```
Like most string functions, your printf doesn't have any information about the size of the array that the string is contained in. It only has a pointer to a single char, and your promise that this char is the first in a sequence of chars terminated by'\0'. When asked to print the whole string, it'll keep going until i...