question
stringlengths
25
894
answer
stringlengths
4
863
I am having a problem in my program that uses pipes. What I am doing is using pipes along with fork/exec to send data to another process What I have is something like this: ``` //pipes are created up here if(fork() == 0) //child process { ... execlp(...); } else { ... fprintf(stderr, "Writing to pipe now\n...
You need to close the read end of the pipe in the process doing the writing. The OS will keep data written to the pipe in the pipe's buffer untilallprocesses that have the read end of the pipe open actually read what's there.
I get a ton of errors in cstdio when I add#include <cstdio>to the C program. ``` c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\cstdio(17) : error C2143: syntax error : missing '{' before ':' c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\cstdio(17) : error C2059: syntax error : ':' ``...
You want#include <stdio.h>.cstdiois the C++ wrapper for the C header. Edit:MSVC only supports the elements in C99 that form a subset of C++. This sitehas a C implementation ofsnprintf()licensed under the GPL.
I am trying to work out if I need to call close on a fstream object if the intial open failed. i.e. ``` std::fstream strm; strm.open( "filename" ); if( ! strm.fail() ) { // Do something strm.close(); // [1] } strm.close(); // [2] ``` Where shouldclosebe called here - should it always be called [2] or o...
The stream will be automatically closed by the fstream's destructor - there is no need to close it explicitly, unless your program logic demands it, for example if you are going to re-open it. However, closing a stream that didn't open won't cause any problems.
How can I free aconst char*? I allocated new memory usingmalloc, and when I'm trying to free it I always receive the error "incompatible pointer type" The code that causes this is something like: ``` char* name="Arnold"; const char* str=(const char*)malloc(strlen(name)+1); free(str); // error here ```
Several people have posted the right answer, but they keep deleting it for some reason. You need to cast it to a non-const pointer;freetakes avoid*, not aconst void*: ``` free((char*)str); ```
Given that I have a pointer to a function (provided bydlsym()for example) and a linked list of typed arguments, how can I construct a C function call with those arguments? Example: ``` struct param { enum type { INT32, INT64, STRING, BOOL } type; union { int i32; long long i64; char *str; bool b; } value; s...
You'll probably need to uselibffi.
can somebody explain me about redefinition in C: is it possible to do something like this ``` typedef struct NumberContainer* ptrNumberContainer; ``` and after that ``` typedef struct NumberContainer* ptrCall; ``` may it cause some problems during linkage? thanks in advance
No, that's perfectly OK - you have two synonyms for the same underlying type - this is quite common. However, the practice of hiding the fact that something is a pointer by using a typedef is generally viewed as bad practice in C.
i have time of the day in seconds and i have to find the utc time since 1970, is there any api which can directly convert this time to utc time, i m using ansi c , and working on windows platform platform independent api will be preferred thanx in advance.
You can fill in atm structwith the time of day you have (you'd have to convert it into seconds/minutes/hours) and the date. Then convert it withmktime()intime.h.
Plus, The program runs on a arm device running Linux, I can print out stack info and register values in the sig-seg handler I assign. The problem is I can't add -g option to the source file, since the bug may won't reproduce due to performance downgrade.
Compiling with the-goption togccdoesnotcause a "performance downgrade". All it does is cause debugging symbols to be included; it doesnotaffect the optimisation or code generation. If you install yourSIGSEGVhandler using thesa_sigactionmember of thesigactionstruct passed tosigaction(), then thesi_addrmember of thesi...
The question shown below is an interview question: Q) You are given/have a datatype, say X in C. The requirement is to get the size of the datatype, without declaring a variable or a pointer variable of that type, And of course, without using sizeof operator ! I am not sure if this question has already been asked ...
define sizeof_type( type ) (size_t)((type*)1000 + 1 )-(size_t)((type*)1000) The original is from this discussion.http://www.linuxquestions.org/questions/programming-9/how-to-know-the-size-of-the-variable-without-using-sizeof-469920/
gcc 4.4.3 c89 I have the following source code. And getting a stack dump on the printf. ``` char **devices; devices = malloc(10 * sizeof(char*)); strcpy(devices[0], "smxxxx1"); printf("[ %s ]\n", devices[0]); /* Stack dump trying to print */ ``` I am thinking that this should create an char array like this. ``` ...
You have allocated memory for an array of pointers. You need to allocate the memory for each element to store the string e.g. ``` #define NUM_ELEMENTS 10 char **devices; devices = malloc(NUM_ELEMENTS * sizeof(char*)); for ( int i = 0; i < NUM_ELEMENTS; i++) { devices[i] = malloc( length_of string + 1 ); } ```
gcc 4.4.3 c89 I have the following code as a sample of what I am trying to do. I don't know the actual size of the array, until I enter the function. However, I don't think I can set the array size after I have declared it. I need it global as some other functions will need to access the device names. Many thanks fo...
You'll need to allocate the memory dynamically using malloc: ``` char **device_names; void fill_devices(size_t num_devices) { device_names = malloc(num_devices * sizeof(char*)); } ``` And then usefree(device_names);to free the memory when you no longer need it.
I am having a problem in my program that uses pipes. What I am doing is using pipes along with fork/exec to send data to another process What I have is something like this: ``` //pipes are created up here if(fork() == 0) //child process { ... execlp(...); } else { ... fprintf(stderr, "Writing to pipe now\n...
You need to close the read end of the pipe in the process doing the writing. The OS will keep data written to the pipe in the pipe's buffer untilallprocesses that have the read end of the pipe open actually read what's there.
I get a ton of errors in cstdio when I add#include <cstdio>to the C program. ``` c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\cstdio(17) : error C2143: syntax error : missing '{' before ':' c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\cstdio(17) : error C2059: syntax error : ':' ``...
You want#include <stdio.h>.cstdiois the C++ wrapper for the C header. Edit:MSVC only supports the elements in C99 that form a subset of C++. This sitehas a C implementation ofsnprintf()licensed under the GPL.
How can I hide curl_easy_perform output (in a shell)?This is in regards to a C application.
Use CURLOPT_NOBODY in curl_easy_setopt(). Example: ``` ... CURL *curl; CURLcode statusCode; curl = curl_easy_init(); if(curl){ curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com/"); //CURLOPT_NOBODY does the trick curl_easy_setopt(curl, CURLOPT_NOBODY, 1); curl_easy_perform(curl); ... ``` ...
I'm trying to check whether or not the second argument in my program is a substring of the first argument. The problem is that it only work if the substring starts with the same letter of the string. EDIT: It must be done in C, not C++. ``` int main(int argc, char **argv){ if (argc != 3) { printf ("Usag...
I am assuming homework, so: Take a look at whatsubStartis initialized with.
I have a doubt. Assume R and S are 2 relations with attributes A and B respectively . If I have a query ``` Select * From R, S Where R.A = S.B ``` Does this work like a double For Loop in say c or c++ ``` For( i=0; i<n; i++) For( j=0; j<n; j++) if (i == j) //DO some work ```
First of all: there is no knowing how mysql will internally optimize the query (without knowing the internals of mysql). In pure relational databases words, this is what you are doing: SELECT * FROM R, S-> perform cross join, that generates all (r,s) tuples. WHERE R.A = S.B-> now select those tuples that have this ...
I want to know aboutconstinternals in C and C++ . How does the compiler impose"constantness"?
In generalconstis 100% compiler. When you declare something const,the compilerplaces restrictions on what it will let you write. It won't let you assign to const scalar, assign through a const reference or or pointer, or invoke a non-const function of const object. There is no guarantee that the compiler will arrange...
A response to a comment I made here made me stop and think: "I don't really know what the state of C99 support is." Wikipedia gives details for a few compilers, but I'm not familiar enough with C99 to know all the bits and pieces of the standard, so I'm looking for a gestalt overview answer to the question: What is ...
MSVC: Intentionally not implemented unless it overlaps with C++GCC: Most of the useful parts are in (and have been for awhile). Some missing features.clang: Claims full C99 support
I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my program. Here's my code so far: ``` #include "python.h" static P...
You need to bind that function to some module, seehttp://docs.python.org/extending/embedding.html#extending-embedded-python Edit: Basicly your code should work. Whats not working?
What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negative number to an unsigned int: ``` 1 /* 2 * ===================================================================================== 3 * 4 * ...
%iis the format specifier for asignedinteger; you need to use%uto print an unsigned integer.
i.e. - ``` int function(char* txt) { sprintf(txt, "select * from %s;", table); //How do I set last char in buffer to NULL here? } ``` so if the text in table some how was 500 chars long and txt in the main was only defined as 100.... thanks.
You need to add a parameter to the function that gives the size of the bufferusesnprintf()instead ofsprintf()check the return value ofsnprintf()to see how large the buffer needed to be to hold all the formatted data; if this is larger than or equal to the size of the buffer, you should handle that as you see fit (the...
I'm trying to debug a small program I've written in C. I open up the file in emacs, M-x gdb, give the program filename (a.out). When i switch to the source file in the emacs pane, and try to place a breakpoint in the main function, I get the message "No default breakpoint address now." and the breakpoint doesn't place...
to debug in gdb you have to use the -g option, this will let gdb work with your output file by adding debugging symbols to your binary ``` gcc -g file.cpp ```
Are there examples of recursion using only heap area?
In C, function call-based recursion always uses the stack, almost by definition. If you are willing to convert your recursion to iteration, then it is possible to use only heap space, but that isn't really recursion. You would do so by implementing a stack in the heap. Certain problems can usetail recursion, which ...
I'm developing a general purpose library which uses Win32'sHeapAlloc MSDN doesn't mention alignment guarantees for Win32's HeapAlloc, but I really need to know what alignment it uses, so I can avoid excessive padding. On my machine (vista, x86), all allocations are aligned at 8 bytes. Is this true for other platform...
Surprisingly, Google turns upevidencethatHeapAllocis not always SSE-compliant: HeapAlloc() has all the objects always 8-byte aligned, no matter what their size is (but not 16-byte-aligned, for SSE). The post is from mid 2008, suggesting that recent Windows XP suffers from this bug. See alsohttp://support.microsoft....
All the Python-provided types have a check method (i.e.,PyList_Check) that allows you to check if an arbitraryPyObject*is actually a specific type. How can I implement this for my own types? I haven't found anything good online for this, though it seems like a pretty normal thing to want to do. Also, maybe I'm just...
That's becausethey're macrosthat use deep magic. Save yourself a bit of headache and usePyObject_IsInstance()instead.
I am confused. I can not use this on a float? Must it be a integer? I try to define that as a point but I guess I can not convert float to float * ``` //global definition float g_posX = 0.0f; &g_posX -= 3.03f; ```
You probably simply want to do this: ``` float g_posX = 0.0f; g_posX -= 3.03f; ``` What your code tries to do is take the address ofg_posXand subtract3.03ffrom theaddress. That does not work, for two reasons: The address is not an lvalue: it cannot be assigned to. Assigning to an address would be meaningless. What ...
There are two problems here: What if content is encoded:gzip...Do I also need to change the header part to make the HTTP packet valid(checksums if any?) UPDATE Can someone with actual experience elaborate the steps involved? I'm usingwinpcapand bpftcp and src port 80to filter the traffic,so my job lies in this cal...
WinPcap doesn't allow you to change a packet that was already sent. If the packet was sent, WinPcap won't prevent it from reaching its destination. If you want to send another response - in addition to the response that was sent - I'm not sure what you're trying to achieve.
Please explain the following piece of code.. ``` printf("%c\n",0+'0'); --> returns 0 printf("%c\n",1+'0'); --> returns 1 printf("%c\n",0+'1'); --> returns 1 printf("%c\n",1+'1'); --> returns 2 ``` Thanx.
Look at theASCII table. '0' has code 48. So '0' + 1 yields 49, which is '1'. So every character is in fact an integer. You add another integer to it and then, because you specify "%c" in printf, you force it to consider it a character. He goes check his ASCII table and, after some deliberation he decides to print the ...
i want to prepare a byte buffer as a upd packet i want to fill each value in reverse order how can i do so in ansi c i have to do this on windows system,
Assuming you are doing this so it will work on any receiving system: Usehtonl()on each byte in your buffer when sending andntohl()on each received byte.
How can I get the file size of a file in C when the file size is greater than 4gb? ftell returns a 4 byte signed long, limiting it to two bytes. stat has a variable of type off_t which is also 4 bytes (not sure of sign), so at most it can tell me the size of a 4gb file. What if the file is larger than 4 gb?
On Linux with glibc, ftell returns anoff_t; depending on the flagsoff_tmay be 32 bit or may be 64 bit. On Linux, you can get the appropriate flags to have a 64 bitoff_tby doinggetconf LFS_CFLAGS(LFS stands for large-file-support).
I've got an array of characters which contains a string: ``` char buf[MAXBUFLEN]; buf[0] = 'f'; buf[1] = 'o'; buf[2] = 'o'; buf[3] = '\0'; ``` I'm looking to pass this string as an argument to thegtk_text_buffer_insertfunction in order to insert it into aGtkTextBuffer. What I can't figure out is how to convert it to...
gcharis just atypedefforcharand the conversion from arrays to const pointers is implicit, so you can just pass it: ``` someFunctionExpectingConstGcharPointer(buf); ``` Note that you can also directly initialize arrays with string literals: ``` char buf[MAXBUFLEN] = "foo"; ```
``` /^[^\s]+\s([^\s]+)\s/ ``` In PHP,I can use regex to get the substr by$1, how should I do it in C? It's better if can do it without regex,though. UPDATE Put simply, how do I getwerwerurout ofswerwer werwerur y(the second)?
I recommend to use strchr() - it is very fast to find characters in strings ``` #include <string.h> .. char str[] = "swerwer werwerur y"; char *p1 = NULL,*p2 = NULL; p1 = strchr(str,' '); p1++; p2 = strchr(p1,' '); if(p2) *p2 = 0; printf("found: %s\n", p1); ``` if you have multiple delimiters, you can use strtok_r...
Pay attentions that there is a space in it. Which function can I use?
You can use ``` if (!strncmp("GET ", str, 4) { ... } else if (!strncmp("POST ", str, 5)) { ... } else { ... } ```
I have the following code to copy files ``` sprintf(command, "copy /Y %s %s", sourceFile, targetFile); system(command); ``` It works except for the dos window showing up which is very annoying. I am trying to use CreateProcess() (with an #ifdef for WINNT), but not sure how to setup the command line for the same. An...
Windows provides theCopyFilefamily of APIs for this.
I need to count the similar elements in an array. For example, if i have an array, array[0,0,0,1,2,3,3].The number of 0's are 3 , no. of 1's are 1 , no. of 2's are 1 , no. of 3's are 2 in this array . I am sorry if this message has been posted before. Help is appreciated. Thanks in advance. Regards, THM P.S : Langu...
You could use a std::map to store and adapt your results based on the array-entry, while iterating over the array. I hope this hint helps for your assignment.
I have heard of WINE but I don't like it because it's slow on the computers I have tested and almost always crashes. It also has some unpleasant looking gui.I am wondering if there is a "win32" library in c/c++ for linux that producesnative linux codeso that if I have my source code for windows, I can just recompile a...
You're looking forWinelib.
I am looking for tool that can convert .Glade (or xml) file to C source.I have tried g2c (Glade To C Translator) but i am looking for windows binary. Any one does know any good tool for window. Thanks,PP.
You don't need a tool. Just write a script in your favorite scripting language to format your glade file as a C string literal: For example, let's call itglade_file.c: ``` const gchar *my_glade_file = "<interface>" "<object class=\"GtkDialog\">" "<et-cetera />" "</object>" "</int...
From a basic test program. . . ``` package main /* #include <stdio.h> static void test() { printf("hello world"); } */ import "C" func main() { C.test(); } ``` I do "cgo hello_cgo.go" and get: ``` _cgo_.o _cgo_defun.c _cgo_gotypes.go hello_cgo.cgo1.go hello_cgo.cgo2.c ``` How do I go about comp...
Try using the go makefiles. Create a makefile like ``` # Makefile CGOFILES=test.go TARG=test include $(GOROOT)/src/Make.$(GOARCH) include $(GOROOT)/src/Make.pkg ``` Running make will then produce the file_obj/test.a, which you'll have to link with6lor similar.
Or in my particular case a windows region (HRGN)? Updated: The problems is the following: I've a collection of objects, each of these objects can hold a HRGN. These region once acquired is released when the object is destroyed. Since some of those objects are stored in a std::vector I've to define an assignement ope...
You cannot make a duplicate of HRGN handle, but you could get a copy usingCombineRgnfunction.
I'm currently using dirent.h and ftw.h for directory traversal at my CGI website 100% programmed in C. I am not sure if they are process safe; would various users interfere with each other while on my site ? Which functions would you recommend for this purpose ?
It is safe for multiple processes to, for example, useftw()to walk the same directory tree at the same time. Howeverit is not necessarily safe for one process to be walking the directory tree while another process isupdatingthe same directory tree structure (ie adding, removing or renaming directories). If you have ...
``` argv[1]=argv[1]/filenames[j] argv[1]=folder1 and filenames[2]=cool ``` I want to store folder1/cool in argv[1] how to proceed? I am not familiar with C.
you should be using"folder1"and"cool"if these are litteralsyou should usestrcat(str1, str2)if you want to mimmicstr1 = str1 + str2of e.g. Javayou might prefersprintf(str1, "%s/%s","folder","cool")none of the above is correct unlessstr1is an array of char that has enough room to store the result (welcome to C)
Is there anyway to do "insmod" and "rmmod" from C/C++ code? Other than running system(...), is there a Kernel API that will allow me to do this?
Have you looked at themodule-init-toolssource?
``` /^[^\s]+\s([^\s]+)\s/ ``` In PHP,I can use regex to get the substr by$1, how should I do it in C? It's better if can do it without regex,though. UPDATE Put simply, how do I getwerwerurout ofswerwer werwerur y(the second)?
I recommend to use strchr() - it is very fast to find characters in strings ``` #include <string.h> .. char str[] = "swerwer werwerur y"; char *p1 = NULL,*p2 = NULL; p1 = strchr(str,' '); p1++; p2 = strchr(p1,' '); if(p2) *p2 = 0; printf("found: %s\n", p1); ``` if you have multiple delimiters, you can use strtok_r...
Pay attentions that there is a space in it. Which function can I use?
You can use ``` if (!strncmp("GET ", str, 4) { ... } else if (!strncmp("POST ", str, 5)) { ... } else { ... } ```
I have the following code to copy files ``` sprintf(command, "copy /Y %s %s", sourceFile, targetFile); system(command); ``` It works except for the dos window showing up which is very annoying. I am trying to use CreateProcess() (with an #ifdef for WINNT), but not sure how to setup the command line for the same. An...
Windows provides theCopyFilefamily of APIs for this.
I need to count the similar elements in an array. For example, if i have an array, array[0,0,0,1,2,3,3].The number of 0's are 3 , no. of 1's are 1 , no. of 2's are 1 , no. of 3's are 2 in this array . I am sorry if this message has been posted before. Help is appreciated. Thanks in advance. Regards, THM P.S : Langu...
You could use a std::map to store and adapt your results based on the array-entry, while iterating over the array. I hope this hint helps for your assignment.
I have heard of WINE but I don't like it because it's slow on the computers I have tested and almost always crashes. It also has some unpleasant looking gui.I am wondering if there is a "win32" library in c/c++ for linux that producesnative linux codeso that if I have my source code for windows, I can just recompile a...
You're looking forWinelib.
I am looking for tool that can convert .Glade (or xml) file to C source.I have tried g2c (Glade To C Translator) but i am looking for windows binary. Any one does know any good tool for window. Thanks,PP.
You don't need a tool. Just write a script in your favorite scripting language to format your glade file as a C string literal: For example, let's call itglade_file.c: ``` const gchar *my_glade_file = "<interface>" "<object class=\"GtkDialog\">" "<et-cetera />" "</object>" "</int...
From a basic test program. . . ``` package main /* #include <stdio.h> static void test() { printf("hello world"); } */ import "C" func main() { C.test(); } ``` I do "cgo hello_cgo.go" and get: ``` _cgo_.o _cgo_defun.c _cgo_gotypes.go hello_cgo.cgo1.go hello_cgo.cgo2.c ``` How do I go about comp...
Try using the go makefiles. Create a makefile like ``` # Makefile CGOFILES=test.go TARG=test include $(GOROOT)/src/Make.$(GOARCH) include $(GOROOT)/src/Make.pkg ``` Running make will then produce the file_obj/test.a, which you'll have to link with6lor similar.
Or in my particular case a windows region (HRGN)? Updated: The problems is the following: I've a collection of objects, each of these objects can hold a HRGN. These region once acquired is released when the object is destroyed. Since some of those objects are stored in a std::vector I've to define an assignement ope...
You cannot make a duplicate of HRGN handle, but you could get a copy usingCombineRgnfunction.
I'm currently using dirent.h and ftw.h for directory traversal at my CGI website 100% programmed in C. I am not sure if they are process safe; would various users interfere with each other while on my site ? Which functions would you recommend for this purpose ?
It is safe for multiple processes to, for example, useftw()to walk the same directory tree at the same time. Howeverit is not necessarily safe for one process to be walking the directory tree while another process isupdatingthe same directory tree structure (ie adding, removing or renaming directories). If you have ...
On a quite ancient UNIX (Apple A/UX 3.0.1 for 680x0 processors) using the built-in c compiler (cc), this issue arrises. Here is the code I'm trying to compile: ``` #include <stdlib.h> #include <stdio.h> int main() int argc; char **argv; { if (argc > 1) puts(argv[1]); return (EXIT_SUCCESS...
Forold skoolK&R C I think it needs to be: ``` #include <stdlib.h> #include <stdio.h> int main(argc, argv) int argc; char **argv; { if (argc > 1) puts(argv[1]); return (EXIT_SUCCESS); } ```
Is that possible? I've seen no method that would generate a plain old C vector or array. I have just NSNumber objects in my array which I need as C vector or array.
An alternative to mouviciel's answer is to use NSArray'sgetObjects:range:method. ``` id cArray[10]; NSArray *nsArray = [NSArray arrayWithObjects:@"1", @"2" ... @"10", nil]; [nsArray getObjects:cArray range:NSMakeRange(0, 10)]; ``` Or, if you don't know how many objects are in the array at compile-time: ``` NSUInte...
I'd like to write a program which reads user input only from tty, instead of redirected stdin pipes, likepasswdandsshdo. Is there any approach? Many thanks
You should try opening/dev/ttydirectly. That's the only way I know for sure that you can bypass thestdinredirection. /dev/ttyis usually a symbolic link to youractualtty device, which may be/dev/consoleor/dev/tty24or pretty much anything you want, depending on the weird and wonderful way your system may be set up. The...
How to lock file in Windows so that this file can be opened/read/wrote only by one process? I found out that file can be locked withCreateFileby giving0todwShareModeflag. It works but only the returned handle can be used to work with file. But I want to be able to lock the file to other processes and at the same time...
Why do you need to create same file twice in the same process? You could use one handle in all I/O functions of your process without reopening file. If you need to pass the handle to another process you could useDuplicateHandlefunction.
Under what circumstances will the "False" part of the following code be executed? ``` x = 20; y = -30; if (x > y) { // True part } else { // False part } ``` NB: Language is C, compiler is gcc (although some other compilers may also do the same thing).
Ifyis of unsigned integer type it will be initialized to some very large value (because of how negative integer values are represented) and the comparison expression will evaluate tofalse.
``` char *substring(char *text, int position, int length) { int i, j=0; char *temp ; for(i=position-1; i<position+length-1; i++) { temp[j++] = text[i]; } temp[j] = '\0'; return temp; } ``` Hi What is the error in the following code.. I am trying to run this on Fedora Machine.. And its givi...
tempis uninitialized.
Currently, we are defining ourselves an extended log mechanism to print out the class name and the source line number of the log. ``` #define NCLog(s, ...) NSLog(@"<%@:%d> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], \ __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__]) ``` For exampl...
``` print(__FUNCTION__) // Swift NSLog(@"%@", NSStringFromSelector(_cmd)); // Objective-C ``` Swift 3 and above ``` print(#function) ```
We have a set of C macros, here, for using the preprocessor to do bitfield operations, and we run into warnings when attempting to use these macros in visual studio. The problem can be demonstrated very easily: ``` #define BITFIELD_WIDTHMASK(Width) \ ((Width) >= 32 ? ~0x0ul : (1ul << (Width)) - 1) unsigned long...
What about: ``` #define BITFIELD_WIDTHMASK(Width) \ ((Width) >= 32 ? ~0x0ul : (1ul << (Width % 32)) - 1) ``` ?
There's this instance variable in my objective-c class: ``` ALuint source; ``` I need to have an mutable array of OpenAL Sources, so in this case probably I need a mutable C-array. But how would I create one? There are many questions regarding that: 1) How to create an mutable C-array? 2) How to add something to ...
I’d keep things simple.ALuintis some kind ofint, so that you can easily wrap it usingNSNumberand stick it in an ordinaryNSMutableArray: ``` ALuint bar = …; NSMutableArray *foo = [NSMutableArray array]; [foo addObject:[NSNumber numberWithInt:bar]]; // and later ALuint source = [[foo lastObject] intValue]; ```
From a long time ago I have a memory which has stuck with me that says comparisons against zero are faster than any other value (ahem Z80). In some C code I'm writing I want to skip values which have all their bits set. Currently the type of these values ischarbut may change. I have two different alternatives to perf...
If it is faster, the compiler will substitute it for you. In general, you can't write C better than the compiler can optimize it. And it is architecture specific anyway. In short,don't worry about itunless that sub-micro-nano-second is ultra important
Can somebody please explain what does this warning mean:undefined reference to 'WinMain@16'?
Googlehaslotsofreferencestothat particular error. You need to provide aWinMainfunction, depending on what type of project you are building (console or Windows app).
Is there an easy way to check if a pipe is closed before writing to it in C? I have a child and parent process, and the parent has a pipe to write to the child. However, if the child closes the pipe and the parent tries to read - I get a broken pipe error. So how can I check to make sure I can write to the pipe, so I...
A simple way to check would be to do a 0 byte write(2) to the pipe and check the return. If you're catching SIGPIPE or checking for EPIPE, you get the error. But that's just the same as if you go ahead and do your real write, checking for the error return. So, just do the write and handle an error either in a signa...
I'd like to know if a fd has data available for reading. I have triedioctlwithFIONREADbut that results in a "Operation not supported error". Any ideas?
You can useselect(), with a zero (notNULL) timeout.
I'm debugging a program with GDB. ``` unsigned int example = ~0; ``` gives me: ``` (gdb) x/4bt example 0xffd99788: 10101000 10010111 11011001 11111111 ``` why is this not all 1's? i defined it as ~0... then the next line of code is: ``` example>>=(31); ``` and GDB gives me this when I tr...
You need to take the address of example in the gdb statement: ``` (gdb) x/4bt &example ```
How to find the size of an integer array in C. Any method available without traversing the whole array once, to find out the size of the array.
If the array is a global, static, or automatic variable (int array[10];), thensizeof(array)/sizeof(array[0])works. If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the...
On a quite ancient UNIX (Apple A/UX 3.0.1 for 680x0 processors) using the built-in c compiler (cc), this issue arrises. Here is the code I'm trying to compile: ``` #include <stdlib.h> #include <stdio.h> int main() int argc; char **argv; { if (argc > 1) puts(argv[1]); return (EXIT_SUCCESS...
Forold skoolK&R C I think it needs to be: ``` #include <stdlib.h> #include <stdio.h> int main(argc, argv) int argc; char **argv; { if (argc > 1) puts(argv[1]); return (EXIT_SUCCESS); } ```
Is that possible? I've seen no method that would generate a plain old C vector or array. I have just NSNumber objects in my array which I need as C vector or array.
An alternative to mouviciel's answer is to use NSArray'sgetObjects:range:method. ``` id cArray[10]; NSArray *nsArray = [NSArray arrayWithObjects:@"1", @"2" ... @"10", nil]; [nsArray getObjects:cArray range:NSMakeRange(0, 10)]; ``` Or, if you don't know how many objects are in the array at compile-time: ``` NSUInte...
I'd like to write a program which reads user input only from tty, instead of redirected stdin pipes, likepasswdandsshdo. Is there any approach? Many thanks
You should try opening/dev/ttydirectly. That's the only way I know for sure that you can bypass thestdinredirection. /dev/ttyis usually a symbolic link to youractualtty device, which may be/dev/consoleor/dev/tty24or pretty much anything you want, depending on the weird and wonderful way your system may be set up. The...
How to lock file in Windows so that this file can be opened/read/wrote only by one process? I found out that file can be locked withCreateFileby giving0todwShareModeflag. It works but only the returned handle can be used to work with file. But I want to be able to lock the file to other processes and at the same time...
Why do you need to create same file twice in the same process? You could use one handle in all I/O functions of your process without reopening file. If you need to pass the handle to another process you could useDuplicateHandlefunction.
Under what circumstances will the "False" part of the following code be executed? ``` x = 20; y = -30; if (x > y) { // True part } else { // False part } ``` NB: Language is C, compiler is gcc (although some other compilers may also do the same thing).
Ifyis of unsigned integer type it will be initialized to some very large value (because of how negative integer values are represented) and the comparison expression will evaluate tofalse.
``` char *substring(char *text, int position, int length) { int i, j=0; char *temp ; for(i=position-1; i<position+length-1; i++) { temp[j++] = text[i]; } temp[j] = '\0'; return temp; } ``` Hi What is the error in the following code.. I am trying to run this on Fedora Machine.. And its givi...
tempis uninitialized.
Currently, we are defining ourselves an extended log mechanism to print out the class name and the source line number of the log. ``` #define NCLog(s, ...) NSLog(@"<%@:%d> %@", [[NSString stringWithUTF8String:__FILE__] lastPathComponent], \ __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__]) ``` For exampl...
``` print(__FUNCTION__) // Swift NSLog(@"%@", NSStringFromSelector(_cmd)); // Objective-C ``` Swift 3 and above ``` print(#function) ```
We have a set of C macros, here, for using the preprocessor to do bitfield operations, and we run into warnings when attempting to use these macros in visual studio. The problem can be demonstrated very easily: ``` #define BITFIELD_WIDTHMASK(Width) \ ((Width) >= 32 ? ~0x0ul : (1ul << (Width)) - 1) unsigned long...
What about: ``` #define BITFIELD_WIDTHMASK(Width) \ ((Width) >= 32 ? ~0x0ul : (1ul << (Width % 32)) - 1) ``` ?
There's this instance variable in my objective-c class: ``` ALuint source; ``` I need to have an mutable array of OpenAL Sources, so in this case probably I need a mutable C-array. But how would I create one? There are many questions regarding that: 1) How to create an mutable C-array? 2) How to add something to ...
I’d keep things simple.ALuintis some kind ofint, so that you can easily wrap it usingNSNumberand stick it in an ordinaryNSMutableArray: ``` ALuint bar = …; NSMutableArray *foo = [NSMutableArray array]; [foo addObject:[NSNumber numberWithInt:bar]]; // and later ALuint source = [[foo lastObject] intValue]; ```
From a long time ago I have a memory which has stuck with me that says comparisons against zero are faster than any other value (ahem Z80). In some C code I'm writing I want to skip values which have all their bits set. Currently the type of these values ischarbut may change. I have two different alternatives to perf...
If it is faster, the compiler will substitute it for you. In general, you can't write C better than the compiler can optimize it. And it is architecture specific anyway. In short,don't worry about itunless that sub-micro-nano-second is ultra important
Can somebody please explain what does this warning mean:undefined reference to 'WinMain@16'?
Googlehaslotsofreferencestothat particular error. You need to provide aWinMainfunction, depending on what type of project you are building (console or Windows app).
Is there an easy way to check if a pipe is closed before writing to it in C? I have a child and parent process, and the parent has a pipe to write to the child. However, if the child closes the pipe and the parent tries to read - I get a broken pipe error. So how can I check to make sure I can write to the pipe, so I...
A simple way to check would be to do a 0 byte write(2) to the pipe and check the return. If you're catching SIGPIPE or checking for EPIPE, you get the error. But that's just the same as if you go ahead and do your real write, checking for the error return. So, just do the write and handle an error either in a signa...
I'd like to know if a fd has data available for reading. I have triedioctlwithFIONREADbut that results in a "Operation not supported error". Any ideas?
You can useselect(), with a zero (notNULL) timeout.
What do the last lines mean? ``` a=0; b=0; c=0; a && b++; c || b--; ``` Can you vary this question to explain with more interesting example?
For the example you gave: ifais nonzero, incrementb; Ifcis zero, decrementb. Due to the rules ofshort-circuiting evaluation, that is. You could also test this out with a function as the right-hand-side argument;printfwill be good for this since it gives us easily observable output. ``` #include <stdio.h> int main(...
i'm trying to run one c executable file using phpexec(). When c contains a simple program likeprint hello. I'm using ``` exec('./print.out') ``` It's working fine. But when I need to pass a argument to my c program I'm using ``` exec('./arugment.out -n 1234') ``` It is not working. Can any body tell me how to pas...
From taking a look at the php documentation, it appears thatexectreats arguments a bit oddly. You could try doing ``` exec("./argument.out '-n 1234'") ``` to prevent it from mangling them (it normally separates them all on space, which might be what's messing it up).
I'm in the process of documenting some firmware but I'm unsure what the standard is (if there is one) for representing static variable declaration in flowcharts
In the 'classic' flowchart it would just be the rectangle.
What does theexternkeyword mean? I've seen that in front of an function declaration like ``` extern void DoFoo ... ```
externgives a nameexternal linkage. This means that the object or function is accessible through this name from other translation units in the program. For functions, this is the default linkage in any case so its usage (in this context) is usually redundant.
Is an NSInteger big enough for UInt32? Or is it even the same thing?
No becauseNSIntegeris a signed type whileUInt32is unsigned. You should inspect the definitions of these types in Apple's header files to understand what they mean. It's very easy to do so. From an open project in Xcode, select File -> Open Quickly... (Command-Shift-D) and type the type name you are interested in into...
I have an CGFloat property and sometimes I get a return value of type Float64 or also of type Float32. Could I store both safely to CGFloat?
From the headers: ``` // CGBase.h typedef float CGFloat; // MacTypes.h typedef float Float32; typedef double Float64; ``` SoCGFloatandFloat32are bothfloats whileFloat64is adoubleso you would lose precision. (Edit to clarify: this is for 32 bit systems such as the iPhone. If you are build...
so if I do: ``` dup2(0, backup); // backup stdin dup2(somefile, 0); // somefile has four lines of content fgets(...stdin); // consume one line fgets(....stdin); // consume two lines dup2(backup, 0); // switch stdin back to keyboard ``` I am finding at this point.. stdin still contains the two lines I haven't consume...
You haven't flushed the stdin buffer. It has buffered up all the lines of somefile even if the underlying file descriptor is restored.
Why canWinMainhave two return types? If I remove it,will report this warning: ``` warning C4007: 'WinMain' : must be '__stdcall' ``` Or I'm reading intWINAPIwrongly? UPDATE I tried these two variants which are said to be the same asWINAPI,none work: ``` int __declspec WinMain int __declspec(stdcall) WinMain ```...
WINAPIisn't a return type it's a macro expanding to an implementation specific decoration or attribute for the function. In this instance it specifies the calling convention and is equivalent to__stdcall. Grammatically, WINAPI is roughly (but not exactly) equivalent to a storage class specifier likestatic.
I have assigned the complement value in an unsigned variable. Then why this C program outputs a negative number? ``` #include<stdio.h> #include<conio.h> int main() { unsigned int Value = 4; /* 4 = 0000 0000 0000 0100 */ unsigned int result = 0; result = ~ Value; /* -5 = 1111 ...
The%dformat specifier instructsprintfto treat the argument as a signed integer. Use%uinstead.
I'm using GCC on Windows 7 (using the TDM's build). I installed MSYS to be able to executeMakeand compile using makefiles. However, it is tedious to every time start up the MSYSBashshell, navigate to the directory of the project and runmake. What I want is to automate this process. I prefer to have a batch file in Wi...
Not an MSYS expert, but does something like this work for you: ``` rem Call this something like compile-project.bat c: cd \src\project bash -c "make" ```
As I know, C inline function body should be defined in .h file because it causes an error 'function-name used but never defined" if body defined in .c file. Is this the regular way? Or how to define inline function body in .c file?
Each.cfile is compiled independently into.ooutput. If you define the inline function in a.cfile, other source files cannot see such function, so that cannot be inlined. Therefore the inline function should be in the.hfile to allow the code to be shared.
What's the "DNS_BLOCK_ASSERTIONS" (C compiler flag)?
The NS_BLOCK_ASSERTIONS macro (no "D") suppresses the checks performed by NSAssert. You supply it to the compiler using-DNS_BLOCK_ASSERTIONS(see the comments for an explanation of the "D").
And, if it does, how do you use one? (syntax) Also, why does or why doesn't C support lambda expressions?
No, C has no support for lambda expressions. If you're willing to use C++, Boost has a library that emulates lambdas. Also, C++0x will have built-in support for lambda expressions. There wasn't a huge demand for lambda expression support in C at the time, so the language didn't support it.
I’m buried in multithreading / parallelism documents, trying to figure out how to implement a threading implementation in a programming language I’ve been designing. I’m trying to map a mental model to thepthreads.hlibrary, but I’m having trouble with one thing: I need my interpreter instances to continue to exist af...
Use apthread_cond_t; wait on it on one thread and signal or broadcast it in the other.
I'm trying to find a way to multiply an integer value with negative value just with bit shifting. Usually I do this by shifting with the power of 2 which is closest to my factor and just adding / subtracting the rest, e.g.x * 7 = ((x << 3) - x) Let's say I'd want to calculatex * -112. The only way I can imagine is-(...
Get the compiler to do it, then check the produced assembly.
Is this code correct? ``` char *argv[] = { "foo", "bar", NULL }; ```
It's syntactically correct, and it does create a NULL-terminated array of strings. argv is passed tomainaschar*[](or equivalently,char**), but it's "more correct" to treat string literals as aconst char*rather than achar*. So with this particular example you'd wantconst char *argv[] = {"foo", "bar", NULL }; Maybe yo...
I was inspecting the code of a linux application and i saw the #include in one of the code files. I tried looking it up on opengroup.org but i couldn't find it there, this is what the sys directory looks like:http://www.opengroup.org/onlinepubs/000095399/basedefs/sys/. I guess it's not standard header file, but i che...
Used in conjunction with ptrace(2) (see PTRACE_PEEKUSER):http://linux.die.net/man/2/ptrace
Will this code: ``` inline int funcA(int a) __attribute__((always_inline)) { return a + 1; } inline int funcB(int b) __attribute__((always_inline)) { return funcA(b + 2); } int main() { return funcB(3); } ``` transformed to code like this?: ``` int main() { return ((3) + 2) + 1; } ``` GCC, ARM (iPho...
Inlining function calls is not something the language requires compilers to do. It's a quality of implementation issue (QoI). But any of GCC, MSVC and clang will do it. Of course, you have to enable optimization. For instance ``` # clang++ -cc1 -emit-llvm -O2 -o - main.cpp define i32 @main() nounwind readnone { entr...
All, My company is in the situation where we are using an embedded control system from another company in another country. We do not have the source code or the schematics to this system, and the manufacturer doesn't want to release them, seemingly at any price or under any terms. We are thus stuck with a 6 month tu...
There are plenty of companies that will re-implement the embedded control system without reverse engineering the one you are using now, as long as you know that system's requirements.
(all are declared as ints, none are initialized to anything beforehand. I have included math.h and am compiling with -lm) ``` cachesize = atoi(argv[1]); blocksize = atoi(argv[3]); setnumber = (cachesize/blocksize); printf("setnumber: %d\n", setnumber); setbits = (log(setnumber))/(log(2)); printf("sbits: %d\n", setbit...
logreturns a double. You should round instead of truncate. However, you can uselog2here.
What do the last lines mean? ``` a=0; b=0; c=0; a && b++; c || b--; ``` Can you vary this question to explain with more interesting example?
For the example you gave: ifais nonzero, incrementb; Ifcis zero, decrementb. Due to the rules ofshort-circuiting evaluation, that is. You could also test this out with a function as the right-hand-side argument;printfwill be good for this since it gives us easily observable output. ``` #include <stdio.h> int main(...