question
stringlengths
25
894
answer
stringlengths
4
863
Suppose a program has memory leaks. 1) When a process dies (normally or segmentation fault), are those leaked memory freed? 2) What aboutother resourcesa process holds?
With most modern operating systems (linux, windows from around NT 3.5), yes.
How do you initialize special ASCII chars, for example EOT (0x04), ENQ(0x05)? ``` char CHAR1 = '\EOT'; char CHAR2 = '\ENQ'; ``` Is this correct?
You can put character code into the variable: ``` char CHAR1 = 4; char CHAR2 = 5; ``` You can also use escape sequences which you'll findhere.
I've asked a question regarding the theoretical aspect of this code a couple of hours ago. Now I understand everything, however, that code simply gives no output. Here's the link to the code onhttp://ideone.com/LWMC5 Code: ``` #include <stdio.h> #include <unistd.h> /* changed from "syscalls.h" it was not working */ ...
I don't understand what did you expect as output, to print something on the screen, you need to use something likeprintf.
I saw this code inthis .c file. ``` struct node { Item data; struct node *next; }; struct stack_type { struct node *top; }; ``` What are the benefits of creating two structs when one would do?
It may make the code clearer to distinguish between the whole stack and a single node.
We have ``` int main(int argc, char** argv, char** envc) ``` for the ordinary. but I want to know if there is any other argument main can have instead of these. And if there is any, what does it point to?
Well, heres the breakdown: argc-- C standardargv-- C standardenv-- Works on most UNIX and MS Win, but not standardapple-- Other information passed as forth argument by Mac OSX and Darwin
I'm an Arduinopadawanlearner. I want to pass a byte array to a function and get the size of the array. ``` byte data[] = { B00000000, B00000001, B00000011, B00000111 }; Serial.println(sizeof(data)); // ----------------------> displays 4 ``` When I pass it to a functionsizeofreturns 2. How can I get ...
When e.g. passing arrays as parameters, the compiler no longer has the size of the array. Instead the array gets passed as a pointer, and inwriteDatathesizeofoperation gets the size of the pointer and not the array (or whatever) it points to.
I am getting an error when I run the executable: ``` (a.out:6815): GooCanvas-CRITICAL **: goo_canvas_item_get_parent: assertion `GOO_IS_CANVAS_ITEM (item)' failed ``` I want to find out which function call is leading to this warning (since I am not calling the above function), I tried running with gdb but didn't sho...
Try to addG_DEBUG=fatal_criticalsto your environment. This way, your program will abort() when a critical error occurs, so your gdb can point you where the assertion fails. That, or adding a breakpoint to theg_criticalfunction.
How can I keep track of time with sub second precision. Can you guys provide me with some ideas and strategies. Also, the pros and cons of each, I am trying to implement this for a hard real-time system using a Linux kernel. The Linux clock() function is not accurate enough since its precision is by seconds.
You can useclock_gettime()to return astruct timespec: ``` struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; ``` The actual resolution is typically not anywhere near nanoseconds but should get you into the millisecond range or better.
Suppose a program has memory leaks. 1) When a process dies (normally or segmentation fault), are those leaked memory freed? 2) What aboutother resourcesa process holds?
With most modern operating systems (linux, windows from around NT 3.5), yes.
How do you initialize special ASCII chars, for example EOT (0x04), ENQ(0x05)? ``` char CHAR1 = '\EOT'; char CHAR2 = '\ENQ'; ``` Is this correct?
You can put character code into the variable: ``` char CHAR1 = 4; char CHAR2 = 5; ``` You can also use escape sequences which you'll findhere.
How can I keep track of time with sub second precision. Can you guys provide me with some ideas and strategies. Also, the pros and cons of each, I am trying to implement this for a hard real-time system using a Linux kernel. The Linux clock() function is not accurate enough since its precision is by seconds.
You can useclock_gettime()to return astruct timespec: ``` struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; ``` The actual resolution is typically not anywhere near nanoseconds but should get you into the millisecond range or better.
Suppose a program has memory leaks. 1) When a process dies (normally or segmentation fault), are those leaked memory freed? 2) What aboutother resourcesa process holds?
With most modern operating systems (linux, windows from around NT 3.5), yes.
How do you initialize special ASCII chars, for example EOT (0x04), ENQ(0x05)? ``` char CHAR1 = '\EOT'; char CHAR2 = '\ENQ'; ``` Is this correct?
You can put character code into the variable: ``` char CHAR1 = 4; char CHAR2 = 5; ``` You can also use escape sequences which you'll findhere.
Say I have a C structure like: ``` typedef struct { UINT8 nRow; UINT8 nCol; UINT16 nData; } tempStruct; ``` Is there a way to put all of those 3 members of the struct into a single 32-bit word, yet still be able to access them individually?
Something with the help ofunions? ``` typedef struct { UINT8 nRow; UINT8 nCol; UINT16 nData; } tempStruct; typedef union { tempStruct myStruct; UINT32 myWord; } stuff; ``` Or even better (with no "intermediate" struct): ``` #include <stdlib.h> #include <stdio.h> typedef union { struct { int ...
This question already has answers here:Closed11 years ago. Possible Duplicate:How to escape the % (percent) sign in C's printf I want to print the%symbol like this: "8%2F16" How can I print this string?
If you're trying to print usingprintf, you'll need to use%%: escape the%with another%: ``` printf("8%%2F16"); ``` %is an escape character with a special meaning in theprintfformat string, and so itself needs to be escaped if you're trying to print it.
I found such an example of scanf in C book (this time not K&R): scanf(" %[-' A-Za-z]s",&variable); Can anybody provide me with information what does it accept? I have not found any info about using 'a' or 'z' as conversion characters
From the standard (C11, §7.19.6.2/12): ]Matches a nonempty sequence of characters from a set of expected characters That means that your format expects a run of of the characters-, space,A, ...,Z,a, ...,z. The[conversion specifier has provisions for two special characters:%[^...invertsthe matching set, and a hyphen...
Does anyone know the buffering characteristics of Unix sockets when sending small chunks of data (a few bytes)? When I am using TCP sockets, I can disable the Nagle algorithm to prevent latency in data transit. But there's no equivalent functionality (that I know of) for Unix Domain sockets.
There is no nagle algorithm available on unix domain sockets. Unix sockets are normally implemented as a memory buffer in the operating system kernel. Once you've written/sent data on the socket, it is copied into that buffer, and becomes immediately available to the peer.
my program is crashing on the second run on this line: ``` char* temp_directive = (char *)malloc(7); ``` with this error: ``` Critical error detected c0000374 Windows has triggered a breakpoint in Maman14.exe. This may be due to a corruption of the heap, which indicates a bug in Maman14.exe or any of the DLL...
http://blogs.msdn.com/b/jiangyue/archive/2010/03/16/windows-heap-overrun-monitoring.aspx Sounds like you ran off the end of the array earlier in the code, and your memory management isn't picking it up until you try to malloc that memory space.
I've got a function that needs to be able to write to either stdout, or to a file, depending on what the user wants. It defaults to standard out though. To accomplish this, I'm doing the following (minus error checking etc): ``` FILE* out; if (writeToFile) { /*Code to open file*/; } else out = stdout; // ...res...
Yes, it's portable and it's fine, provided you don't also mess with the low-level implementation of*stdout(e.g. by callingclose(fileno(stdout))on Posix or usingdup).
I was trying to enumerate filetypes with bitmasking for fast and easy distinguishing on bitwise OR: ``` typedef enum { FileTypeDirectory = 1, FileTypePIX = 2, FileTypeJPG = 4, FileTypePNG = 8, FileTypeGIF = 16, FileTypeHTML = 32, FileTypeXML = 64, FileTypeTXT = 128, FileTypePDF = ...
Allenumconstantsin C are of typeintand not of the type of the enumeration itself. So the restriction is not in the storage size forenumvariables, but only in the number of bits for anint. I don't know much of objective-c (as this is tagged also) but it shouldn't deviate much from C.
I am using the Pelles C IDE and for certain projects have to tell the linker to include a certain library e.g.Ws2_32.lib. Currently I am developing a function I plant to reuse frequently throughout numerous projects, so I decided to make a header file for it. Is there a way to tell the linker to include a certain libr...
You have link the library, no other way. If compiler is gcc in linux, you can link the lirarylibtemp.solikegcc youfile.c -ltempAnd before running the executable add the path oflibtemp.sotoLD_LIBRARY_PATH In your IDE you can config the samething.
Saw this in an answer to another question: ``` char (*arrs)[rowSize] = malloc(bytesPerTable); ``` What is arrs? / why are there parentheses / what is the description of this declaration?
What is arrs ? what is the description of this declaration? It's a pointer to an array ofrowSizechars, vastly different from a pointer to achar. why are there parentheses Because without them it would be an array of pointers tochar.
I am currently using time from the ctime library. Is there any faster alternative? ``` time_t start_time, elapsed_time; for(int i = 0; i < n; i++) { start_time = time(NULL); /// optimized code if(condition_met()) { elapsed_time = time(NULL) - start_time; } else continue; } ``` time(NULL) ...
You seem to want to only measure elapsed time (and aren't concerned with the absolute time). One of the fastest approaches of measuring elapsed time (if you are on x86) is to read therdtsc counter. In mvsc++ this can be achieved by: ``` #include <intrin.h> unsigned __int64 rdtsc(void) { return __rdtsc(); } ```
Let say I have these: ``` typedef id Title; typedef struct{ Title title; int pages; }Book; ``` So far, the code is okay. But the problem is here: ``` typedef struct{ int shelfNumber; Book book; //How can I make this an array of Book? }Shelf; ``` Like what I have stated in the comment in the code, ...
``` typedef struct{ int shelfNumber; Book book[10]; // Fixed number of book: 10 }Shelf; ``` or ``` typedef struct{ int shelfNumber; Book *book; // Variable number of book }Shelf; ``` in the latter case you'll have to usemallocto allocate the array.
``` int a[10]; printf("%p ", &a); ``` will display the address of arraya. So, if I perform a redirection,*(&a), why is that I don't get value stored ata[0]. What is the rule in C language that states I should be getting address ofa. Yes, it does make sense, I get address ofa, since*and&will cancel each other leading...
``` int a[10]; printf("%p ", (void *) &a); // address of the array printf("%p ", (void *) a); // adress of the first element of the array printf("%p ", (void *) *(&a));// same as above ``` Here, the value ofais the same as&a[0]. And the value*&ais the same as the value ofawhen theaobject is an array ofint. Note t...
I've written a program to encrypt a given message by XOR. It works, but It doesn't end. Here is the code.(I have created 3 files): encrypt.h : ``` void encrypt(char *message); ``` message_hider.c: ``` #include <stdio.h> #include "encrypt.h" int main() { char msg[80]; while (fgets(msg, 80, stdin)){ encryp...
When I pressed Ctrl+D to stop it (in cmd) If that's thecmdfrom Windows you probably wantCtrl+Z.
When I do something like: ``` ./foo -uxw --bar something ``` Does the shell automatically parse these commands, or does each program have to do the parsing itself?
Each program parses its arguments. You'll probably want to look intogetoptfor that so the answer becomes:each program usually relies ongetoptto parse arguments.
Here's what I have: ``` #define STRING "string 1" string string2 = STRING + "string3"; ``` This is wrong. What is the solution? Is the problem thatstring2must be constant or what else, and why?
``` #define STRING "string 1" std::string string2 = STRING "string3"; ``` Concatenation of adjacent string litterals isn't a feature of the preprocessor, it is a feature of the C/C++
I started to look into glibc (GNU Libc) to understand how it's written. Inmalloc.c, I found a piece of code as follow: ``` #ifndef void #define void void #endif ``` Can someone please explain to me what this means? Isn'tvoidalways defined? Thanks
Looking atthe git history, it was like this: ``` /* Void_t* is the pointer type that malloc should say it returns */ #ifndef Void_t #if (__STD_C || defined(WIN32)) #define Void_t void #else #define Void_t char #endif #endif /*Void_t*/ ``` This was a workaround for historical [C], which did not havevoida...
any solutions? Is that even possible? ``` __global *float abc; // pointer to global memory stored in private memory ``` I want abc to be storedin local memoryinstead of private memory.
I think this is clarifiedhereList 5.2: ``` __global int global_data[128]; // 128 integers allocated on global memory __local float *lf; // pointer placed on the private memory, which points to a single-precision float located on the local memory __global char * __local lgc[8]; // 8 pointers stored on the local mem...
In gdb is there any way to get base data types of a structure ? suppose for following structure ``` typedef struct _trial { int i; double j; }trial_t; ``` in gdb ``` (gdb) whatis trial_t type = struct _trial (gdb) whatis _trial No symbol "_trial" in current context. (gdb) ``` any workarounds ? I ...
You probably wantptype ptype accepts the same arguments as whatis, but prints a detailed description of the type, instead of just the name of the type. ``` (gdb) ptype struct _trial ``` Or even: ``` (gdb) ptype trial_t ``` Contrary to whatis, ptype always unrolls any typedefs in its argument declaration
Generally when we do something like: ``` printf ( " %.*f ", 2, 3.3 ); ``` the precision width is being set to 2 and outputs3.30. But what if the width is given the negative value, e.g. ``` printf ( " %.*f ", -2, 3.3 ); ``` The output is3.300000which means the default width is being used. So what exactly is this-2d...
A negative precision is taken as if the precision were omitted. Source: C99 7.19.6.1 (HTML version athttp://port70.net/~nsz/c/c99/n1256.html#7.19.6.1) Or from POSIX (more readable):http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html
I am using RHEL 6 and trying to compile some code using SWIG. The SWIG file is named mySwig.i and looks like ``` %module base_module %{ #include "base.h" %} %include "base.h" ``` The mySwig.i file is kept in a folder named foo. The folder foo also has other .h, .c and .cxx files. The command I use i...
gcc -fpic -c foo/*will matchallfiles in the directory foo/. You only want to match C files most likely. You can do what withgcc -fpic -c foo/*.cif you really want. Personally I'd recommend using something like CMake or Autotools, or even just a Makefile to build your project rather than calling cc directly.
I have a C program. ``` int main () { if (getchar()!=EOF) puts("Got a character"); else puts("EOF"); } ``` What should I type into the stdin on the terminal to produce an EOF?
In Windows,Control+Zis the typical keyboard shortcut to mean "end of file", in Linux and Unix it's typicallyControl+D.
Any reccomendations of a libary which I can call from my Linux (C) app to send simple log messages to anyone who happens to be listening on the network, using Multicast UDP?
You don't need a library tosenda multicast packet. Sending a UDP message to a multicast socket is only marginally more complicated than sending one to a unicast address. In particular you'll need to usesetsockoptto set theIP_MULTICAST_TTLof your packets. The receiving side is slightly harder - you have to join a pa...
I want to initialize a char array using pointers, on the fly.That is user giving input do not know the size of array.User keeps on giving input until return is pressed.Condition here is to: Use pointers to initializeNot to pass size of array in advance.
Assuming a C question, how about (untested): ``` char *arr = malloc(10); size_t size = 10, index = 0; int ch; while ((ch = getc(stdin)) != EOF && ch != '\n' && ch != '\r') { if (index >= size) { size *= 2; arr = realloc(arr, size); /* XXX check it first. */ } arr[index++] = ch; } arr[index...
In a multi threaded application all threads block all signals and a single thread does the signal handling in a loop withsigwait. Now should we considerEINTRafter using system calls likereadandwritein other threads? ``` while (true) { num = read(fd, buf, size); if (num == -1 && errno == EINTR) continu...
EINTRis only returned if the system call was interrupted by a signal handler. If all signals are blocked in the signal mask of the thread that's making the system call, then this can't happen.
Do I just usefree()function to free the pointer, or some specific API?
Sincereadahead()populates the page cache, memory is handled by the kernel. You don't do anything.
I would like to name my file descriptors, fp, based on the index of the for loop. For instance, ``` char* fbad[4]= "fbad"; char* mod[3]="mod"; for (int i=0; i<10; i++) { sprintf(fbad_file, "%s%s%d", fbad,mod,i); FILE *fp = fopen(fbad_file, "w"); ////???????????? /*then do stuff here*/ fclose(fp); } ``` Ho...
For example, what I want to achieve is: for i=6, FILE *fp6. Use an array: ``` FILE *fp[10]; for(int i=0; i<10; i++) { fp[i] = fopen(...); } ``` Although, if you are closing the file pointer inside of the for-loop, what is the problem with reusingfp?
The only thing that passed to my mind was, MULT((3+2)(5*4))= 100 not 62? Can someone explain this? ``` #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #define ADD(x1, y1) x1 + y1 #define MULT(x1,y1) x1 * y1 int _tmain(int argc, _TCHAR* argv[]) { int a,b,c,d,e,f,g; a=2; b=3; c=4; d=5; ...
When the macros are expanded, this: ``` MULT(ADD(a,b),MULT(c,d)) ``` becomes: ``` a + b * c * d ``` which, replacing the variables with their values, is equivalent to: ``` 2 + 3 * 4 * 5 ``` and the value of this expression, evaluated according to the precedence rules, is 62, because multiplication has higher pre...
As in whether it falls within 2^3 - 2^4, 2^4 - 2^5, etc. The number returned would be the EXPONENT itself (minus an offset). How could this be done extremely quickly and efficiently as possible? This function will be called a lot in a program that is EXTREMELY dependent on speed. This is my current code but it is far...
What you're after is simply log2(n), as far as I can tell. It might be worth cheating and using some inline assembly if your target architecture(s) have instructions that can do this. See theWikipedia entryon "find first set" for lots of discussion and information about hardware support.
From what I understand ,#define blah 8is a macro . While ,#is the pre-processor directive . Can we say #include,#if,#ifdef,etc. are also macros , or are they called something else ? Or is it that macro is just a term used for #define statements only? Please correct me if I am wrong.
Lines that start with#arepreprocessing directives. They are directives that tell the preprocessor to do something. #include,#if,#ifdef,#ifndef,#else,#elif,#endif,#define,#undef,#line,#error, and#pragmaare all preprocessing directives. (A line containing only#is also a preprocessing directive, but it has no effect.)...
How do I initialize a new line char in C? For example, to initialize char A: ``` char letter = 'A'; ``` How to initialize new line? Like this maybe: ``` char newLine = '0x0A'? ```
Use an escape character like this: ``` char letter = '\n'; ```
I can't understand why this code does not print current time in every one second. What is the problem here ? ``` #include <stdio.h> #include <unistd.h> #include <time.h> int main(int argc, const char * argv[]) { while (1) { sleep(1); time_t tm; struct tm *t_struct; tm = time(NUL...
stdoutmay be line buffered, so you might need to eitherfflushit after outputting text, or print a newline to make changes visible.
This question already has answers here:Closed11 years ago. Possible Duplicate:Most effective way for float and double comparisonstrange output in comparison of float with float literal ``` int main() { float a = 0.8; if (a == 0.8) printf("x\n"); else printf("y\n"); return 0; } ``` Thoughais equal...
0.8 cannot be represented accurately in binary floating-point. Your codeif (a == 0.8)basically compares single-precision 0.8 with double-precision 0.8, which are not equal. To see this for yourself, try the following code: ``` int main() { double a = 0.8f; double b = 0.8; printf("%lX\n", *(long *)&a); ...
I am unsure about compiling C files into executables by using Cygwin under Windows 7. Can anyone please tell me how to do this? I've read some tutorials but still don't get it. I understand that I need a Makefile, but what shall I write into it to have an executable file after the compilation process?
For the beginning I would say it is enough to Install MinGW. If you have installed it you find in the bin folder a gcc.exe which is the Compiler. Either set the PATH Variable to the bin folder or go directly to this folder. In terminal use: ``` gcc your_C_file.c ``` The output will be an exe.
I am trying to write a GStreamer (0.10.34) plugin. I need manipulate an incoming image. I have my Sink caps set as "video/x-raw-yuv" so I know I'll be getting video. I am having trouble in understanding how to use the GstBuffer, more specifically: How do I get the bits per pixel?Given the bpp, how do I determine t...
After some source code hunting (jpegenc), I found the BaseLib plugins, most importantly GstVideo. This gives you the functiongst_video_format_parse_caps GstVideoFormat seems to be what you use to parse incoming video information.
Suppose I have a struct like that: ``` typedef struct { char *str; int len; } INS; ``` And an array of that struct. ``` INS *ins[N] = { &item, &item, ... } ``` When i try to access its elements, not as pointer, but as struct itself, all the fields are copied to a temporary local place? ``` for (int i = 0;...
Correct,inis acopyof*ins[i]. Never mind your memory consumption, but your code will most likelynot be correct: The objectindies at the end of the loop body, and any changes you make toinhave no lasting effect!
This is an example question for an exam I'm studying for - the question is what's wrong with the code. I'm thinking it may be the alarm(3), the delay causing it to jump into the while loop? Or possibly that SIGALRM shouldn't be used to wake up from a sleep, but I don't think that's a valid point here. Any feedback app...
The problem here (maybe just one of them) is that you suspend the process on anemptysignal set,sigset(3)does not populate it.sigsuspend(2)modifies process signal mask, soSIGALRMis blocked.
I have written a function which acceptsDIR *as argument and lists files inside that (withreaddirfunction) In addition, I just want to be able tostatfiles returned byreaddir. It is not clear whereDIR *is pointing to, so is there a way to get full path of directory fromDIR *or is there any other way that I canstatfiles...
You can usedirfd(), as many other answers, and then for each entry read withreaddir()call functionfstatat(): ``` int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags); ``` I think this relatively obscure function does just what you need. Alternatively you could callopenat()passing in the fd of t...
I am trying to figure out how to embed a simple structure inside another structure that is passed to a C dll from c#. How do you marshall the embedded structure? Stripped down to essentials. ``` //The C code typedef struct { int a; int b; } A; typedef struct { int c; A myStruct; } B; //The...
``` [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class B{ int c; public A a; } ``` You need IntPtr only if B is defined as: ``` typedef struct { int c; A* myStruct; } B; ```
In thislinkunsigned wchar_tistypedefed asWCHAR. But I cant find this kind of typedef in my SDKwinnt.hor mingwwinnt.h. wchar_tis signed or unsigned? I am using WINAPIs in C language.
The signedness ofwchar_tis unspecified. The standard only says (3.9.1/5): Typewchar_tshall have the same size, signedness, and alignment requirements (3.11) as one of the other integral types, called itsunderlying type. (By contrast, the typeschar16_tandchar32_tare expressly unsigned.)
I am new to C programming. I have two Linux machine. I want to send some data packets from one Linux machine to other Linux machine. Please suggest some references. I found so many things on net, and bit confused how to proceed. Please suggest.
Starting from scratch with both C and networking is a bit tough, but the best online sockets tutorial would beBeej's Guide to Network Programming. If you are serious about learning network programming though, get this book - you'll never regret:UNIX Network Programming, Volume 1by W. Richard Stevens.
Any reccomendations of a libary which I can call from my Linux (C) app to send simple log messages to anyone who happens to be listening on the network, using Multicast UDP?
You don't need a library tosenda multicast packet. Sending a UDP message to a multicast socket is only marginally more complicated than sending one to a unicast address. In particular you'll need to usesetsockoptto set theIP_MULTICAST_TTLof your packets. The receiving side is slightly harder - you have to join a pa...
I want to initialize a char array using pointers, on the fly.That is user giving input do not know the size of array.User keeps on giving input until return is pressed.Condition here is to: Use pointers to initializeNot to pass size of array in advance.
Assuming a C question, how about (untested): ``` char *arr = malloc(10); size_t size = 10, index = 0; int ch; while ((ch = getc(stdin)) != EOF && ch != '\n' && ch != '\r') { if (index >= size) { size *= 2; arr = realloc(arr, size); /* XXX check it first. */ } arr[index++] = ch; } arr[index...
In a multi threaded application all threads block all signals and a single thread does the signal handling in a loop withsigwait. Now should we considerEINTRafter using system calls likereadandwritein other threads? ``` while (true) { num = read(fd, buf, size); if (num == -1 && errno == EINTR) continu...
EINTRis only returned if the system call was interrupted by a signal handler. If all signals are blocked in the signal mask of the thread that's making the system call, then this can't happen.
Do I just usefree()function to free the pointer, or some specific API?
Sincereadahead()populates the page cache, memory is handled by the kernel. You don't do anything.
I would like to name my file descriptors, fp, based on the index of the for loop. For instance, ``` char* fbad[4]= "fbad"; char* mod[3]="mod"; for (int i=0; i<10; i++) { sprintf(fbad_file, "%s%s%d", fbad,mod,i); FILE *fp = fopen(fbad_file, "w"); ////???????????? /*then do stuff here*/ fclose(fp); } ``` Ho...
For example, what I want to achieve is: for i=6, FILE *fp6. Use an array: ``` FILE *fp[10]; for(int i=0; i<10; i++) { fp[i] = fopen(...); } ``` Although, if you are closing the file pointer inside of the for-loop, what is the problem with reusingfp?
The only thing that passed to my mind was, MULT((3+2)(5*4))= 100 not 62? Can someone explain this? ``` #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #define ADD(x1, y1) x1 + y1 #define MULT(x1,y1) x1 * y1 int _tmain(int argc, _TCHAR* argv[]) { int a,b,c,d,e,f,g; a=2; b=3; c=4; d=5; ...
When the macros are expanded, this: ``` MULT(ADD(a,b),MULT(c,d)) ``` becomes: ``` a + b * c * d ``` which, replacing the variables with their values, is equivalent to: ``` 2 + 3 * 4 * 5 ``` and the value of this expression, evaluated according to the precedence rules, is 62, because multiplication has higher pre...
As in whether it falls within 2^3 - 2^4, 2^4 - 2^5, etc. The number returned would be the EXPONENT itself (minus an offset). How could this be done extremely quickly and efficiently as possible? This function will be called a lot in a program that is EXTREMELY dependent on speed. This is my current code but it is far...
What you're after is simply log2(n), as far as I can tell. It might be worth cheating and using some inline assembly if your target architecture(s) have instructions that can do this. See theWikipedia entryon "find first set" for lots of discussion and information about hardware support.
From what I understand ,#define blah 8is a macro . While ,#is the pre-processor directive . Can we say #include,#if,#ifdef,etc. are also macros , or are they called something else ? Or is it that macro is just a term used for #define statements only? Please correct me if I am wrong.
Lines that start with#arepreprocessing directives. They are directives that tell the preprocessor to do something. #include,#if,#ifdef,#ifndef,#else,#elif,#endif,#define,#undef,#line,#error, and#pragmaare all preprocessing directives. (A line containing only#is also a preprocessing directive, but it has no effect.)...
How do I initialize a new line char in C? For example, to initialize char A: ``` char letter = 'A'; ``` How to initialize new line? Like this maybe: ``` char newLine = '0x0A'? ```
Use an escape character like this: ``` char letter = '\n'; ```
I can't understand why this code does not print current time in every one second. What is the problem here ? ``` #include <stdio.h> #include <unistd.h> #include <time.h> int main(int argc, const char * argv[]) { while (1) { sleep(1); time_t tm; struct tm *t_struct; tm = time(NUL...
stdoutmay be line buffered, so you might need to eitherfflushit after outputting text, or print a newline to make changes visible.
This question already has answers here:Closed11 years ago. Possible Duplicate:Most effective way for float and double comparisonstrange output in comparison of float with float literal ``` int main() { float a = 0.8; if (a == 0.8) printf("x\n"); else printf("y\n"); return 0; } ``` Thoughais equal...
0.8 cannot be represented accurately in binary floating-point. Your codeif (a == 0.8)basically compares single-precision 0.8 with double-precision 0.8, which are not equal. To see this for yourself, try the following code: ``` int main() { double a = 0.8f; double b = 0.8; printf("%lX\n", *(long *)&a); ...
Given this struct: ``` typedef struct _WLAN_AVAILABLE_NETWORK_LIST { WLAN_AVAILABLE_NETWORK Network[1]; } *PWLAN_AVAILABLE_NETWORK_LIST; ``` What does the declarationWLAN_AVAILABLE_NETWORK Network[1]mean?
It looks likely thatNetworkis intended to serve as aflexible array member. By over-allocating the struct bysizeof(Network) * (n - 1)bytes, the library and client code can access past the end of the struct as if the array member wasnelements long. Library code: ``` PWLAN_AVAILABLE_NETWORK_LIST list = malloc(sizeof(_...
I spent a long time finding out the actual origin type of data sent out from the serial port. Since I want byte by byte data, I cannot see he correct answer if I just use achar[]buffer to read!
You just write bytes into the serial port. When reading them back on the receiving end just read into anunsigned charbuffer. To correctly interpret the data, you need to know how it was structured when it was sent. This is usually specified by some kind of protocol so that you can detect the end of transmission (an ex...
Is there a way to dynamically load compiled c-code in a linux-kernel-module at run-time? I am looking for something likedlopenfromlibdl.
Yes. Move the code into another modules and then create a dependency to that other module in yours.
This question already has answers here:Closed11 years ago. Possible Duplicate:32-bit to 16-bit Floating Point Conversion How do I convert between 32-bit floats and 16-bit half-precision floats in C?
Since C typically doesn't have a 16-bit floating point type built-in, I would expect you would either have to Use some super-specific platform "magic", like a dedicated CPU instruction if available. This will of course not be a C solution, it will likely be inline assembly in the C source. Not portable.Manually extr...
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 want to ask that how can I see if...
``` if( ( a>(b*0.98) ) && ( a<(b*1.02) ) ) { //we have %2 error tolerance here. Bee careful! Dont pass the tol. level. //do your work yourself, if you cant find, then ask us. Dont forget //to google } if( abs(a-b)<(b*0.02) ) { } if ( abs((a-b)(a+b))<0.07 ) { } if(check(a,b)) { } if( pre...
This is some example code from my app: ``` int page_id; string page_name; enum COLUMNS { PAGE_ID, PAGE_NAME }; if (mysql_query(conn, "SELECT page_id, page_name FROM pages")) { exit_mysql_error(conn); } MYSQL_RES *res = mysql_use_result(conn); while (MYSQL_ROW row = mysql_fetch_row(res)) { page_id ...
``` page_id = atoi(row[0]); page_name = row[1]; // not really sure ```
``` static struct{ unsigned a:5; unsigned b:5; unsigned c:5; unsigned d:5; }v={1,2,3,4}; printf("%d %d %d %d %d",v.a,v.b,v.c,v.d,sizeof(v)); ``` Outputis : 1 2 3 4 4 Can someone explain why is the size of this struct 4 ? Shouldn't it be 16 ?
You're using 20 bits which fit nicely in 4 bytes. No need for 16 bytes. EDIT I think it is actuallyrequiredthat they be packed like that: 6.7.2.1An implementation may allocate any addressable storage unit large enough to hold a bit- field. If enough space remains, a bit-field that immediately follows another bit-fiel...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
The canonical library to render SVG islibrsvg. You may want to check that out. try thislink... its very use full to you..
``` struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif) ``` Here is declaration of function, that converts connection attributes tostruct sock. As I googled, first argument should be&init_net. But what should be last argument?
Thedifargument is the device interface.
I have this code: ``` int main() { char ch[15]; cout<<strlen(ch)<<endl; //7 cout<<sizeof(ch)<<endl; //15 return 0; } ``` Why doesstrlen(ch)give different result even if it is emptychararray?
Your code hasundefined behaviorbecause you are reading the uninitialized values of your array withstrlen. If you want a determinate result fromstrlenyou must initialize (or assign to) your array. E.g. ``` char ch[15] = "Hello, world!"; ``` or ``` char ch[15] = {}; ``` sizeofwill give the size of its operand, as t...
``` char * str = "Hello"; *(str+1) = '3'; cout<<str; ``` What I was trying to do there was to change the second character into '3', turning it into H3llo Why doesn't it work?
This is undefined behaviour. You cannot change literal. To have a pointer to literal, it should be: ``` const char* str = "Hello"; //^^^^^ ``` Then, to be able to change string, this should be, for example ``` char str[] = "Hello"; ``` The other option is to allocate dynamically the memory (usingmallocandfree)
There must be something I'm misunderstanding, why does this not return 10? ``` int main() { float i = 0; func(i); printf("%f", i); return 0; } void func(float i) { int j; for (j = 0; j < 5; j++) { i += 2; } } ```
Primitive types (like floats) are "passed by value", func() is really modifying a copy of i.
Is it possible (and if so, how?) to redirectstdout(and, optionally, stderr) temporarily to a file, and later recover the originalstdout? In a POSIX environment, I usedupanddup2to store and replaceSTDOUT_FILENO.freopenisn't a good solution, sincestdoutcannot be recovered that way. Is it possible to do this with the W...
Take a look at theSetStdHandleWin32 API. Also,_dup and _dup2are available. EDIT See the following StackOverflow posts. Redirect stdout to an edit control (Win32) practical examples use dup or dup2
For whatever reason the following code prints (null): ``` #include <stdio.h> #include <stdlib.h> int main(void) { char *foo; scanf("%ms", &foo); printf("%s", foo); free(foo); } ``` I'm trying to allocate memory for a string dynamically but as I said earlier my program simply outputs (null). I worke...
I am not seeing%min section 7.21.6.2 of theDraft C11 standard(the section onfscanf). I suggest that you avoid it and callmalloc()as you would in C99.
I am attempting to convert some text from a text field to a(n) u32 value. An example would be that I enter in string format (to represent a 32-bit integer), "0x30323436", and the output in string format would be "0246". I am trying to do this in C#, but I can use C as well. Thank you.
This should do what you want: ``` string ParseWeirdFormat(string input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.Length; i += 2) { string hex = input.Substring(i, 2); int value = Convert.ToInt32(hex, 16); char c = (char)value; sb.Append(c); } ...
Does autotools comes out of box for all the major unix systems? I am looking for something that can compile the code without installing any additional software and platform independent(UNIX flavors and Architecture).
If you use autotools correctly, the end result is a scriptconfigureso that ``` configure make make install ``` works -- and yes, the very point of autotools is that this should work just about everywhere.
I'm trying to implement a spinlock in my code but the spinlock that I implemented based on Wikipedia results in extremely slow performance. ``` int lockValue = 0; void lock() { __asm__("loop: \n\t" "movl $1, %eax \n\t" "xchg %eax, lockValue \n\t" "test %eax, %eax \n\t" ...
How about something like this (I understand this is the KeAcquireSpinLock implementation). My at&t assembly is weak unfortunately. ``` spin_lock: rep; nop test lockValue, 1 jnz spin_lock lock bts lockValue jc spin_lock ```
``` int x = 0xff; printf("%#x",x); ``` Output:0xff ``` printf("%x",x); ``` Ouput:ff Why is there a difference in output? What does#specifically do?
The standard says: 7.21.6 - 2The result is converted to an ‘‘alternative form’’. ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. It does other interesting stuff (especially for floats) but I have rarely seen it used - I honestly admit I had to look it up to remember.
I create a child with CreateProcess and wait for it to finish. This process is very likely to crash. Is it possible to prevent the "%PROGRAMNAME% stopped working" dialog for the child?
Is the child your own code (ie, is source available which you can modify)? If it is, you can catch unhandled exceptions and exit - use theSetUnhandledExceptionFilterfunction. If it isn't, then you could attach to the process as a debugger (CreateFile with DEBUG_ONLY_THIS_PROCESS) and run a simple event loop (seeMSDN ...
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.Closed10 years ago. I have a program where I callCreate...
If you have a control over child process make it return distinct error code on success, whereas if 0 then it means program crashed.
I want to make a stop-watch in C (live Stop-watch) without using inbuilt function "Timer" in Turbo C. My code is as follows: ``` #include<stdio.h> #include<conio.h> #include<dos.h> int main() { int hh,mm,ss; hh=mm=ss=0; gotoxy(10,10); printf("\nSTOP - WATCH: "); gotoxy(20,18); printf("HH : MM : SS"); _set...
Usekbhit()andgetch()from<conio.h>to get keyboard input.
I'm dealing with win32 api subclass. My issue is I don't know my subclass procedure is running on a dialog or a "normal window". Can anyone tell me how can I determine current window is a dialog or a normal window?
Check the name of the window class. There is no formal documented way of determining this other than that.
Is there a way to dynamically load compiled c-code in a linux-kernel-module at run-time? I am looking for something likedlopenfromlibdl.
Yes. Move the code into another modules and then create a dependency to that other module in yours.
This question already has answers here:Closed11 years ago. Possible Duplicate:32-bit to 16-bit Floating Point Conversion How do I convert between 32-bit floats and 16-bit half-precision floats in C?
Since C typically doesn't have a 16-bit floating point type built-in, I would expect you would either have to Use some super-specific platform "magic", like a dedicated CPU instruction if available. This will of course not be a C solution, it will likely be inline assembly in the C source. Not portable.Manually extr...
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 want to ask that how can I see if...
``` if( ( a>(b*0.98) ) && ( a<(b*1.02) ) ) { //we have %2 error tolerance here. Bee careful! Dont pass the tol. level. //do your work yourself, if you cant find, then ask us. Dont forget //to google } if( abs(a-b)<(b*0.02) ) { } if ( abs((a-b)(a+b))<0.07 ) { } if(check(a,b)) { } if( pre...
This is some example code from my app: ``` int page_id; string page_name; enum COLUMNS { PAGE_ID, PAGE_NAME }; if (mysql_query(conn, "SELECT page_id, page_name FROM pages")) { exit_mysql_error(conn); } MYSQL_RES *res = mysql_use_result(conn); while (MYSQL_ROW row = mysql_fetch_row(res)) { page_id ...
``` page_id = atoi(row[0]); page_name = row[1]; // not really sure ```
``` static struct{ unsigned a:5; unsigned b:5; unsigned c:5; unsigned d:5; }v={1,2,3,4}; printf("%d %d %d %d %d",v.a,v.b,v.c,v.d,sizeof(v)); ``` Outputis : 1 2 3 4 4 Can someone explain why is the size of this struct 4 ? Shouldn't it be 16 ?
You're using 20 bits which fit nicely in 4 bytes. No need for 16 bytes. EDIT I think it is actuallyrequiredthat they be packed like that: 6.7.2.1An implementation may allocate any addressable storage unit large enough to hold a bit- field. If enough space remains, a bit-field that immediately follows another bit-fiel...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
The canonical library to render SVG islibrsvg. You may want to check that out. try thislink... its very use full to you..
``` struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif) ``` Here is declaration of function, that converts connection attributes tostruct sock. As I googled, first argument should be&init_net. But what should be last argument?
Thedifargument is the device interface.
I have this code: ``` int main() { char ch[15]; cout<<strlen(ch)<<endl; //7 cout<<sizeof(ch)<<endl; //15 return 0; } ``` Why doesstrlen(ch)give different result even if it is emptychararray?
Your code hasundefined behaviorbecause you are reading the uninitialized values of your array withstrlen. If you want a determinate result fromstrlenyou must initialize (or assign to) your array. E.g. ``` char ch[15] = "Hello, world!"; ``` or ``` char ch[15] = {}; ``` sizeofwill give the size of its operand, as t...
``` char * str = "Hello"; *(str+1) = '3'; cout<<str; ``` What I was trying to do there was to change the second character into '3', turning it into H3llo Why doesn't it work?
This is undefined behaviour. You cannot change literal. To have a pointer to literal, it should be: ``` const char* str = "Hello"; //^^^^^ ``` Then, to be able to change string, this should be, for example ``` char str[] = "Hello"; ``` The other option is to allocate dynamically the memory (usingmallocandfree)
There must be something I'm misunderstanding, why does this not return 10? ``` int main() { float i = 0; func(i); printf("%f", i); return 0; } void func(float i) { int j; for (j = 0; j < 5; j++) { i += 2; } } ```
Primitive types (like floats) are "passed by value", func() is really modifying a copy of i.
Is it possible (and if so, how?) to redirectstdout(and, optionally, stderr) temporarily to a file, and later recover the originalstdout? In a POSIX environment, I usedupanddup2to store and replaceSTDOUT_FILENO.freopenisn't a good solution, sincestdoutcannot be recovered that way. Is it possible to do this with the W...
Take a look at theSetStdHandleWin32 API. Also,_dup and _dup2are available. EDIT See the following StackOverflow posts. Redirect stdout to an edit control (Win32) practical examples use dup or dup2
For whatever reason the following code prints (null): ``` #include <stdio.h> #include <stdlib.h> int main(void) { char *foo; scanf("%ms", &foo); printf("%s", foo); free(foo); } ``` I'm trying to allocate memory for a string dynamically but as I said earlier my program simply outputs (null). I worke...
I am not seeing%min section 7.21.6.2 of theDraft C11 standard(the section onfscanf). I suggest that you avoid it and callmalloc()as you would in C99.
I am attempting to convert some text from a text field to a(n) u32 value. An example would be that I enter in string format (to represent a 32-bit integer), "0x30323436", and the output in string format would be "0246". I am trying to do this in C#, but I can use C as well. Thank you.
This should do what you want: ``` string ParseWeirdFormat(string input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.Length; i += 2) { string hex = input.Substring(i, 2); int value = Convert.ToInt32(hex, 16); char c = (char)value; sb.Append(c); } ...
This question already has answers here:Closed11 years ago. Possible Duplicate:Sizeof string literal On my windows7 mingw environment, I tried this: ``` char str[] = "hello"; ``` The value ofsizeof(str)is 6, not 4 or 8. How can this happen?
sizeof(str)returns the number of bytes in the string which includes the terminating null character. I.e.,"hello\0"makes for 6 bytes in yourarray. If instead you had had ``` char* str = "hello"; ``` thensizeof(str)would have returned the number of bytes in thepointerstr(4 for 32-bit systems). You may find this SO q...