question
stringlengths
25
894
answer
stringlengths
4
863
The POC:https://gist.github.com/1197309 I would like to determine which of the three runs./prime,./prime 0and./prime 1have covered which code and have it nicely displayed in the HTML report. Is this possible in a straightforward fashion? How to do it? Other tools are ok, as long as they work on linux with gcc. Than...
Sure: Just rename the coverage file after each run, then examine the three files individually and create a merged HTML report. Or create HTML from the three files and merge the HTML - that might be more simple than writing a parser for the coverage output. Oh, you meant "built-in" or "simple"? No.
I'm trying to callKernelIoControlbut can't find the header file pkfuncs.h anywhere. I'm wondering if: a) Is there a secret download I need? b) Or is it not present because the device's SDK I'm using (Casio) does not include these libraries? Also ... presumably it's WINAPI? I think I'll just dynamically link to it.
You don't need the header to call KernelIoControl. Just add this to your own app: ``` extern "C" BOOL KernelIoControl( DWORD dwIoControlCode, LPVOID lpInBuf, DWORD nInBufSize, LPVOID lpOutBuf, DWORD nOutBufSize, LPDWORD lpBytesReturned ); ``` The linker will find it for you.
I have a code in which am trying to use outportb(), but while compiling it on MinGw i am getting below error. ``` C:\Users\A_TOMAR\AppData\Local\Temp\ccYPvctv.o:dsp.c:(.text+0x68): undefined reference to `outportb' ``` ``` #include <stdio.h> #include <stdlib.h> #include <dos.h> int main(void) { outportb(0x378,0xF...
Windows doesn't provide access to a hardware. You should use Win32 API calls.This function is DOS specific and unavailable in Windows Googling shows that your solution is inpout32.dll (example with weird font color)
I have an fmemopen file descriptor(pointing to a buffer in the parent) in Linux and I would like to be able to, in C, set this file descriptor as the standard input for a child process(for whom I do not have access to the code) Is this possible? If so how do I do it? I would like to avoid having to write to disk if...
This is not possible. Inheriting stdin/out/err is based purely on file descriptors, not stdio FILE streams. Sincefmemopendoes not create a file descriptor, it cannot become a new process's stdin/out/err or be used for inter-process communication in any way. What you're looking for is a pipe, unless you need seeking, i...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Ear clippingis by far the best way to do this. It is fully robust for both convex and concave polygons and runs in O(n^2) time
Assuming that in UDP, i know that packets i am receiving are 200 bytes each. In C socket programming: ``` n = recvfrom(sockfd,mesg,1000,0,(struct sockaddr *)&cliaddr,&len); ``` if i define the buffersize as 1000. Does that mean i can received 5 packets each time? Or i will only still get 1 packet and the remaining ...
If you KNOW your packets will NEVER exceed 200 bytes, then there's no need to declare your buffer any larger than 200 bytes. Each recvfrom() will receive AT MOST one packet. Remaining packets are buffered by the stack. There is really no "performance penalty" from reading multiple packets in a "while()" loop.
I have the following code in C, Its basically a maze where S=starting point G=Goal .=open path and #=dead end ``` char maze[6][6] = { "S...##", "#.#...", "#.##.#", "..#.##", "#...#G", "#.#..." }; ``` I am trying to convert into c#, here is my attempt ``` char[,] maze = new char[6,6]; ``` ...
``` char[,] maze = new char[6,6] { {'a','b','c','d','e','f'}, {'g','h','i','j','k','l'}, {'a','b','c','d','e','f'}, {'a','b','c','d','e','f'}, {'a','b','c','d','e','f'}, {'a','b','c','d','e','f'} }; ``` Edit:http://msdn.microsoft.com/en-us/library/2yd9wwz4%28v=vs.71%29.aspx
What folder do I place a file to pass in as a command line argument in xcode 4? I'm placing my list.txt file in the folder that xcode created but when I test for the existence of the file I'm getting NULL.I thought that when I edit the scheme and add list.txt as an argument that the file would be passed in.
Either you should pass the full path to the file, or you need to figure out the working directory that Xcode launches the executable in: ``` NSString *workingDir = [[[NSProcessInfo processInfo] environment] objectForKey:@"PWD"]; NSLog(@"working directory = %@", workingDir); ``` and put your file in that dir.
I need to open a text document and read it's data. One of the data points in this file is an int that I need to use to create a data structure. Question: Once I open a file passed in from the command line with fscanf() can I read the file again with fscanf() or another stream reading function? I have tried do this by...
In order to re-read all or a portion of an opened file, you need to reposition the stream. You can usefseek()to reposition the file stream to the beginning (or other desired position): ``` int fseek(FILE *stream_pointer, long offset, int origin); ``` e.g. ``` FILE *file_handle; long int file_length; file_hand...
I need a management application running with no-gui, doing some periodic jobs and connectable anytime by another console or desktop application. On Linux, it would be a daemon. Is Windows service project equivalent on Windows?
If you want a program to run periodically, you should consider using Task Scheduler (the equivalent of cron) - setting this up will be much easier than using a Windows Service. However, if you need to be able to connect to it 24/7, you are correct that a Windows Service is equivalent.
I have to read strings of different length in C.I can do it using an array of pointers and using ,alloc inside the loop.The problem is that the input to the program is a series of sentences like this: Rene Decartes once said,"I think, therefore I am." and there can be many more. How can I check programmaticaly that ...
Maybe he's even looking for the end-of-file (end of input, end of stream). You can detect the end of the input stream by checking the return value of various input functions. You did not tell us which function you use for reading input. E.g. withfgets()and input on standard input you would do ``` #include <stdio.h> ...
A foremention, the following is in a header file: ``` typedef struct{ void* userData; } ESContext; ``` and, in the source file, there is the following structure: ``` typedef struct { GLuint programObject; } UserData; ``` So here goes. In the same source file there is a function that begins as thus: `...
It assigns the pointer esContext->userData to the pointer userData. The C language allows implicit cast between void pointers and pointers of any other type. You might want to read the section of theC FAQ relating to Pointers.
I wrote this little program to illustrate my problem : ``` int main(int argc, char* argv[]) { int i = 0; while(1) { std::cout << i++ << std::endl; Sleep(1000); } return 0; } ``` So this simple program will stop counting if you hold the vertical scroll bar ( to watch back logs or whateve...
Not really. What happens is that holding the scrollbar prevents the application to write any new output to the console, so it eventually blocks on flushing std::cout. This is due to how Windows implements the console and can not be avoided.
I am trying to parse a string that has some numbers seperated by a space. However, these numbers could be integers or floats. Is there a way in scanf to parse both integers and numbers as one collective float? For example: ``` float arg1, arg2 = 0; sscanf("LINE 10 10", "LINE %f %f", &arg1, &arg2); // and sscanf("L...
It just works, integers are special cases of floating points. Note, however, that large integers might not be able to be represented precisely by floats (eg.1e9 + 1), but I don't think you bother about that.
A multithreaded application hangs and it is not responding to any commands. I have tried following things without luck: Attach a process to gdb (error: (gdb) attach 6026 Attaching to process 6026 ptrace: Operation not permitted.)gstack (gstack just hangs l...
Thanks for all your response. The problem is at kernel level. we used echo t > /proc/sysrq-trigger, which logs the stack of all the running process in /var/log/messages. This stack trace helped to analyze the problem. From the stack trace, file system posted some waited event on behalf of the application process to o...
i need a library with functions for generating random number, given average, standard deviation and using one of three distribution - exponential, normal or unified. even one of the three would help. i'm looking for something like this -http://www.codeproject.com/KB/recipes/zigurat.aspx, but in c. thanks
May I recommend theGNU Scientific Libraryeither for use or for inspiration? It has severalRandom Number Distributionsand is designed to be used from C and C++.
``` if(stat("seek.pc.db", &files) ==0 ) sizes=files.st_size; sizes=sizes/sizeof(int); int s[sizes]; ``` I am compiling this in Visual Studio 2008 and I am getting the following error: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0. I tried using vector s[si...
The sizes of array variables in C must be known at compile time. If you know it only at run time you will have tomallocsome memory yourself instead.
Is there a way with feature test macros to have glibc expose GNU extensions (functions not specified in POSIX, and additional flag/argument macros for standard functions, likeMAP_ANONYMOUS), but still prefer POSIX semantics whenever the POSIX and GNU definitions conflict? I'm thinking things likebasename,strerror_r, e...
For the specific case ofbasename(), including<libgen.h>header gives you the XPG / POSIX definition. MAP_ANONYMOUSisn't a GNU extension (_GNU_SOURCE), it's defined if either_BSD_SOURCEor_SVID_SOURCEis defined.
A foremention, the following is in a header file: ``` typedef struct{ void* userData; } ESContext; ``` and, in the source file, there is the following structure: ``` typedef struct { GLuint programObject; } UserData; ``` So here goes. In the same source file there is a function that begins as thus: `...
It assigns the pointer esContext->userData to the pointer userData. The C language allows implicit cast between void pointers and pointers of any other type. You might want to read the section of theC FAQ relating to Pointers.
I wrote this little program to illustrate my problem : ``` int main(int argc, char* argv[]) { int i = 0; while(1) { std::cout << i++ << std::endl; Sleep(1000); } return 0; } ``` So this simple program will stop counting if you hold the vertical scroll bar ( to watch back logs or whateve...
Not really. What happens is that holding the scrollbar prevents the application to write any new output to the console, so it eventually blocks on flushing std::cout. This is due to how Windows implements the console and can not be avoided.
I am trying to parse a string that has some numbers seperated by a space. However, these numbers could be integers or floats. Is there a way in scanf to parse both integers and numbers as one collective float? For example: ``` float arg1, arg2 = 0; sscanf("LINE 10 10", "LINE %f %f", &arg1, &arg2); // and sscanf("L...
It just works, integers are special cases of floating points. Note, however, that large integers might not be able to be represented precisely by floats (eg.1e9 + 1), but I don't think you bother about that.
A multithreaded application hangs and it is not responding to any commands. I have tried following things without luck: Attach a process to gdb (error: (gdb) attach 6026 Attaching to process 6026 ptrace: Operation not permitted.)gstack (gstack just hangs l...
Thanks for all your response. The problem is at kernel level. we used echo t > /proc/sysrq-trigger, which logs the stack of all the running process in /var/log/messages. This stack trace helped to analyze the problem. From the stack trace, file system posted some waited event on behalf of the application process to o...
i need a library with functions for generating random number, given average, standard deviation and using one of three distribution - exponential, normal or unified. even one of the three would help. i'm looking for something like this -http://www.codeproject.com/KB/recipes/zigurat.aspx, but in c. thanks
May I recommend theGNU Scientific Libraryeither for use or for inspiration? It has severalRandom Number Distributionsand is designed to be used from C and C++.
``` if(stat("seek.pc.db", &files) ==0 ) sizes=files.st_size; sizes=sizes/sizeof(int); int s[sizes]; ``` I am compiling this in Visual Studio 2008 and I am getting the following error: error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0. I tried using vector s[si...
The sizes of array variables in C must be known at compile time. If you know it only at run time you will have tomallocsome memory yourself instead.
Is there a way with feature test macros to have glibc expose GNU extensions (functions not specified in POSIX, and additional flag/argument macros for standard functions, likeMAP_ANONYMOUS), but still prefer POSIX semantics whenever the POSIX and GNU definitions conflict? I'm thinking things likebasename,strerror_r, e...
For the specific case ofbasename(), including<libgen.h>header gives you the XPG / POSIX definition. MAP_ANONYMOUSisn't a GNU extension (_GNU_SOURCE), it's defined if either_BSD_SOURCEor_SVID_SOURCEis defined.
I have a standard c function with the following prototype ``` extern void lcd_puts(const char *s); ``` in my other function i have something like this ``` send_to_lcd() { uint8_t count = 10 lcd_puts(count); } ``` my question is how do i convert count to a string pointer to be able to send it to lcd_puts which ...
On a microcontroller, you have to be at least a little worried about performance (which rules outsprintf), even division is a very expensive operation on such chips. So you want code optimized for a microcontroller. I've written some here:http://ideone.com/SsEUW(will need a few changes for use with C-style strings i...
I have a problem with this. Here's the specific part of my C code: ``` unsigned char *p; char s[1048]; int m[1048], r[2]; int e = 0, L = 0, mov = 0, ri, i; for(*p = s; *p; ++p, mov += m[L++]) m[L] = min(*p - 'A', 'Z' - *p + 1); ``` Now i got the message - assignment makes integer from pointer without a cast. ...
Change the for. Drop the*so you will correctly assign to achar *: ``` for(*p = s; *p; ++p, mov += m[L++]) ^ ```
``` #include <stdlib.h> inline int f0(int a) { return a*a; } inline int f1(int a) { return a*a*a; } int main() { int (*f)(int); f = rand()%2 ? f0 : f1; return f(rand()); } ``` So with gcc, asm file generated is same with or without inline. Is it same with any code with function pointers?
Function pointers cannot be inlined unless their value is fully decidable at compile time. Your case is not decidable. Most of the time function pointers will never be inlined, even if the compiler can see which function is in the function pointer.
Ansi C allows that two different structs can contain pointers to each other (also shown instructs-that-refer-to-each-other). I know that this is not a good idea in many circumstances, but that's not the question here. Is it possible to achieve the same using typedef'ed structs? The code below works just fine. ``` st...
You can do this instead: ``` typedef struct a A; typedef struct b B; struct a { B *bb; }; struct b { A *aa; }; ``` Does this work for you ?
I have the code: ``` wchar_t* temp = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1000 * sizeof(wchar_t)); wchar_t* temp2 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1000 * sizeof(wchar_t)); GetTempPathW(1000, temp); GetTempFileNameW(temp, L"vdr", GetCurrentProcessId(), temp2); HeapFree(GetProcessHeap(), 0, t...
You are freeing the memory before callingMessageBox(). In any case, there's no need to useHeapAlloc(), just usemalloc(). In fact, sinceGetTempFileName()has a maximum buffer size ofMAX_PATH, it's easiest to do this with stack allocated buffers.
I need to handle unicode strings in C. I have heard that ICU is the appropriate set of libraries to use but I am not having any luck getting started. So my question: Can anyone provide a link to a good beginners tutorial on using unicode strings with ICU in C P.S. I have installed libicu44 (under Ubuntu 11.04).
ICU Reference Documentation Tutorial
I have been able to use gnuplot to plot graphs as I run my program, but now I want to write the graphs to files. The following code opens a plot and creates a png, but the png does not open (Gimp says it is corrupted). Admittedly I don't really understand the code I've written, because it's taken from snippets online....
You wantset terminal pnginstead.
I'm beginner in C. I have an char array in this format for example "12 23 45 9". How to convert it in int array {12,23,45,9}? Thanks in advance.
Usesscanf, orstrtolin a loop.
see i want to count total no of code line, comment line in my whole project so is there any command or script inlinuxmachine for that purpose. Is there any script for counting no of code in particular directory? NOTE : my code is written in c langauge
UseCLOC.
How could one initialize and set an array at the same time? I'm looking for something equivalent to this: ``` int mat[2][2]={{1,1},{1,0}}; ``` in mpz_t. Cheers.
mpz_t is more or less opaque to you, and it requires function calls to initialize. So you can't initialize it with a C initializer.
I'm doing a project that makes unix system calls. To be specific, my project heavily relies of calls to getcontext(), makecontext(), swapcontext() and setcontext(). I tried to debug my code using gdb. I stepped into the code line by line and examined the control but once a call to swapcontext() is made, it doesn't st...
setcontext and swapcontext calls change the program's stack, and gdb gets confused. I do not know whether some other debugger can handle it nicely.
This question already has answers here:Closed12 years ago. Possible Duplicate:"static const" vs "#define" in c A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. (No memory required) So, people use it as a method to define constants ins...
Macros can be used for other reasons than just defining constants. Nowadays, macro usage is generally frowned upon unless there are absolutely no other options available. Debugging complex code with macros littered throughout can cause you more than one headache. FromGCC docs: A macro is a fragment of code which ha...
I have one functionextern "C" int ping(void)in a C++ "static-library" project. Now, I would like to write a simple Hello-WorldCprogram that will call this functionint x = ping();. I useg++ / gccbut I cannot link theCexecutable withC++shared library. Please, how can one do that? Could you please provide exactgcccomman...
You may have to use g++ as the linker, not gcc. If theping()function uses any STL, or exceptions, new, etc, it probably links againstlibstdc++, which is automatically linked in when you use g++ as the linker.
I'm using lighttpd and wrote the following cgi script: ``` main(){ printf("Content-type: text/html\n\n"); char * pwd =""; pwd=getenv("PWD"); printf ("The current path is: %s",pwd); } ``` The Result is ``` The current path is: (null) ``` Well, I don't get why. And I don't know how to find the path o...
Usegetcwd()instead.PWDisn't required to be set. ``` #include <unistd.h> char *getcwd(char *buf, size_t size); ```
I am writing a small C application using winapi. There I've got a window with a child window (toolbox). I am able to keep it inside this window and so on, but my question is: How to keep the main window active, if the child window gets focused? The main window gets grayed out in this moment. The windows get created ...
I've found out that simply creating it asWS_CHILDand explicitlyNOTasWS_POPUPsolves that. It also turns the absolute window coordinates to relative ones so that I dont have to care about the window position anymore by moving the parent window. // Solved
I am using Ubuntu Lucid Lynx is it possible to write data in a file through a C program which has read only permission. If it's not possible, then is there any way to give sudo access to the C program. For files without permissions, I would save the data in a string. Then i would open the file with write option: ``...
No you cannot write to a read-only file, that would undermine the whole point of read-only. As for giving root access to a c program, you could always run it as root or as someone who has permissions to modify the file.
i just want to implement below statement ``` "if bin folder is not available in current directory then make new bin folder & if bin folder is available then its do nothing" ``` can anybody give me any idea how can i do this? EDIT : i dont want any error like ``` mkdir: cannot create directory `./bin `./bin': Fil...
You can just do this: ``` -mkdir ./bin ``` If./binalready exists thenmkdirwill fail silently, otherwise it will create the directory.
I'm looking for a free implementation that finds theminimum bounding box(MBB- the box around a cloud of 3D points with the smallest volume). It should be written in either C or C++. An algorithm to do this was published by Joseph O'Rourke and is cubic in time. I'd also be content with an approximate MBB genered for i...
Seehttp://valis.cs.uiuc.edu/~sariel/research/papers/00/diameter/diam_prog.htmlwhich has full code of the Barequet and Har-Peled algorithms.
I have some Matlab functions that I have to translate in C but I do not understand the syntax or the behaviour to create. I have this call and the following implementation: ``` { ... [vSolution,sReturnVal] = Func1(10, @(X) Func2(X, hour_of_the_day)); ... } function [SolutionVector,ReturnValue] = Func1(IterationsTer...
Itisdefining an anonymous function. But that anonymous function happens to callFunc2. The anonymous function is equivalent to: ``` function Y = myFunc(X) Y = Func2(X, hour_of_the_day); ```
I am using Libcurl in my application with C and GNU compiler on a linux machine. Application also uses OpenSSL libraries and some other libraries. I am trying to statically link the libraries, except forlcurllinking with other libraries works fine. I am trying to compile as below. ``` gcc -static -I. -o test test.c ...
Libcurl is itself linked against atonof other libraries, most of which aren't included in your compile command line. For instance, mine (on Debian Squeeze) links against: libclibcom_errlibcryptolibdllibgcryptlibgnutlslibgpg-errorlibgssapi_krb5libidnlibk5cryptolibkeyutilslibkrb5libkrb5supportliblber-2.4libldap_r-2.4li...
Wouldn't it have made more sense to make long 64-bit and reserve long long until 128-bit numbers become a reality?
Yes, it does make sense, but Microsoft had their own reasons for defining "long" as 32-bits. As far as I know, of all the mainstream systems right now, Windows is the only OS where "long" is 32-bits. On Unix and Linux, it's 64-bit. All compilers for Windows will compile "long" to 32-bits on Windows to maintain compa...
Given the following code: ``` #include <stdio.h> int main() { int *p; p = (int *)malloc(10 * sizeof(int)); while(1); return 0; } ``` When the above code is compiled and run, and is interrupted while in execution by pressingCtrl+C, how is the memory allocated topfreed? What is the role of the Operat...
When a process terminates, the operating system reclaims all the memory that the process was using. The reason why people make a big deal out of memory leaks even when the OS reclaims the memory your app was using when it terminates is that usually non-trivial applications will run for a long time slowly gobbling up ...
Is it possible to useIntel C++compiler (icc) in Eclipse (CDT) on Windows? How?
For what I could read inthis forum"no such integration is currently supplied in the Windows environment for the Intel C++ compiler". Alternatively, there is MinGW, a free tool for developing Microsoft applications and it gives access to the functionality of the Microsoft C runtime. Seeherehow to set it up with Eclip...
This code: ``` int p = 10; void *q; *q = 10; ``` Does not compile: '=' : cannot convert from 'int' to 'void *' However, this code compiles fine: ``` int p = 10; void *q; q = &p; ``` What is the reason behind it?
Avoid *points to data of an unknown type (if it is initialized, which yours is not). You can only assign to variables of a known type, or via pointers of a known type. ``` int p = 10; void *q = &p; *(int *)q = 20; if (p != 20) ...something has gone horribly wrong... ``` This converts thevoid *into anint *and ...
I am writing this code to access a file in eclipse CDT ``` ifstream inFile; ofstream outFile; string next; inFile.open("input.txt"); if (inFile.fail()) { cout << "\nCould not open input.txt"; exit(1); } ``` the problem is when I try to debug my app or run my app from inside eclipse it cannot find the input...
It could be an issue with relative paths. Isinput.txtin the root directory of your project? Eclipse makes the top-level directory of the project the working directory. If you replace"input.txt"in your code with the fully qualified file name, that should also work.
I useVisual Studio 2010and Intelicccompiler forCdevelopment. I useC99but editor is still showingC99constructs as errors (compiling is fine). How to get rid of it? Second question, is it possible to useEclipse(CDT) with Intel compiler on Windows?
As mentioned in the responses to your post, the problem you're seeing is with your intellisense only. You can turn off intellisense error reporting in VS2010: Tools > Options > Text Editor > C/C++ > Advanced. Under IntelliSense, choose "Disable Error Reporting" and set it to "True".
I want to write some C code such that gcc using the-msse4.1flag can optimize it. Basically I want to check whether or not the compiler is taking advantage of SSE4.1 instructions. There are many SSE4.1 instructions (http://en.wikipedia.org/wiki/SSE4#New_instructions) but I am not able to write a fragment of C Code whi...
From what I've seen, compilers rarely ever generate SSE4.1 instructions. I've seen a few cases where it will use the insert/extract instructions to pack data. But for the most part, if you want to use the SSE4.1 instructions, you need to do them explicitly using intrinsics: http://software.intel.com/sites/products/d...
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.Closed12 years ago. I am getting two errors in code blo...
Ensure you have set correctly LD_LIBRARY_PATH for searching library path. The linker is looking for static library files libc.a and libm.a. They are standard c library and math library.
I have been looking all over the internet on how exactly to use the Perlin noiseclass(the C version), but I can't seem to find anything. Here's what I'm doing: ``` double height = noise1(12); NSLog(@"%f", height); ``` I set a double equal to noise1 with a random argument. Then I output height to the console with th...
Try, e.g., ``` for(double x = 0; x < 10; x+=0.1) { double height = PerlinNoise1D(x,2,2,n); //... } ``` Herexis the coordinate of the texture; it seems the functions the code is blending together are all 0 at integer values ofxso it makes sense that their blend is also always0. As best as I can tellnis the number...
``` printf("what is your name?"); gets(send_name); strcpy(send_name2, strcat("You are connected to ", send_name)); send(connected, send_name2, strlen(send_name2), 0); ``` The other executable is not receiving what i sent... ``` nbytes_recieved = recv(sock, recv_name, 50 ,0); recv_name[nbytes_recieved] =...
strcatexpects as its first argument a writeable buffer. What you give to it is a constant string, probably stored somewhere in a read-only area of the process. The function attempts to write right after this constant string, which results in a memory access violation.
Can you guys please explain the below program ``` int main() { int max = ~0; printf("%d\n",max); return 0; } ``` AFAIK ~ will flip the bits. In this case i.e ~0 will set all the bits into 1. So max variable should contain MAX value but I am getting o/p as -1. So can anyone here please tell me why I am g...
Why did you expect to obtain the "max value"? In 2's-complement signed representation all-1 bit pattern stands for-1. It is just the way it is. Maximum value in 2's-complement signed representation is represented by01111...1bit pattern (i.e the first bit is0). What you got is1111...1, which is obviously negative sinc...
I've removed the import of the UIKit framework, and now I get this error. Do I have to somehow recompile the framework? It's not really giving me anything to go on... And if it means anything, I am able to run the SDK examples in IOS so there aren't any system requirements that I'm not meeting. ``` ld: warning: ig...
You can't just use the.frameworkprovided by Amazon, because the binary is only for iOS. You need to rebuild the framework from the source, which thankfully comes in the SDK.
C supports concatenating constant strings at compile-time. Can I do the same for any constant array? (E.g. concatenate two char ** arrays.)
Basically no, but you can always workaround this with the preprocessor. The trick is to define arrays without curly braces: ``` #define ARRAY_ONE "test1", "test2", "test3" #define ARRAY_TWO "testa", "testb", "testc" ``` Now, you can join arrays in compile time with comma. To use them, however, you will either have t...
i've managed to succesfully create an .php extension. I would like to move further. Insted of using the .cc that i want my .php to link with i would like to add the library.so. When compiling i have this error. how to solve it? thx. appreciate EDIT: I succed to compile it. now i have this error: undefined symbol:...
I guess you need to link withlibstdc++. Or compile withg++instead ofgcc, thenlibstdc++will be linked by default.
I want to make a thread sleep for an indefinite amount of time. The reason I want to do this is because my program only takes action when it receives a signal and has nothing to do in the primary thread. Therefore, all processing is done inside the signal handler. How can I sleep for an indefinite amount of time?
I believe you're looking for thepausefunction: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pause.html You could do something like:for (;;) pause();
When sending a signal from one process to another, I also want to send a value of typelong. Is that possible? I am using SIGUSR1.
Sure you can, but you'll have to send it withsigqueue(2)instead ofkill(2). And you can send anintor asival_ptr. ``` union sigval { int sival_int; void *sival_ptr; }; ``` Establish the handler ``` struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_sigaction = handler; sa.sa_flags = SA_SIGINFO; /* Importa...
I can only use these symbols: ! ~ & ^ | + << >> Here is the table I need to achieve: ``` input | output -------------- 0 | 0 1 | 8 2 | 16 3 | 24 ``` With the output I am going to left shift a 32 bit int over. Ex. ``` int main() { int myInt = 0xFFFFFFFF; myInt = (x << (myFunction(2))...
Well, if you want a function withf(0) = 0,f(1) = 8,f(3) = 24and so on then you'll have to implementf(x) = x * 8. Since 8 is a perfect power of two the multiplication can be replaced by shifting. Thus: ``` int myFunction(int input) { return input << 3; } ``` That's all.
I read that there is a funciton called alloca that allocates memory from the stack frame of the current function rather than the heap. The memory is automatically destroyed when the function exits. What is the point of this, and how is it any different from just crating an array of a structure or a local variable wi...
When you usealloca, you get to specify how many bytes you want at run time. With a local variable, the amount is fixed at compile time. Note thatallocapredates C's variable-length arrays.
I am gathering data into a char[][] array, then let a user choose which of those string to write to a file. So I'm doing for example ``` char arr[3][3]; // assume there are three different two-char long strings in there FILE* f = fopen("file", "w"); fputs(arr[1], f); fclose(f); ``` Now the problem is, I'm getting a ...
Make sure the file pointer returned byfopenisn't NULL; assumingarrcontains valid 0-terminated strings, that's the only other thing I can think of that would causefputsto barf.
Suppose some memory location 0xF0000 contains four character string"four". so is this valid: ``` char *mem = (char*) 0xF0000; ``` and then is mem[0] == 'f' ?
Yes it is valid if 0xF0000 is the starting address of the four character string "four"
This question already has answers here:Closed12 years ago. Possible Duplicate:What is the signature of printf?Does C support overloading?Does printf support function overloading In C? C'sprintffunction seems to show method overloading as different types of arguments can be given to it. Is this right orprintfis somet...
printf()is something else that is calledvariadic function. The exact number and types of its arguments is specified through its first one, the format. Other variadic functions have other ways of specifying number and/or type of arguments but it is always through one fixed argument.
I need to use a returned value of a C function in objective C..for Ex:consider a file samplec.h & samplec.c..It contains method definition for display i.e.. ``` char *display() { char *b="Hi"; printf("%s",b); return b; } ``` This returned value should be called and used in objective C function i.e..in s...
``` // sampleObjC.m #include sampleC.h - (void)myMethod { NSString *string = [NSString stringWithUTF8String:display()]; NSLog(@"%@", string); } ```
see if i have made one c program in c on linux machine now if i want to compile that program on other os or lets say on windows how can i do that.? what if i have used os specific things like pthread.h, in that program.? Is there any direct way to do so.?
see if i have made one c program in c on linux machine now if i want to compile that program on other os or lets say on windows how can i do that.? Then I hope you were paying attention which APIs are available on Windows and which are not. This is not an easy problem to solve. As you have usedpthreads, there is no ...
I would like to create an executable of my two mycode.c and my main.c, how can I create an executable? i did gcc mycode.c main.c and it generates a a.out, but when i click it it would not run.. (i am new to this so please bear with me) Thank you
Try this ``` gcc mycode.c main.c -o myprogram ``` Then run./myprogram If you double click it you probably won't see anything, you should instead try running it from the command line, where you compiled it from in the first place.
I would like to use setjmp and longjmp in a C program that links to a library that is implemented in C++ (but has a C API). The C++ code does do dynamic memory allocation and pointers get passed through the API, but as long as the C side of the code manages those (opaque) objects correctly, there shouldn't be any mes...
The fact that you call C++ functions from your C code does not make setjmp and longjmp more unsafe than they always are. What's important is that if your library allocates resources you must have recovery code in place to ensure that those are released properly after longjmp is called. While this is likely easy for y...
Out of all of the functions which aren't referenced, my gluPerspective returns an error when I try to use it. I know it has nothing to do with syntax or human error: I've been copy/pasting the line of code used by it right out of an SFML tutorial. I'm using QT Creator. Could someone tell me why this may be the case,...
A function not being referenced sounds like a linker error. Have you linked to the glu library?
I've been trying to get a program's STDOUT redirecting to a file. So far, this code works well: ``` FILE *output = fopen("output","w"); if (dup2(fileno(output),1) == -1) { /* An error occured. */ exit(EXIT_FAILURE); } ``` The issue is, I'm trying to stick to ANSI C, and fileno isn't ANSI. When I compile with...
The ANSI C way to do it isfreopen(): ``` if (freopen("output", "w", stdin) == NULL) { /* error occured */ perror("freopen"); } ```
I'm back again with another string problem. I've no idea what's wrong with this. I'm trying to pass a string into a function but GCC expects an expression from me. Help is appreciated. These errors are always so hard to debug! ``` if (fmenu == 1) { printf("\nEnter the file name: \n"); scanf("%s", name); /* p...
name[]isn't a valid expression. You needfileoperations(name);
The following code confused me a bit: ``` char * strcpy(char * p, const char * q) { while (*p++=*q++); //return } ``` This is a stripped down implementation ofstrcpyfunction. From this code, we see that pointerpandqare incremented then dereferenced andqis assigned topuntil the\0char has been reached. I would li...
Because the++is after the variables, they aren't incremented untilafterthe expression is evaluated. That's why it's the post-increment operator; the pre-increment is prefixed (++p).*++pwould write to the second spot,*p++writes to the first.
``` void normalizeStepOne (double F[], double hsum, double V, double Fkjsum) { int i; F[i] = hsum/V; Fkjsum+=F[i]; return; ``` in main I try to call this function in this way: ``` normalizeStepOne (double F[0], double Csum, double VC, double Fkjsum); ``` and I got error: syntax error before 'double' ...
You must not include type declarations at the call site. Instead it should read something like this: ``` double F[ARRAY_LEN]; double Csum; double VC; double Fkjsum; /* initialize the variables */ normalizeStepOne(F, Csum, VC, Fkjsum); ```
I can only use these symbols: ! ~ & ^ | + << >> Here is the table I need to achieve: ``` input | output -------------- 0 | 0 1 | 8 2 | 16 3 | 24 ``` With the output I am going to left shift a 32 bit int over. Ex. ``` int main() { int myInt = 0xFFFFFFFF; myInt = (x << (myFunction(2))...
Well, if you want a function withf(0) = 0,f(1) = 8,f(3) = 24and so on then you'll have to implementf(x) = x * 8. Since 8 is a perfect power of two the multiplication can be replaced by shifting. Thus: ``` int myFunction(int input) { return input << 3; } ``` That's all.
I read that there is a funciton called alloca that allocates memory from the stack frame of the current function rather than the heap. The memory is automatically destroyed when the function exits. What is the point of this, and how is it any different from just crating an array of a structure or a local variable wi...
When you usealloca, you get to specify how many bytes you want at run time. With a local variable, the amount is fixed at compile time. Note thatallocapredates C's variable-length arrays.
I am gathering data into a char[][] array, then let a user choose which of those string to write to a file. So I'm doing for example ``` char arr[3][3]; // assume there are three different two-char long strings in there FILE* f = fopen("file", "w"); fputs(arr[1], f); fclose(f); ``` Now the problem is, I'm getting a ...
Make sure the file pointer returned byfopenisn't NULL; assumingarrcontains valid 0-terminated strings, that's the only other thing I can think of that would causefputsto barf.
Suppose some memory location 0xF0000 contains four character string"four". so is this valid: ``` char *mem = (char*) 0xF0000; ``` and then is mem[0] == 'f' ?
Yes it is valid if 0xF0000 is the starting address of the four character string "four"
This question already has answers here:Closed12 years ago. Possible Duplicate:What is the signature of printf?Does C support overloading?Does printf support function overloading In C? C'sprintffunction seems to show method overloading as different types of arguments can be given to it. Is this right orprintfis somet...
printf()is something else that is calledvariadic function. The exact number and types of its arguments is specified through its first one, the format. Other variadic functions have other ways of specifying number and/or type of arguments but it is always through one fixed argument.
I need to use a returned value of a C function in objective C..for Ex:consider a file samplec.h & samplec.c..It contains method definition for display i.e.. ``` char *display() { char *b="Hi"; printf("%s",b); return b; } ``` This returned value should be called and used in objective C function i.e..in s...
``` // sampleObjC.m #include sampleC.h - (void)myMethod { NSString *string = [NSString stringWithUTF8String:display()]; NSLog(@"%@", string); } ```
see if i have made one c program in c on linux machine now if i want to compile that program on other os or lets say on windows how can i do that.? what if i have used os specific things like pthread.h, in that program.? Is there any direct way to do so.?
see if i have made one c program in c on linux machine now if i want to compile that program on other os or lets say on windows how can i do that.? Then I hope you were paying attention which APIs are available on Windows and which are not. This is not an easy problem to solve. As you have usedpthreads, there is no ...
I would like to create an executable of my two mycode.c and my main.c, how can I create an executable? i did gcc mycode.c main.c and it generates a a.out, but when i click it it would not run.. (i am new to this so please bear with me) Thank you
Try this ``` gcc mycode.c main.c -o myprogram ``` Then run./myprogram If you double click it you probably won't see anything, you should instead try running it from the command line, where you compiled it from in the first place.
I would like to use setjmp and longjmp in a C program that links to a library that is implemented in C++ (but has a C API). The C++ code does do dynamic memory allocation and pointers get passed through the API, but as long as the C side of the code manages those (opaque) objects correctly, there shouldn't be any mes...
The fact that you call C++ functions from your C code does not make setjmp and longjmp more unsafe than they always are. What's important is that if your library allocates resources you must have recovery code in place to ensure that those are released properly after longjmp is called. While this is likely easy for y...
Out of all of the functions which aren't referenced, my gluPerspective returns an error when I try to use it. I know it has nothing to do with syntax or human error: I've been copy/pasting the line of code used by it right out of an SFML tutorial. I'm using QT Creator. Could someone tell me why this may be the case,...
A function not being referenced sounds like a linker error. Have you linked to the glu library?
I've been trying to get a program's STDOUT redirecting to a file. So far, this code works well: ``` FILE *output = fopen("output","w"); if (dup2(fileno(output),1) == -1) { /* An error occured. */ exit(EXIT_FAILURE); } ``` The issue is, I'm trying to stick to ANSI C, and fileno isn't ANSI. When I compile with...
The ANSI C way to do it isfreopen(): ``` if (freopen("output", "w", stdin) == NULL) { /* error occured */ perror("freopen"); } ```
I'm back again with another string problem. I've no idea what's wrong with this. I'm trying to pass a string into a function but GCC expects an expression from me. Help is appreciated. These errors are always so hard to debug! ``` if (fmenu == 1) { printf("\nEnter the file name: \n"); scanf("%s", name); /* p...
name[]isn't a valid expression. You needfileoperations(name);
The following code confused me a bit: ``` char * strcpy(char * p, const char * q) { while (*p++=*q++); //return } ``` This is a stripped down implementation ofstrcpyfunction. From this code, we see that pointerpandqare incremented then dereferenced andqis assigned topuntil the\0char has been reached. I would li...
Because the++is after the variables, they aren't incremented untilafterthe expression is evaluated. That's why it's the post-increment operator; the pre-increment is prefixed (++p).*++pwould write to the second spot,*p++writes to the first.
``` void normalizeStepOne (double F[], double hsum, double V, double Fkjsum) { int i; F[i] = hsum/V; Fkjsum+=F[i]; return; ``` in main I try to call this function in this way: ``` normalizeStepOne (double F[0], double Csum, double VC, double Fkjsum); ``` and I got error: syntax error before 'double' ...
You must not include type declarations at the call site. Instead it should read something like this: ``` double F[ARRAY_LEN]; double Csum; double VC; double Fkjsum; /* initialize the variables */ normalizeStepOne(F, Csum, VC, Fkjsum); ```
I'm working on a CGI application written using C++ with the C MySQL adapter. I'm trying to run a query on two databases, so I want to connect to a MySQL server without choosing a default database. Is this possible? I'm usingmysql_real_connect().
mysql_real_connect()can take aNULLparameter for the database paramter, and this selects the default. Just ensure that the user has no default database set.
I have now admitted defeat that you cannot use/build a good audio pitch function without using the NDK. Now my question is does anyone know of any good pitch changing code either in a library or some source code for the NDK?
You could have a look at the MicDroid app that does auto-tune, sources available on GitHub:https://github.com/intervigilium/MicDroid some more info here: http://forum.xda-developers.com/showthread.php?t=721388
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this question I need to install curl on Windows to use it in a C application, I am using MinGW. Detailed instructions would be appreciat...
Go to the librarydownload pageand under "Win32 - Generic" download the libcurl option. This zip file includes headers and libraries in the .a format. Extract the files and use them in your project.
I was doing some C coding and after reading some C code I've noticed that there are code snippets like ``` char *foo = (char *)malloc(sizeof(char) * someDynamicAmount); ``` So I want to ask what's more C-ish way to allocate memory for char array? Usesizeof(char)and supposedly future-proof the code against any standa...
The more Cish way would be ``` char* foo = malloc(someDynamicAmount * sizeof *foo); ``` referencing the variable and not the type so that the type isn't needed. And without casting the result of malloc (which is C++ish).
If I have a code, fully written in C, using only libraries written also in C, and I have a compiler, like GCC, supporting many platforms, can I be sure that this code will run foranyarchitecture supported by compiler? For example, can I takeFlexorCPython, compile and use it, let say, atAVR? Edit: compile and run, of...
No, it's hard to say without seeing your code. For example, if you depend on thatlongis 4 bytes, it won't be right on 64bit machine.
I am trying ti make my own packer, and my packer works fine with executable compiled VC++ 6, but when I try to pack executable compiled with VC++ 8, the executable will crash. So I wanted to know if there is any change in the PE structure in the new versions of C++?
There has been no change to the PE File format, and as commenters above point out it is not related to your problem. It sounds like your packer is dependent on the VC++6 runtime libraries and as such when it unpacks something that is expecting VC++8 libraries bad things happen. The solution would be to make your pack...
Is there a library for creating zip files (thezip file formatnot gzip or any other compression format) on-the-fly (so I can start sending the file while it is compressing) for very large files (4 Gb and above). The compression ratio does not matter much (mostly media files). The library has to have a c-interface and...
libarchive supports any format you want, on the fly and even in-memory files.
Say I have a program where the value of an integerishould never be negative. Is there a way I can insert a globalassert(i>=0)such that wheneveribecomes negative an error is reported. This can be very useful while debugging. I don't want to put an assert everywhere the value ofiis manipulated.
No. Your debugger might have this sort of facility, though. For instance, GDB haswatchpoints.
Why this code does not work ? ``` #include <iostream> #include <cstdio> int main() { printf("%X", 1327644190303473294); } ``` I am getting o/p5f264e8e but expected o/p is126cbd5b5f264e8eas given by below php script ``` <?php echo dechex(1327644190303473294); ?> ```
format '%X' expects type 'unsigned int', but argument 2 has type 'long int' ``` #include <stdio.h> int main(void) { printf("%lX",1327644190303473294); return 0; } ``` outputs ``` 126CBD5B5F264E8E ```
How can I suppress this error in valgrind's output? ``` ==16727== 1 errors in context 2 of 18: ==16727== Conditional jump or move depends on uninitialised value(s) ``` What causes this error? Can I just ignore it?
It means that one of your control path is such that an variable/data does not get initialized when that control path gets executed. Unitialized variables usually result in Undefined Behavior So valgrind detects it and reports it. Have a look atthis, It shall help you understand the error. Also, add the flag--track-o...
I twotime_tvariables say start_sec and end_sec. Now I've to perform million operations of finding out whether a given randomtime_tfalls in this range. ``` if(given_sec >= start_sec && given_sec <= end_sec) { /* given_sec falls in the interval*/ } ``` or ``` start_sec -= -1; //keep it for million comparisons end...
No, they don't save anything and if they were, optimizer would help you anyway.