question
stringlengths
25
894
answer
stringlengths
4
863
Is there any way to convert C/C++ to Assembly not to HEX. Not like something that gcc or other compiler done(C/C++ --> ASM --> HEX). Only Convert It to ASM. Is there any way to do it by gcc,I mean stop compiler when translate C/C++ to ASM? with special thanks for your attention,and so sorry for my basic question
Use the-Soption of gcc, for example: ``` gcc -S hello.c ``` This will give you a filehello.swith assembly instructions.
I have such a funny problem I thought I'd share with you. I cornered it down to the most little program I could : ``` #include <unistd.h> #include <stdlib.h> #include <stdio.h> int cmd_left(char *name) { pid_t pid; int f_d; if ((pid = fork()) == -1) { perror(""); exit(1); } f_d = open...
open(2)takes at least two parameters. Since you are passing it only one argument, you are invoking Undefined Behavior. In this case,open()is just using some garbage as second argument.
I need to write files to the /etc folder on an embedded system with the root partition mounted as Read Only and have them persist. Can I do this in C or C++ assuming that the application is running as root?
You can always do the obvious: ``` system("mount -o remount,rw /etc"); ``` Most embedded systems should be complete enough that mount is available.
This is a stupid question, but I can't work it out and it's beginning to irritate me! I have the following (reg is a global): ``` #define CS 4 #define DS 5 unsigned char reg[6] = {0, 0, 0, 0, 0, 0x10}; ``` Now, I would expect reg[DS] to access element 5 of array reg (0x10). However, when debugging (VC2010), Visua...
Yes. ``` reg[DS] == 0x10 ``` Unless you have redefined the macroDSsomewhere else in the code.Macros are evaluated at pre-compilation. So if you definedDSas5then what goes to the compiler for compilation isreg[5]. Also, You cannot check a macro value at run-time because they do not exist at run-time, they are alread...
I am using Ubuntu 10.10 (64 bit) withgccand I wanted to use a 64 bit integer in my C++ program. On my system the outputs ofsizeof(long),sizeof(long long int)andsizeof(int64_t)are all 8 bytes (64 bits). Which qualifier (long,long long, orint64_t) would you recommend for using 64 bit integers?
int64_t-- This is because it is the most portable representation. The other two could be represented differently on other machines.
I'm a bit confused about the result of this code : ``` #include <stdio.h> #include <stdlib.h> int char_address(char *myChar) { printf("IN FUNCTION ADRESS = %p\n", &myChar); return 0; } int main(int argc, char **argv) { char *string; string = (char *)malloc(32 * sizeof(char)); ...
You are printing the pointer to the address of the actual pointers. Remove the&in yourprintfcall. ``` printf("IN MAIN ADDRESS = %p\n", string); ``` and ``` printf("IN FUNCTION ADRESS = %p\n", myChar); ```
I have some C code in a static library that I'm compiling into an iPhone app. I'd like to print some debug messages to the console; is there something like NSLog I should use? I'm guessing NSLog only works for the Objective-C parts of the program. EDIT: fprintf(stdout, fmt...) and fprintf(stderr, fmt...) don't work e...
you can always do the classic: ``` fprintf(stderr, "hi, this is a log line: %s", aStringVariable); ```
Recently, I had to implement a stream library,libstream, for one of my projects. Basically, it's achar-FIFO implemented as a linked list storing chunks of 4k bytes each (instead of one large chunk), with wrapper functions such asread(),write()andpeek(). Seemingly, there's nothing comparable available on the net, at l...
There is an I/O Stream library from A&T Research underCommon Public License 1.0, calledSFIO: A Safe/Fast I/O Librarywhich you might want to give a look. It is downloadablehere. It is difficult to answer Why there are no generic more commonly available stream libraries in open domain because pretty much everything in ...
If I want to transport a signed long (32 bit integer) across the network what do I do? If I send as a signed long then at other end I won't know (potentially) how remote machine represents signed numbers? So what do I do?
Just usentohlandhtonland cast or implicitly convert back and forth betweenuint32_tandint32_t.
I am converting some old OpenCV code using the C api to the new C++ API in OpenCV 2.3. I am wondering what the method is to replace thecvGetSubRectcall is? I have the following,cvGetSubRect(some_cv_mat_pointer, another_cv_mat_pointer, some_cv_rect); What is the equivalent to this in the C++ api?
You create an roi on the source image which gives you a new image - there is no actual pixel copying it all happens automatically ``` Mat image(.....) // original image Rect roi(10, 20, 100, 50); // shape of roi Mat image_roi = image(roi); /// really a window into image, copy it if you need to...
I am writing a windows kernel mode driver in which I will have to manipulate lots of strings. Everywhere it has been advised to use "Safe String" functions instead of normal C functions. However, many of the string functions haven't been implemented e.g. strchr, strstr. My question is whether there are any functions ...
You can use regular C runtime functions like strstr() in a driver. Avoid focusing on finding a safe version of that function, none exists. There's no scenario where strchr() or strstr() can corrupt memory unintentionally. They only read, they don't write. They can certainly cause a blue screen if the input strings...
I have a library; call itlibdog.so. I do not have the source tolibdog.so. I do not have the.ofiles which went intolibdog.so. ``` ldd libdog.so libdogfood.so.1 => not found ``` libdog depends on libdogfood. I have a static dogfood library,libdogfood.aandlibdogfood.la. I want to create a new library,libcompletedog.so...
Most UNIX systems (AIX is the exception) consider.solibraries a "final" product of the link, that can not be relinked into something else. If yourlibdogfood.ais a 32-bit library, you might be able to link it intolibdogfood.so.1, and thus satisfy the missing dependency: ``` gcc -shared -o libdogfood.so.1 \ -Wl,--who...
I have a Xilinx Virtex-II Pro FPGA board that is attached via RS232 to an iRobot Create. The iRobot takes a stream of byte integers as commands. I've found that printf will actually send over the serial port (Hypterminal is able to pick up whatever I print), and I figure that I can use printf to send my data to the ...
Usefwrite: ``` char buf[] = { 0x80, 0x80, 0x80 }; fwrite(buf, 1, sizeof(buf), stdout); ``` You can write to any file handle;stdoutis just an example to mirror yourprintf. On a Posix system, you can also use the platform-specificwritefunction that writes to a file descriptor.
The question is actually somewhat broader. Based on the last 15 years experience I currently assume that size of types is as follows: ``` byte = 8 bit short = 2 bytes int = 4 bytes long long = 8 bytes ``` Is there a modern OS where this assumption can be challenged?
Whether or not such "modern" systems exist, you shouldstatic_assertassert those assumptions in your code so that if your code is ever ported to a platform where the assumption is incorrect, the person doing the porting will be alerted to the problem immediately.
Is there any way to convert C/C++ to Assembly not to HEX. Not like something that gcc or other compiler done(C/C++ --> ASM --> HEX). Only Convert It to ASM. Is there any way to do it by gcc,I mean stop compiler when translate C/C++ to ASM? with special thanks for your attention,and so sorry for my basic question
Use the-Soption of gcc, for example: ``` gcc -S hello.c ``` This will give you a filehello.swith assembly instructions.
I have such a funny problem I thought I'd share with you. I cornered it down to the most little program I could : ``` #include <unistd.h> #include <stdlib.h> #include <stdio.h> int cmd_left(char *name) { pid_t pid; int f_d; if ((pid = fork()) == -1) { perror(""); exit(1); } f_d = open...
open(2)takes at least two parameters. Since you are passing it only one argument, you are invoking Undefined Behavior. In this case,open()is just using some garbage as second argument.
I need to write files to the /etc folder on an embedded system with the root partition mounted as Read Only and have them persist. Can I do this in C or C++ assuming that the application is running as root?
You can always do the obvious: ``` system("mount -o remount,rw /etc"); ``` Most embedded systems should be complete enough that mount is available.
I test the following code: ``` char ch,z=120; int x=5; double y=7.5; printf("\nsize of (z+100): %d" , sizeof(z+100)); ``` The output I get is : ``` size of (z+100): 4 ``` Can someone explain me this result? I thought that the output had to be ``` size of (z+100): 1 ``` Because tha range of char is 0...255,and 10...
The expressionz + 100is an addition with arithmetic operands of typecharandint(the numeric literal100is considered an integer in C). The rules of the language stipulate that the result of such an arithmetic addition is also of typeint, andsizeof(int) == 4(at least under your current compiler).
consider the code below, Am trying to make a Sparse_matrix that contains an array of pointer. In "struct Sparse_matrix", Is this a proper way to create a pointer array when size is unknown? What's the C programmer way to solve this? I'm new to C. Thanks for help ``` #include "sparse_matrix.h" struct Node{ short ...
Better write ``` SparseMatrix* matrix=malloc(cols*sizeof(Node*)+sizeof(SparseMatrix)); ``` because of alignments and gaps
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago. I would like to know what are the t...
Try next programs: Deleaker (Windows), Valgrind (Linux), CheckPointer
I made a wrapper for some basic things in libxml2, stuff like grabbing element content, stepping into children nodes etc. My super has just asked me to make sure I'm parsing the XML file serially and not loading the entire DOM into memory. I'm pretty sure the I'm doing it serially, but I couldn't find any documentat...
libxml2 can operate in either mode. It just depends how your code uses it. You can either parse the full file into a DOM, or use Sax callbacks to parse serially. What does your parsing code look like?
I have to call a Java method from JNI. This Java method returns int array (int[] simpleMethod()). How to call this from JNI to get the array as a return value? I know how to do this when method returns void/String/int/etc but couldn't find anything with arrays. I have some ideas how to work around this but maybe ther...
UseCallObjectMethod. For example: ``` jmethodID myMethod = (*env)->GetMethodID(myClass, "myMethod", "()[I"); jintArray retval = (jintArray) (*env)->CallObjectMethod(myObject, myMethod); ```
I need a method which can give me the number of miliseconds or seconds, elapsed since the system was started. I could parse/proc/uptime, but i can't afford to lose performance over this I/0 and parsing. I'm using Linux and C/C++. Maybe i can put some Qt/Boost, but is better to be something native.
Why cannot you afford reading/proc/uptime? It isnot a real fileso reading it should be quick (there is no real i/o involved, since the/proc/filesystem contains pseudo-files). Did you benchmark its reading? You might also callclock_gettimewithCLOCK_MONOTONIC NB. This is specific to Linux.
I have a C console app where I need to output the absolute path to a file given a (possibly) relative path. What is the best way to do this in C in a Windows environment?
I think you are looking for_fullpath().
Today,when I was reading the MSDN,I encountered the following codes: ``` void draw( int I, long L ); long sq( int s ); int main() { long y; int x; y = sq( x ); draw( x, y ); return(); } long sq( int s ) { return( s * s ); } void draw( int I, long L ) { /* Statements defining the draw function here */ return; } ```...
1 Yes, I believe it's a mistake.2 In a void returning method, omitting the return statement is equivalent to having a return as the last line of the method.
Hi I have a base 10 number for example 3198, and the hex representation is 0x0C7E How do I convert that number to hex and put that hex value in a byte array in the format of [00][0C][7E], assuming the biggest hex value i can have is 0xffffff.
Maybe this will work ? ``` uint32_t x = 0x0C7E; uint8_t bytes[3]; bytes[0] = (x >> 0) & 0xFF; bytes[1] = (x >> 8) & 0xFF; bytes[2] = (x >> 16) & 0xFF; /* Go back. */ x = (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0] << 0); ```
I have to shift development from NetBeans to Eclipse. My unit tests used NetBeans' "simpletest" and resulted in a tree structure with red/green indicators for each test and a summry. Can I useNetBEans simpletescripts in Eclipse and get a similar visual reult? If not, what's the simplest unit test sytem with such fu...
Probably CUTE is close to what you need:http://www.cute-test.com/
I readpointeras ornament ofCthat makesCa special language. However, i also used pointers in C++. I guess there are some limitations while using pointer in C++ than in C. As pointers are data types of C. If i am asked to write a program in pureC++, can i use pointers ?
Ofcourse you can use pointers in C++. There are some instances where pointers are the only way out. For eg: to use dynamic memory allocations. One special thing about pointers in C++ is C++ providesSmart pointerswhich can make your life easier. Prefer them over raw c like pointers. Bottomline is:Use what suits your ...
I want to print a float value which has 2 integer digits and 6 decimal digits after the comma. If I just useprintf("%f", myFloat)I'm getting a truncated value. I don't know if this always happens in C, or it's just because I'm using C for microcontrollers (CCS to be exact), but at the reference it tells that%fget jus...
You can do it like this: ``` printf("%.6f", myFloat); ``` 6 represents the number of digits after the decimal separator.
I want to call a C classes main function from within another class (which is written with objectiveC). I would like to pass some arguments to the main. I tried it like this, but the frist parameter gets ignored: ``` char *argv[] = { "--a", "--b", srcFile , destFile }; my_c_main(4, argv); ``` Am ...
the first entry in the argv array is the application name itself. so if you want to pass arguments, skip the first entry and start your args at the second entry in the array. you could probably just use an empty string as the first array element. ``` char *argv[] = { "", "--a", "--b", srcFile , ...
Could someone say me where I can found the source file where are the definitions of the standard libraries?For example, where is the filestring.cthat contains the definitions of the function prototyped instring.h? And above all, it exists?
its all in compilled state, some of maybe optimized by asm. You need find sources of your compiler to see definitions
Trying to output a pointer's address in decimal form using the%zuconversion specifier. Runs okay as expected except that GCC warns format ‘%zu’ expects type ‘size_t’, but argument 4 has type ‘long int *’ GCC options used are shown in the question. GCC still warns without any options set (other than-std=c99). clang h...
This appears to be specific to thezsize modifier in clang; youdoget a warning with%lu,%u,%hu, etc. (Even without any options) Generally speaking, it has been my experience that clang has more useful warning messages than GCC does. This is an exception to that experience. I'll file a bug.
Is there a difference between what a translation unit is in C++ and C? In other posts, I read that a header and source file makes a translation unit, but can a source file alone be called a translation unit in C++ where it contains all the definitions in one file?
A translation unit is not "a header and a source file". It could include a thousand header files (and a thousand source files too). A translation unit is simply what is commonly known as "a source file" or a ".cpp file" after being preprocessed. If the source file#includes other files the text of those files gets inc...
If destination and source are the same, doesmemmovestill "move" the data (or does it return directly)? What aboutrealloc; what if the new size is the same as the old size?
That's really going to be implementation-specific. It would be good practice to do so, sure, but it really dependswhichimplementation you mean. It's going to work either way, but presumably a suitably clever implementation would check for overlapping segments (and particularly for the case wheresource == dest) and d...
Simple question about this piece of code: ``` union MyUnion { int a; int b; }; union MyUnion x, y; x.a = 5; y.b = 2; y.a = 3; x.b = 1; int c = (x.a - y.b) + (y.a - x.b); ``` Can someone explain why the value ofcis 0 here ?
You can only access the last-written field of a union. This code violates that, and thus invokes undefined behavior. In essence, since both MyUnion.x and MyUnion.y share the same memory, you can probably replace the code with: ``` int x, y; x = 5; y = 2; y = 3; x = 1; int c = (x - y) + (y - x); ``` This simplifies ...
I need to append information into a given file from a shared lib I wrote in C in Solaris. What would be the safest way to open the file in a shared way for writing ? Being a shared lib I assume there's a risk two instances try to write to the file simultaneously. Thanks in advance
Two processes writing to the same file will, sooner or later, result in a garbled file. If you have access to both the library (which it seems you do) and the application, then you can protect all writes to the file withflockcalls.
I'm trying to compile the following minimal C code on ubuntu 10.10: ``` #include <sys/capability.h> void main(void) { cap_t cap; cap = cap_get_proc(); } ``` withgcc -lcap test.cwhich gives me the following error: ``` /tmp/ccCQFyXS.o: In function `main': test.c:(.text+0x9): undefined reference to `c...
Trygcc -Wl,--no-as-needed -lcap test.corgcc test.c -lcap.Hope this helps!
While debugging a multithreaded c program using GDB, how do I find out the execution position of individual threads in situations like " the execution of a program hanging midway". Thanks
Hit Contol-C to get the(gdb)prompt, and thenthread apply all where.
How to put the contents of a 32 bit CPU register in a byte array?
Basically you need to write inline assembly to read contents of some register. For example - to read ESP register into some int variable (Windows & Visual Studio) - you would do something like this: ``` int stackpointer = 0; __asm { mov stackpointer, esp } printf("stack pointer: %i\n", stackpointe...
I was wondering if there was possibly a way where one could scan a variable and then compare it all in the same line (same time). So far I tried this: ``` if(strcmp((scanf("create.%s",comp)),comp)==0) //Please do not mind any missed parentheses or something like that... ``` I know ^that doesn't work becaus...
It didn't work since scanf returns length, not char pointerThe fact that you write it in the same line have nothing to do with the execution time, you might as well separate it into two parts.If you really really want to do that (and I see no reason to), you may do the following:char *superScanfWithString(const char *...
I am new to C so I am not able to figure out how to do this. I have a while loop like this: ``` char my_line[MAXLINE]; while(gets(my_line) != NULL) { //process line } ``` Currently this while loop takes input from stdin. Can someone tell me how to use a char array instead i.e. read my data from a file into a cha...
Pretty easy. Just usefgets. This doesn't address dynamic memory allocation, this example uses a fixed sized char array. ``` FILE * pFile; char mystring [100]; pFile = fopen ("myfile.txt" , "r"); if (pFile == NULL) { perror ("Error opening file"); } else { fgets (mystring , 100 , ...
How can I split a string on a carriage return (\r\nor just\n) withsscanf?
Modifying Chris's answer slightly, to determine when the second part begins: ``` const char *str = ... // = source string while (str[0]) { char buffer[100]; int n; sscanf(str, " %99[^\r\n]%n", buffer, &n); // note space, to skip white space str += n; // advance to next \n or \r, or to end (nul), or to 100...
What is a reasonable minimum compression block-size for compression ratio when usingLZO-like algorithm? I expect that compressing 32B would be useless but compressing 512B might be good. Am I too far? Please, no "check yourself answers" :)
This paper, Table I, shows blocks sizes of 245 to 8196 give compression of 3.3 to 4.3 for ecommerce web data. So 256 is enough to be useful, but more helps. For the Explorer binaries, the ratios went from 1.5 to 2.1 over that range.
If I have a prototype that is declared as: ``` void foo(int (*fi)(void *, void *)) ``` And I call the function with something like this: ``` foo(int (*)(void*, void*)(bool_expr ? func1 : func2)); ``` Where func1 and func2 are defined as follows: ``` int func1(char *s1, char *s2); int func2(int *i1, int *i2); ``` ...
According to C specification, casting function pointers results in unspecified behavior, but many compilers (e.g. gcc) do what you expect them to do, because function pointer is just an address in memory. Just to be safe, I would re-declare func1 and func2 to take void*, and then cast these pointers to char* and int* ...
Assume we have a pointer(e.g., defined as int* p) to the beginning of an array and the size of the array(e.g., 1000). We want to reset all 1000 array values to 0. What is the simplest way?
The simplest way would be to use memset. ``` memset(p, 0, 1000 * sizeof(int)); ```
There are a lot of excellent answers how can one simulate object oriented concepts with C. To name a few: C double linked list with abstract data typeC as an object oriented languageCan you write object-oriented code in C? Whenis it appropriate to use such simulation and not to use languages that support object-orie...
I'll give you the one reason I know of because it has been the case for me: When you are developing software for a unique platform, and the only available compiler is a C compiler. This happens quite often in the world of embedded microcontrollers.
Task: To create database of workers. The program also should to ouput worker's info by name and count average salary of all workers. When I try to compile this code ``` #include <stdio.h> #include <stdlib.h> #include <string.h> struct worker { char name[10]; int salary; }; int main (void); struct worker...
Remove the;from the end of the following lineint main(void);and insert a{instead.
I am pulling (in the IT sense) hard drives from working machines and need to adjusttheir service configuration in the registry. In the Windows APIOpenSCManager, which is used to edit services in the registry, has a sparsely documentedlpDatabaseNameparameter. Can I use that, say if a Workingbut not runningWindows insta...
According to theSCM remote protocol specification, lpDatabaseName can only be NULL, "ServicesActive", or "ServicesFailed".
I'm new to programming in Objective-C, though I do have some experience in Python. I wrote this (what I thought would be simple) program: ``` #include <stdio.h> int main(){ printf("hello world\n"); return 0; } ``` But when I click run in Xcode it gives me this error: Command /Developer/usr/bin/clang failed ...
Like other commenters here, I can't see any direct problem with your code, so maybe you could get it to work if you start from a clean project template. In Xcode, choose New Project, type Command line tool You can select either straight C or Objective-C. The latter will give you an autorelease pool that you don't ne...
Here is a method from a class in some of Apple'sexample code. Why is this method defined as a static C method rather than an Objective C class method or a class method? In the context in which it is used I suppose it needs to be as performant as possible. Is this why? Is this the most performant way to declare a metho...
It's not a static method, but rather a function. And it's probably defined as a function because it operates on two data types (MKMapPointandMKMapRect) which are not objects (they are C structs) and thus can't have methods associated with them.
What happens if I compare two characters in this way: ``` if ('a' == 'b') doSomething(); ``` I'm really curious to know what the language (and the compiler) does when it finds a comparison like this. And, of course, if it is a correct way to do something, or if I have to use something likestrcmp(). EDITWait wai...
you can absolutely securely compare fundamental types by comparison operator==
I have a VS 10 console application,which has to take two char inputs and make some processing based on their values.I wrote the following code: ``` char c1,c2; printf("Ener c1:"); c1 = getChar(); //Some desicion is made based on c1 printf("Ener c2:"); c2 = getChar(); //Some desicion is made based on c2 ``` Run it wi...
When you get a single char from cin, the user technically presses the character: 'y' then enter, or '\n'. The \n is in the buffer, so you should flush the buffer after the first getchar to remove the \n. Try usingcin.ignore(); PS: I'd read this instead and rethink what you're doing: How do I flush the cin buffer?
I don't understand why sometimes I need to usefflush()and sometimes not. My program is segfaulting at the moment and I am debugging it with print statements. When a program segfaults, doesstdoutnot flush its buffer automatically?
I don't understand why sometimes I need to use fflush() and sometimes not. Sometimes thestdiobuffers are flushed sometimes they aren't. For example simply including a "\n" in the printed stuff will typically flush it (becausestdoutis by default line-buffered when attached to a terminal). When a program segfaults, ...
Does there exist a test framework for C that forces race conditions? Or for C++ and Java, for that matter.
The Valgrind toolHelgrinddetects (among other things) data races in C or C++ programs that use pthreads.
I need to dynamically allocate an array of typeintwith size 12MB. I did it as follows: ``` unsigned int *memory; memory = (int *) malloc( 3072 * sizeof(int)); ``` How would I iterate through the array without having to use3072? Is there a way to get the length of the array? Or should I just dofor (int i = 0; i < 307...
The is no portable or convenient way to find out how large the allocate chunk is. Aftermallocis done all that is visible is a pointer to an indeterminate amount of memory (*). You must do the bookkeeping yourself. (*) Actuallymallocand friendsdoknow how large the chunk is but there is no standard way for a client t...
I'm trying to find a way to get the number of bytes transferred from a network interface in the last 24 hours (or any other timeframe), excluding HTTP traffic. I've come across several threads likethis one, but this just gives me one flat number -- optimally, I'd like to get separate numbers for each protocol used. ...
Wiresharkcan do this and it is open source
I'm writing a C program for a micro-controller. At the moment I've already written the functions that reads from an analog-to-digital converter port on the board, and a function that can create a delay (just a loop that takes time). The incoming signal from a microphone is read into the board and each read value is s...
You either want to resample your waveform samples before you play them at the same ADC/dAC rate, change the sample rate, or look into time-pitch modification, which is a much more complicated DSP process.
I just started learning C. What I am trying to right now is that I have two strings in which each word is separated by white spaces and I have to return the number of matching words in both strings. So, is there any function in C where I can take each word and compare it to everyother word in another string, if not an...
Break up the first string in words, this you can do in any number of ways everything from looping through the character array inserting\0at each space to usingstrtok. For each word found, go through the other string usingstrstrwhich checks if a string is in there. just check return value fromstrstr, if!= NULLit found...
when i use non-ascii character for defining global array, for example: ``` const char table[] = {[L'č'] = 'c', ...}; ``` so C handles situation, where i change locale and then access array through those indexes? How this is compiled? Because'č'has different value in different encodings.
The compiler should convert the character in the source code from the source code encoding to the execution wide character set, which is chosen at compile time. The values will then be constants with the integer value of whatever that character is in that encoding. Calls tosetlocale()will not have any effect on the va...
Using the C API (not C++), how do you read in a simple video file frame by frame, and pass this frame (as a CvMat*) off for processing?
Something like the following: ``` CvCapture* cap = cvCreateFileCapture(MyVideoFile); if (!cap) { /* handle error */ } for(;;) { IplImage* frame = cvQueryFrame(cap); if (!frame) { /* EOF */ break; } CvMat tempMat; CvMat* myMat = cvGetMat( frame, &tempMat, 0, 0); // use myMat // Note: Don't ...
I wrote this C code below, when I loop, it returns a random number. How can I achieve the 5 different random values if myrand() is executed? ``` #include <stdio.h> #include <stdlib.h> int myrand() { int ue_imsi; int seed = time(NULL); srand(seed); ue_imsi = rand(); return ue_imsi; } int main() ...
Seeding the generator should be done once(for each sequence of random numbers you want to generate of course!): ``` #include <stdio.h> #include <stdlib.h> int main() { int seed = time(NULL); srand(seed); int value = 0; int i=0; for (i=0; i< 5; i++) { value =rand(); printf("val...
I'm having problem with mapping part of volume to memory. Volume is opened successfully, I can read from it, butCreateFileMapping()fails.GetLastError()returns 87, which hasfollowingmeaning: "The parameter is incorrect." I've created image of the volume and it is handled correctly. This is how I open file and create ma...
CreateFileMapping only supports mapping files. It's returning the "The parameter is incorrect" because the handle isn't for a file.
Can you launch a process on top of the topmost window? (csharp wpf) I have the following, but the current window before this one ( a wpf window using window class that has topmost=true ), remains on top of the process when the process is launched.. ``` if (System.IO.File.Exists(MY_CALC_PATH)) { System.Diagnostic...
You need to set the Calculator window as a child window of your TopMost window by callingSetParent. However, this approachhas drawbacks.
I need to extract hours, minutes and seconds from a string formatted as e.g: "00:53:12" to variables a, b and c. How would I go about this in C? Thanks in advance!
You can usestrptime ``` struct tm tm; if (strptime("00:53:12", "%H:%M:%S", &tm) != NULL) printf("hour: %d; minutes: %d; seconds: %d;\n", tm.tm_hour, tm.tm_min, tm.tm_sec); ```
``` #include <iostream> using namespace std; void main(){ char name[20]; gets(name); cout<<name<<endl; } ``` I can't found answer in google, function gets() is C or C++ language function ? Because in university I must use only C++ functions.
C functions are subset of c++ functions, but no, you probably don't wantgets()in c++ project. You may considergetline()oroperator>>for stream. Did they not tell you anything about it in the university?
I am trying to invoke the following macro in my .cpp file: ``` #define IAP_ROM_LOCATION 0x1FFF1FF1UL #define IAP_EXECUTE_CMD(a, b) ((void (*)())(IAP_ROM_LOCATION))(a, b) ``` However, when I call said function like so: ``` IAP_EXECUTE_CMD(0, 0); ``` I get an error saying too many arguments ...
For readability, define a signature for the function to be called: ``` typedef void signature_t(int, int); ``` Then you can cast your ROM location ``` #define IAP_EXECUTE_CMD(a, b) ((signature_t*)IAP_ROM_LOCATION) ((a),(b)) ``` and with a recent GCC (current version of GCC is4.6) I would make that an inline funct...
What is the best or recommended method for bit shifting a large amount of binary data in C? I have a 200K binary file and I want to left, then right shift the entire lot.
If your OS can support it use a memory mapped file. Then do a bit shift It'll be very very efficient. See this answer for more info:What are the advantages of memory-mapped files?
I have a simple program: ``` #include <stdio.h> #include <iostream> using namespace std; int main(int argc, char **argv) { double i=0.000006; printf("%lf\n",i); cout <<i<<endl; return 0; } ``` the output of which is : ``` pearl.236> ./a.out 0.000006 6e-06 pearl.237> ``` How can i achieve 0.000006 using thecout...
Stream formatting is achieved with the help ofmanipulators. The manipluators to specify standard and scientific notation arefixedandscientific. ``` cout << fixed <<i<<endl; ```
See in one situation uint64_t trackuid = 2906622092; Now I want to pass this value in one function where function argument isconst char* ``` func(const char *uid) { printf("uid is %s",uid); } ``` This should print ``` uid is 2906622092 ``` How can I do this?
``` // length of 2**64 - 1, +1 for nul. char buff[21]; // copy to buffer sprintf(buff, "%" PRIu64, trackuid); // call function func(buff); ``` This requires C99, however, my memory says the MS compiler doesn't havePRIu64. (PRIu64is ininttypes.h.) YMMV.
``` typedef struct node{ char one; char two; struct node *next; } nodea; ``` I'm thinking in terms of compiler padding, is there any way I can make the sizeof(nodea) smaller than 16?
You can use the#pragma packcompiler directivehttp://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx ``` #pragma pack(push) #pragma pack(1) typedef struct node { char one; char two; struct node* next; } nodea; #pragma pack(pop) ```
I want to know the difference betweenstr == NULLandstr[0] == '\0': ``` int convert_to_float(char *str, double *num) { if ((str == NULL) || (str[0] == '\0')) return(-1); *num = strtod(str, (char **)NULL); return(0); } ``` I'm using gcc on Linux.
str==NULLtells you whether the pointer is NULL. str[0]=='\0'tells you if the string is of zero-length. In that code, the test: ``` if ((str == NULL) || (str[0] == '\0')) ``` is used to catch the case where it is either NULL or has zero-length. Note that short-circuiting plays a key role here:The point of the te...
On executing the following code using 'Macro Definitions Set 1', I encounter the error "C2065: 'C1' : undeclared identifier". While using 'Macro Definitions Set 2', the code runs to give an output of 2. I am guessing it has something to do with preprocessor tokenization. Please Explain. ``` #include <iostream> // ...
The macro parameter is substituted unless it is before or after##, or after#. So in Set 1,D(A)becomesB(1)after substitution ofD(n), which is substituted toC1after rescan. In Set 2,D(A)becomesCA, whereAis not substituted as it is after##, andCAbecomes2after rescan.
I'm trying to use the function gethostbyname, but my code: ``` int handleTCP(char *hostname, char* portNo){ struct hostent *hp = gethostbyname(hostname); ... } ``` Keeps returning: ``` 21: warning: initialization makes pointer from integer without a cast ``` Does anyone know what is wrong with my syntax...
You forgot to#include <netdb.h>. Because you didn't include this file, you are running into the "default int" rule. Basically, in C, if a function has no prototype, it is assumed to be: int function_name();in other words "returns an int, takes unknown number of parameters". Properly declaring the function prototype ...
I am trying to convert65529from anunsigned intto a signedint. I tried doing a cast like this: ``` unsigned int x = 65529; int y = (int) x; ``` Butyis still returning 65529 when it should return -7. Why is that?
It seems like you are expectingintandunsigned intto be a 16-bit integer. That's apparently not the case. Most likely, it's a 32-bit integer - which is large enough to avoid the wrap-around that you're expecting. Note that there is no fully C-compliant way to do this because casting between signed/unsigned for values ...
I am exposed to the pointerint* i, of which I only know its memory is allocated but am not sure it has been initialized to some integer or not. If I try to deference it, what would happen? In other words, how should I check if it is initialized or not? If it is not, I'd like to assign an integer value to that address...
Define "initialized". There will always be some value, and there is no way you can tell whether that value is a garbage or an integer, because any 32 bits of garbage will yield some value. You can dereference it though, no problem.
I have a VS 10 console application,which has to take two char inputs and make some processing based on their values.I wrote the following code: ``` char c1,c2; printf("Ener c1:"); c1 = getChar(); //Some desicion is made based on c1 printf("Ener c2:"); c2 = getChar(); //Some desicion is made based on c2 ``` Run it wi...
When you get a single char from cin, the user technically presses the character: 'y' then enter, or '\n'. The \n is in the buffer, so you should flush the buffer after the first getchar to remove the \n. Try usingcin.ignore(); PS: I'd read this instead and rethink what you're doing: How do I flush the cin buffer?
I don't understand why sometimes I need to usefflush()and sometimes not. My program is segfaulting at the moment and I am debugging it with print statements. When a program segfaults, doesstdoutnot flush its buffer automatically?
I don't understand why sometimes I need to use fflush() and sometimes not. Sometimes thestdiobuffers are flushed sometimes they aren't. For example simply including a "\n" in the printed stuff will typically flush it (becausestdoutis by default line-buffered when attached to a terminal). When a program segfaults, ...
Does there exist a test framework for C that forces race conditions? Or for C++ and Java, for that matter.
The Valgrind toolHelgrinddetects (among other things) data races in C or C++ programs that use pthreads.
I need to dynamically allocate an array of typeintwith size 12MB. I did it as follows: ``` unsigned int *memory; memory = (int *) malloc( 3072 * sizeof(int)); ``` How would I iterate through the array without having to use3072? Is there a way to get the length of the array? Or should I just dofor (int i = 0; i < 307...
The is no portable or convenient way to find out how large the allocate chunk is. Aftermallocis done all that is visible is a pointer to an indeterminate amount of memory (*). You must do the bookkeeping yourself. (*) Actuallymallocand friendsdoknow how large the chunk is but there is no standard way for a client t...
I'm trying to find a way to get the number of bytes transferred from a network interface in the last 24 hours (or any other timeframe), excluding HTTP traffic. I've come across several threads likethis one, but this just gives me one flat number -- optimally, I'd like to get separate numbers for each protocol used. ...
Wiresharkcan do this and it is open source
I'm writing a C program for a micro-controller. At the moment I've already written the functions that reads from an analog-to-digital converter port on the board, and a function that can create a delay (just a loop that takes time). The incoming signal from a microphone is read into the board and each read value is s...
You either want to resample your waveform samples before you play them at the same ADC/dAC rate, change the sample rate, or look into time-pitch modification, which is a much more complicated DSP process.
I just started learning C. What I am trying to right now is that I have two strings in which each word is separated by white spaces and I have to return the number of matching words in both strings. So, is there any function in C where I can take each word and compare it to everyother word in another string, if not an...
Break up the first string in words, this you can do in any number of ways everything from looping through the character array inserting\0at each space to usingstrtok. For each word found, go through the other string usingstrstrwhich checks if a string is in there. just check return value fromstrstr, if!= NULLit found...
Is accessingconstvariables faster than non-constvariable? I'm wondering if it is worth usingconstmore as a step in optimizing a program.
If the value is acompile time constant(e.g.numbers,enum,constvalues,constexprsometimes in c++11 and so on), then yes theycan beaccessed faster compared to other variables. They can even be placed in the code segment. However, it's not true for anyconst: ``` const int x = 5; // can be faster const int c = foo(); // ...
I was looking for the old anwser found two solution. I have two process one is batch process and another is real time process. I want to give higher priority to the real-time process. One is ``` setpriority ``` I can set priority of the process b/w -20 to 19. Where -20 is highest and 19 is lowest. Question are wh...
You can also change the IO priority. In practice, I'm using the followingreallynicescript ``` #! /bin/sh exec ionice -n 6 nice -8 $* ``` and I'm doing e.g. ``` batch << END reallynice make END ``` Theman page ofsched_setschedulermentions SCHED_FIFO & SCHED_RR forreal-timeprocesses.
I have this program which worked find in my college lab, but when I run it at my home it gives different result ``` #include <stdio.h> int main(int argc, char* argv[]) { const int size=100; int n, sum=0; int* A = (int*)malloc( sizeof(int)*size ); for (n=size-1; n>0; n--) ...
You are not assigning value toA[0]. As a result of thisA[0]will have garbage value which is getting added tosum. Change ``` for (n=size-1; n>0; n--) ^^^ ``` to ``` for (n=size-1; n>=0; n--) ^^^^ ``` Also you need to free the dynamically allocated memory by doing: ``` free(A); ``` b...
I have the following code. How to bring the control back to cleanupCode() when I received SIGINT while sleeping? I don't want to use goto or jump. Calling cleanupCode inside handler is not an option. ``` sigHandler(int sig __atribute__((unused)) { loopFlag = 0; } void cleanupCode() { printf("Graceful exit \n...
You have to set the signal handler somewhere. ``` #include <signal.h> #include <unistd.h> volatile int loopFlag = 1; void sigHandler(int sig) { loopFlag = 0; } void cleanupCode() { printf("Graceful exit \n"); } int main () { signal(SIGINT, sigHandler); while(loopFlag) sleep(600); c...
i'm trying to compile my programm(it's a server that uses shared memory) and when i try to delete the shared memory(shmctl()) inside a signal handler for SIGINT i keep getting ``` undefined reference to `schmctl' ``` i searched around and saw that this usually requires something like ``` gcc -o server server.c -lrt...
-lrtmeans you are linking withlibrt.alibrary. To get rid of your error you should find the library where symbol shmctl is defined and then pass it togcc.
I have 2 sets of values. Each is in the range of -50 to + 50. Is there any way to represent two of these values in a single byte? (I am working in C, using Vstudio 2010). Thank you. Clarification: the values are arbitrary integers; that is, the values can be any integer between -50 and +50. (So, question has been...
No, not in 8 bits. -50 to +50 is 101 possibilities. With two of them, that's 10201 possibilities. 8 bits only has 256 combinations. You will need a minimum of 14 bits to store two values -50 to +50.
Is there a way to change the defaulta.outto something nicer, likefile.cautomatically becomesfile? I know one can do this withgcc file.c -o file, but... is there something easier?
No. Although if you havemakeavailable, you can just do: ``` make file ```
How to formatstruct timespecto string? This structure is returned e.g. byclock_gettime()on Linux gcc: ``` struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; ```
One way to format it is: ``` printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec); ```
In C, is it possible to have the forked() process alive indefinitely even after the parent exits? The idea of what I am trying to do is, Parent process forks a child, then exits, child keeps running in background until another process sends it a kill signal.
Yes, it is definitely possible to keep the child alive. The other responders are also correct; this is how a "daemon" or background process runs in a Linux environment. Some call this the "fork off and die" approach. Here's a link describing how to do it:http://wiki.linuxquestions.org/wiki/Fork_off_and_die Note that...
How do I generate the a.out file format with GCC on x86 architectures? WithNASMI can do this easily with the-fflag, for example: ``` nasm -f aout start.asm objdump -a start.o start.o: file format a.out-i386-linux start.o ``` On Linux, compiling .c files produces an ELF object file. How can I producea.outfiles ...
To generate the a.out format with gcc, your linker needs to be told to do so. You can do it by passing it flags from gcc thanks to the-Wlflag. Here is what you would do for the a.out format: ``` gcc -Wl,--oformat=a.out-i386-linux file.c -o file.out ``` You can also display all formats supported by typing: ``` objd...
I'm on Ubuntu 10.04 using GCC and I want to use the macro TEMP_FAILURE_RETRY as described here: http://www.gnu.org/s/hello/manual/libc/Interrupted-Primitives.html However, when I compile I got the following error: ``` undefined reference to `TEMP_FAILURE_RETRY' ``` I looked in unistd.h where the macro is defined a...
__USE_GNUis an internal macro, so you shouldn't define it yourself. But you may define_GNU_SOURCE, either in your code, or when compiling (using the-Doption). I think defining this one will help to makeTEMP_FAILURE_RETRYavailable.
I'm trying to get my program to restart itself, but nothing seems to work. I tried usingfork(), but after killingtheparentprocessthechildgets killed too. CODE ``` void sigup_handler(int signum) { int pid = fork(); if (pid == 0) { execve("prog2", NULL); } else kill(getpid(), SIGTERM);...
Why bother with theforkif you're just going tokilltheparent? Just do theexec. The new instance of the program will still be the same process but will effectively be rebooted.
``` #include <stdio.h> int main () { char loop='y'; while(loop != 'n') { printf("loop? "); scanf("%c", &loop); if(loop != 'y') { loop='n'; } } return 0; } ``` If I type in 'y' he restart the while-loop but ignores the scanf the second time and end the loop ...
Make sure thescanfdiscards the newline. Change it to: ``` scanf(" %c", &loop); ^ ```
I don't know if I'm just being a total fool, most likely I am, it's been a long day, but this isn't working as I want it to, and, well, I don't see why. It should be able to have 11 numbers entered, a new number on each line, add them to the array, then total them, yet it's just not working. It's not stopping to exit...
You have 10 elements in the array, numbered 0 - 9. You are overflowing the buffer, so all bets are off. This is undefined behaviour.
I am trying to learn C for my class. One thing I need to know is given an array, I have to take information from two characters and store it in one bytes. For eg. if string is "A1B3C5" then I have to store A = 001 in higher 3bits and then store 1 in lower 5bits. I have to function that can get two chars from array at ...
Assuming an ASCII character set, subtract '@' from the letter and shift left five bits, then subtract '0' from the character representing the digit and add it to the first part.
I'm trying to compile the NIF Test from Erlang (http://www.erlang.org/doc/man/erl_nif.html) on Mac OS X Lion. I can't get it to compile. Am I missing a compiler flag? Here's the error I get: ``` Computer:~ me $ gcc -fPIC -shared -o niftest.so niftest.c -I /usr/local/Cellar/erlang/R14B02/lib/erlang/usr/include/ Undefi...
for 64-bit Erlang, the following works for me: ``` gcc -undefined dynamic_lookup -dynamiclib niftest.c -o niftest.so \ -I /usr/local/Cellar/erlang/R14B02/lib/erlang/usr/include ```
Why is: ``` if(x!=y!=z) ``` handled as: ``` x=1 y=1 z=2 ``` ?? I just noticed it today.
x != yandx == yreturn booleans.You're comparingzto those booleans. Neither of them will work they way you want them to.
What is the best way to duplicate an integer array? I knowmemcpy()is one way to do it. Is there any function likestrdup()?
There isn't, andstrdupisn't in the standard, either. You can of course just write your own: ``` int * intdup(int const * src, size_t len) { int * p = malloc(len * sizeof(int)); memcpy(p, src, len * sizeof(int)); return p; } ```