question
stringlengths
25
894
answer
stringlengths
4
863
I need to convert a formated data to struct like this: ``` struct header { int a; int b; char c; } ``` I have to do it manually like this: ``` [data getBytes:&h.a range:(NSRange){0,4}]; [data getBytes:&h.b range:(NSRange){4,4}]; [data getBytes:&h.c range:(NSRange){8,2}]; ``` Is there a better way to c...
``` [data getBytes:&h range:(NSRange){0, sizeof(struct header)}]; ```
Is there any way to convert ".so" file into source code or some in readable format.
Source code is probably hard, since the .so doesn't "know" which language it was written in. But you can browse around in the assembly code by doing something like this: ``` $ objdump --disassemble my_secret.so | less ```
I want to use distinct function in users collection. In mongo shell, I can use like the following: ``` db.users.distinct("name"); ``` where name is the collections field used to distinct. likewise I want, the same in c code. Only the distinct part I want, familiar with creating connections, working cursors, working...
Seems like you can do that using themongo_run_commandfunction, sincedistinctis acommand:db.runCommand( { distinct: 'users', key: 'name' } )
I have searched for the usage of conditional statements(<,>,<=,etc..,) in C API documentation in the linkhttp://api.mongodb.org/c/current/. But I am unable to find it. Example: The mongo shell query is ``` db.users.find({age: {$gt: 3}}, {}) ``` I want the equivalent C statement for the above.
For example, query: ``` find({ age : { $gt : 5, $lt : 12}}) ``` would be written like this: ``` bson_init(&b); bson_append_start_object(&b,"age"); bson_append_int(&b,"$gt",5); bson_append_int(&b,"$lt",12); bson_append_finish_object(&b); bson_finish(&b); ```
I am working under Linux, with two physical ethernet interfaces. I have grouped the two interfaces to a bonding interface for backup... and it works. I would like to know if there is any way to know, from my C user program, what is the active interface. Thanks
Look at/sys/class/net/bond0/bonding/active_slaveand read it using a program or code of your choice. (Replace path accordingly if using an interface name different frombond0.)
I was reading android source code in that I am not getting what doesOPEN GL ESlibrary do and what doesEGL librarydo.? Is there any relationship between this two libraries? I have looked athttp://www.khronos.org/opengles/documentation/opengles1_0/html/but still not getting.
EGL is the interface between OpenGL ES and the underlying native display platform. It is used to create & manage rendering surfaces & graphics contexts.
I executed this code after compiling in codeblocks:- ``` #include <stdio.h> int main() { char arr[]="HELLO"; int a=arr; return printf("...%s ,%s\n",arr,&a+1); } ``` I got this output:- ...HELLO,HELLO when I changed&atoa,printf returned -1. I am not able to sort out this address logic ,please help...
You are tellingprintfto expect a string, but you are giving it the address of anint(&a). This invokesundefined behaviour, so anything could happen. [In practice, what's probably happening is that the compiler placesadirectly belowarron the stack. So&a+1ends up equal in value to&arr.printfthen reinterprets that addr...
Does C have scope hiding? For example, if I have a global variable: ``` int x = 3; ``` can I 'declare' inside a function or main 'another' int x?
Yes, that's how C works. For example: ``` int x; void my_function(int x){ // this is another x, not the same one } void my_function2(){ int x; //this is also another x { int x; // this is yet another x } } int main(){ char x[5]; // another x, with a different type } ```
I have a function that recieves a pointer to dynamic array of 100 ints. But instead of 100 I have just 50 allocated by malloc or calloc before that. Is there a way that I could check if any ellement (like 79th for example) is allocated rather than wonder what this SIGSEGV actually means ? My question is purely theor...
No, the pointer does not store its size. You may be better off storing the size and the pointer in a struct and passing it instead: ``` typedef struct { size_t size; int *ptr; } my_data; ``` ``` void myFunc(my_data *data) { size_t i; for(i = 0; i < data->size; i++) { // data->ptr[i]; ...
How can I upload (very) large file with HTTP protocol in C (or C++)? I know it's not the right way to upload huge files, but that's not the point. I've already seen sources about POST transfers of files in C++ but I noticed that, each time, the WHOLE binary file was included inside the POST sequence (between "--boun...
You may use "Content-Range" header in HTTP POST request, to upload a slice of a huge file. ``` POST http://[server_ip]:80/upload?fn=xx.dat HTTP/1.1 Content-Range: bytes=0-4095 Content-Type: application/octet-stream Content-Length: 4096 ...... ```
For functions registered usingatexit(): Is it possible to retrieve references to them, to call them directly? Although this is meant as a general question, solutions regarding the use ofgcc/glibcare welcome.
Not in any portable way, no. The list of registered functions is owned by the runtime library, and there is no interface to access it. For glibc specifics as per your comment, the exit handlers are implemented byexit.candexit.h. I haven't studied them intensely enough to figure out of it's possible to drill through t...
I need to convert a formated data to struct like this: ``` struct header { int a; int b; char c; } ``` I have to do it manually like this: ``` [data getBytes:&h.a range:(NSRange){0,4}]; [data getBytes:&h.b range:(NSRange){4,4}]; [data getBytes:&h.c range:(NSRange){8,2}]; ``` Is there a better way to c...
``` [data getBytes:&h range:(NSRange){0, sizeof(struct header)}]; ```
Is there any way to convert ".so" file into source code or some in readable format.
Source code is probably hard, since the .so doesn't "know" which language it was written in. But you can browse around in the assembly code by doing something like this: ``` $ objdump --disassemble my_secret.so | less ```
I want to use distinct function in users collection. In mongo shell, I can use like the following: ``` db.users.distinct("name"); ``` where name is the collections field used to distinct. likewise I want, the same in c code. Only the distinct part I want, familiar with creating connections, working cursors, working...
Seems like you can do that using themongo_run_commandfunction, sincedistinctis acommand:db.runCommand( { distinct: 'users', key: 'name' } )
I have searched for the usage of conditional statements(<,>,<=,etc..,) in C API documentation in the linkhttp://api.mongodb.org/c/current/. But I am unable to find it. Example: The mongo shell query is ``` db.users.find({age: {$gt: 3}}, {}) ``` I want the equivalent C statement for the above.
For example, query: ``` find({ age : { $gt : 5, $lt : 12}}) ``` would be written like this: ``` bson_init(&b); bson_append_start_object(&b,"age"); bson_append_int(&b,"$gt",5); bson_append_int(&b,"$lt",12); bson_append_finish_object(&b); bson_finish(&b); ```
I am working under Linux, with two physical ethernet interfaces. I have grouped the two interfaces to a bonding interface for backup... and it works. I would like to know if there is any way to know, from my C user program, what is the active interface. Thanks
Look at/sys/class/net/bond0/bonding/active_slaveand read it using a program or code of your choice. (Replace path accordingly if using an interface name different frombond0.)
I was reading android source code in that I am not getting what doesOPEN GL ESlibrary do and what doesEGL librarydo.? Is there any relationship between this two libraries? I have looked athttp://www.khronos.org/opengles/documentation/opengles1_0/html/but still not getting.
EGL is the interface between OpenGL ES and the underlying native display platform. It is used to create & manage rendering surfaces & graphics contexts.
This question already has answers here:Closed11 years ago. Possible Duplicate:Why doesn't scanf need an ampersand for strings and also works fine in printf (in C)? In C when we use thescanf()function to get user input, we always use the&sign before the variable. For example: ``` scanf("%d", &number); scanf("%c", ...
A "string" in C is the address of a character buffer.You wantscanfto fill the memory in the buffer, which is pointed to by the variable. In contrast, anintis a block of memory, not an address. In order forscanfto fill that memory, you need to pass its address.
This question already has answers here:Closed11 years ago. Possible Duplicate:Is array name a pointer in C?How do I use arrays in C++? Following program shows the same attributes of an array and pointer... Are array elemenst somehow related to pinters? ``` #include <iostream> using namespace std; int main(){ in...
the C FAQ answers a lot of the common questions about arrays and pointers, and that arrays aren't pointers but there is some magic going on that makes them look like pointers... http://c-faq.com/aryptr/index.html
Is it possible to make a pointer variable hold the address of another pointer variable? eg:int a; int *ptr,*ptr1; ptr=&a; ptr1=&ptr;
Sure, a pointer to a pointer. ``` int i; int *pi = &i; int **ppi = &pi; ``` There is nothing particularly unusual about a pointer to a pointer. It's a variable like any other, and it contains the address of a variable like any other. It's just a matter of setting the correct type so that the compiler knows what to d...
I have microcontroler that I am working with. When debugging it is necessary to call a function from that is hard coded in ROM. Technical Reference shows how to do this: ``` # define Device_cal (void(*)(void))0x3D7C80 ``` and calling procedure looks like this: ``` (*Device_cal)() ``` I can't understand what actual...
void (*) (void)is a type. It's a pointer to a function that takes no parameter and returnsvoid. (void(*)(void)) 0x3D7C80casts the0x3D7C80integer to this function pointer. (*Device_cal)()calls the function. (Device_cal)()would do the exactly the same. The parentheses around*Device_calandDevice_calare required becau...
I understand the whole typedef-ing a struct in C concept so that you can avoid using the keyword struct whenever you use it. I'm still a little confused about what's going on here though. Can someone tell me the various things this structure definition is doing? ``` typedef struct work_tag { //contents. } work_...
It defines two typedefs, like: ``` typedef struct work_tag { //contents. } work_t; typedef struct work_tag *work_p; ```
Are both pointer statements the same? ``` void reverse(const char * const sPtr){ } ``` and ``` void reverse(const char const *sPtr){ } ```
No. const char const *sPtris equivalent toconst char *sPtr. const char *sPtrsay parametersPtris a pointer to aconst char. const char * const sPtris aconstpointer to aconst char. Note that this is equivalent in C99 and C11: (C99, 6.7.3p4) "If the same qualifier appears more than once in the same specifier-qualifie...
Given knowledge of the prototype of a function and its address in memory, is it possible to call this function from another process or some piece of code that knows nothing but the prototype and memory address? If possible, how can a returned type be handled back in the code?
On modern operating systems, eachprocess has its own address spaceand addresses are only valid within a process. If you want to execute code in some other process, you either have toinject a shared libraryorattach your program as a debugger. Once you are in the other program's address space, this codeinvokes a functi...
Hello everyone I want to ask a question about includingguardsin C programming. I know their purpose but in some programms I have seen a1" written after #define like this: ``` #ifndef MYFILE_H #define MYFILE_H 1 ``` What is the purpose of this1? Is it necessary?
It's not necessary,#define MYFILE_Hshould do the trick. The fact thatMYFILE_Hisdefined(the condition tested byifndef) is separated from its value. It could be 0, ' ', 42, etc.
I'm trying to implement a function that have to return the minimum value from a list of array, without comparers (“==”, “!=”, “>”, “<”, “>=”, “<=”), but to simplify I will work with only two variables. Suppose I have two values : the number 5 declared as "a" and the number 35 declared as "b", so I found a way to get ...
Cheap & cheesy solution: If you are using 32-bit unsigned integers you can cast them to 64-bit signed integers and use the code you have above.
I'm working on a Nelder-Mead optimization routine in C that involves taking the average of twofloats. In rare (but perfectly reproducible) circumstances, the twofloats, sayxandy, differ only by the least significant bit of their significand. When the average is taken, rounding errors imply that the result will be eith...
I don't think there's a hardware rounding mode for that. You have to write your own function, then, ``` double average(double x, double y) { double a = 0.5*(x+y); return (a == x) ? y : a; } ```
I am just starting to learn C, this is probably a very easy question for you guys but your help is very appreciated. I am trying to use this code to count the number of characters inputted into the console but when I hit enter it just gives me a blank new line, likeprintfhasn't worked. Where am I going wrong? ``` int...
When you hit enter, the program increments the counter because it gets a newline character and waits for more input. You have to feed the program an EOF withCtrl+D(Linux, Unix, Mac) orCtrl+Z,Enter(Windows).
ThisMicrosoft support page shows that there is no Win32 equivalent to C Run-Time'sisdigit(). But there isIsCharAlphaNumericandIsCharAlpha. Intuitively, this leads me to:IsCharAlphaNumeric() && !IsCharAlpha()is equivalent to (the non-existent)IsCharNumeric() But I may be missing something... Can I safely assume tha...
Without knowing the semantics ofIsCharAlphaNumeric()andIsCharAlpha(), there's no way to determine whether ``` IsCharNumeric(c) == (IsCharAlphaNumeric(c) && !IsCharAlpha(c)) ``` holds for allc. And it might be reasonable that it doesn't hold, for example hexadecimal digits can be both, numeric and alphabetic. In oth...
I've been confused with what I see on most C programs that has unfamiliar function declaration for me. ``` void *func_name(void *param){ ... } ``` What does*imply for the function? My understanding about (*) in a variable type is that it creates a pointer to another variable thus it can be able to track what ad...
The asterisk belongs to the return type, and not to the function name, i.e.: ``` void* func_name(void *param) { . . . . . } ``` It means that the function returns a voidpointer.
What is the correct term/name for the following construction: ``` string myString = (boolValue==true ? "true": "false"); ```
It's a ternary conditional expression.
i searched for my problem, but didn't found it. I have a declaration of an pointer array ``` int *Blocks[] = {Block1,Block2,Block3,Block4}; ``` The Blocks are arrays with a length of 50. Now i have a for-loop, there i want to step by step init the fields ``` for(int i=0;i<50;++i) { *(Blocks[section])+i = 1; } ```...
No, that line isn't quite right. The following is (note the position of the parentheses): ``` *(Blocks[section]+i) = 1; ``` or, equivalently but more concisely: ``` Blocks[section][i] = 1; ```
Teaching myself C and finding that when I do an equation for a temp conversion it won't work unless I change the fraction to a decimal. ie, tempC=(.555*(tempF-32))will work buttempC=((5/9)*(tempF-32))won't work. Why?According to the book "C Primer Plus" it should work as I'm using floats for both tempC and tempF.
It looks like you have integer division in the second case: ``` tempC=((5/9)*(tempF-32)) ``` The5 / 9will get truncated to zero. To fix that, you need to make one of them a floating-point type: ``` tempC=((5./9.)*(tempF-32)) ```
I'm usingsprintf(newpath, "%s%s", cCurrentPath, "\\init.scm");to add \init.scm to current dir path but there is the usual warning: warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. Sprintf_sdoesn't support suc...
sprintf_sis basically the same assprintf, but it gets another parameter: ``` sprintf_s(newpath, sizeof(newpath), "%s%s", cCurrentPath, "\\init.scm"); ``` Note - ifnewpathis a normal character array,sizeof(newpath)works. If it's a pointer or an array passed as an argument, you may need a different way to get the size...
i need to understand the format of init.rc in init.rc there are so manny services. One of them is ``` service bootanim /system/bin/bootanimation user graphics group graphics disabled oneshot ``` here whats meaning ofdisabled,oneshotfor what purpose this all are here? i have refer thisarticlebut not...
http://elinux.org/Android_Bootingis probably a better reference. There's alsosystem/core/init/README.mdfrom the Android source tree.
Ok so I was just wondering how console applications liketop(1)for linux overwrite multiple lines. I want to know how to do it for C++ or C. I know how to overwrite 1 line by just putting a \r but I wanted to know how to do so for multiple lines, again like in top or if its even possible.
They use terminal escape sequences to move the cursor around the screen. A few even use direct framebuffer access, to treat the screen as an array of characters which can be directly indexed. Thecurses(orncurses) library is a good abstraction layer.
I was trying to understand why structure padding is the reason structures cannot be compared by memcmp. One small thing i dont understand about structure padding is this... why should "a short be 2 byte aligned"or"a long be 4 byte aligned". I understand it is with their sizes but why can they not appear at any byte b...
Because some platforms (i.e. CPUs) physically don't support "mis-aligned" memory accesses. Other platforms support them, but in a much slower fashion. The padding you get in a struct is dependent on the choices your compiler makes, but it will be making those choices in order to satisfy the specific requirements of ...
Is there any standard (or widely used) simple POSIX path manipulation library for C (path join, filename stripping, etc.) ? Actually, because I'm mostly working under Windows, I currently use'shlwapi'path functions. Is there any equivalent set of functions available for POSIX paths?
path join - snprintf()filename stripping - dirname()etc. - basename(), realpath(), readlink(), glob(), fnmatch()...
In a question about getting a system's time zone,this answerdid not get up-voted. It suggests the use oftzset()and some system globals (e.g.daylight,timezone, andtzname) fromtime.h. After some testing, I was able to get accurate results from this method on both Windows and Mac. But I'm guessing the answer mentioned ...
No, if there is not an standard C function (and you are programming to at least one POSIX compliant system) then you should use prefer POSIX functions over OS specific ones. If one of your systems is not POSIX compliant, then you should have an OS specific solution only for that system.
Currently I am doing something like ``` "+" return TADD; ``` in my .l file to return token TADD.I want to know if there is a way I can return '+' directly so that I don't have to add a token for every operator.
Is this yacc/lex? If so, then you can just ``` "+" return '+'; ```
``` int m=32 printf("%x" , ~m); ``` Output of this statement isffdfand without~output is20. What is the significance of%xand~?
The~operator is bitwise negation. It will print bitwise negation ofm's value.%xmeans thatprintfwill output its value in hexadecimal format. So, value0xffdfis the negation of value0x20(32). Value 32 (int bits would be): ``` 0000 0000 0010 0000 ``` Its bitwise negation will be: ``` 1111 1111 1101 1111 ``` Which ma...
I'm trying to use WinSock.h header file, but I get either one of the errors below: in VS2010 (C++): ``` Unresolved External Symbol to [the function included in winsock.g, e.g socket()] ``` in gcc command line (C): ``` Undefined Reference to [the function included in winsock.g, e.g socket()] ``` code is simple: Jus...
According to the documentation, you needws2_32.lib. Go to Project->Properties->Linker->Additional dependencies and addws2_32.lib. EDIT: That should be Project->Properties->Linker->Input->Additional Dependencies
Suppose a process is running and it invokes a system call . Does that means that process will now be blocked . Are all system calls block a process and changes its state from running to block ? Or it depends on the scenario at that time?
No, it does not mean the process is blocked. Some system calls are blocking and some are not. However, note that for the duration of the time the kernel processes the system call, while the process continues to run, your own user code is not executing but the kernel code is executing on behalf of the process.
I am trying to pass a string from C# to a C DLL. From what I have read .NET should do the conversion from string to char* for me, however I get "error CS1503: Argument '1': cannot convert from 'string' to 'char*'" Can someone advise me of where I have went wrong? Thanks. C# code ``` [DllImport("Source.dll", ExactSpe...
Declare your external method as: ``` public static extern bool StreamReceiveInitialise(string filepath); ```
I am a bit confused in user space and kernel space . Is kernel space included in the 4 gb virtual memory of a.out in linux or kernel space is different and not included in that 4 gb memory space . Also the part of 4 gb virtual memory which is reserved for operating system includes kernel or kernel space . Please do ...
The standard memory model for 32-bit Linux uses 1 GB for the kernel, and 3 GB for the user space. This sums to the total 4 GB memory space available, so "yes", the kernel's space is included in the address space. This articlehas some graphs that show the split.
Im trying to triangulate a polygon for use in a 3d model. When i try using the ear method on a polygon with points as dotted below, i get triangles where the red lines are. Since there are no other points inside these triangles this is probably correct. But i want it to triangulate the area inside the black lines only...
There are many algorithms to triangulate a polygon that do not need partitioning into monotone polygons first. One is described in my textbookComputational Geometry in C, which has code associated with it that can be freely downloaded from that link (in C or in Java). You must first have the points in order correspon...
I am trying to change the affinity of each thread inside the start routine. Here's the code. In the below code, 't' is the argument passed through the pthread_create function. ``` cpu_set_t mask; pthread_t c; a = *((int *)t); printf(" thread no. is %d \n",a); CPU_ZERO(&mask); a =a/2 + 1; ...
I had misunderstood the bounds of the mask. That was where I was going wrong.
Is there a way to declare a variable like this before actually initializing it? ``` CGFloat components[8] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15 }; ``` I'd like it declared something like this (except this doesn't work): ``` CGFloat components[8]; components[8] = { 0.0, 0.0, 0.0...
You cannot assign to arrays so basically you cannot do what you propose but in C99 you can do this: ``` CGFloat *components; components = (CGFloat [8]) { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15 }; ``` the( ){ }operator is called thecompound literaloperator. It is a C99 feature. Note that in this examplecomp...
I want to create log.c file with containing info(), debug() and error() functions. These functions are working without printing file name, line number,..etc. So when I call one of this function I want to dump the file name, line number, and function name of the caller. So how do we exactly trace back? Is there a way t...
I'd pass the data to the function through parameters (maybe get the help of a macro) ``` int info(const char *fname, int lineno, const char *fxname, ...) { /* ... */ } int debug(const char *fname, int lineno, const char *fxname, ...) { /* ... */ } int error(const char *fname, int lineno, const char *fxname, ...) { /*...
I might be going insane, but I don't think I've ever seen this in c++ (though my reference code is in C). Why is there a static on the return value of the code here and what impact does it have? I don't think I've ever seen a static function outside class scope (but obviously C doesn't have classes and this probably...
thestaticis not on thereturn type but on the function definition. static functions don't have external linkage basically they are only visible to other functions in the same file.
I have a pointer array defined declared as ``` char (*c)[20] ``` When allocating memory using malloc ``` c=malloc(sizeof(char)*20); ``` or ``` c=(char*)malloc(sizeof(char)*20); ``` I get a warning as "Suspicious pointer conversion" Why?
In this declaration char (*c)[20]; cobject has typechar (*)[20]. We know that in Cmallocreturn type isvoid *and that there is an implicit conversion betweenvoid *to any object pointer types. Soc = malloc(whatever_integer_expression)is valid in C. If you get a warning, you are probably using a C++ compiler or you a...
Is it possible toctypedefa function, as it is a common pattern in C++? Like ``` typedef int (*foo)(int, double, char*) # Cython equivalent ctypedef int (*foo)(int, double, char*) ``` Or at least to extern it without declaring it directly ? Something similiar to ``` # myheader.h typedef int (*foo)(int, double, char...
Yes that's perfectly possible: ``` ctypedef void (*function_type_name)(int, int) ```
I am trying to implement my own memory allocation code which is simple yet efficient. Any idea where I can start from. What algorithm gcc uses?
This is a problem that has been examined and implemented hundreds of times; chances are your implementation is going to work in a very specific situation and nowhere else. Before spending an extraordinary amount of time attempting to solve this problem yourself, consider existing implementations that beat gcc's genera...
When I compile C/C++ program withpopeninphp... I got this error: ``` g++: error trying to exec 'cc1plus': execvp: No such file or directory ``` but if I run php code in shell.. it works fine.. in Arch Linux.. PHP Code: ``` <?php function rfile($fp) { $out=""; while (!feof($fp)) { $out.= ...
You need to installgcc-c++package. ``` yum install gcc-c++ ```
I was figuring out a problem where starting the application from GDB results in a symbol lookup error, but starting it from the shell works. It turns out that whenever you start a program from within GDB it will start a new shell and thus override all environment variables I had set before starting GDB (likeLD_LIBRAR...
I am guessing that youunconditionallysetLD_LIBRARY_PATHin your~/.cshrcor the like. So if from a shell prompt you do this: ``` export LD_LIBRARY_PATH=foo # or for csh: setenv LD_LIBRARY_PATH foo $SHELL -c 'echo $LD_LIBRARY_PATH' ``` the result is something other thanfoo. Don't dothat. Usually this happens to CSH us...
In a homework assignment we were asked to add a system call to the Linux Kernel (Red Hat 2.4.18). According to the assignment the return value of the new system call should be void. The system call in itself is quite simple (just one assignment) and there is no chance for error. From what I read and learnt system call...
In Linux all system calls return long, if they return at all. Say you declare your system call using: ``` SYSCALL_DEFINE0(mycall) { /* ... */ } ``` This results in: ``` asmlinkage long sys_mycall(void) ``` If you don't have any useful return and the call cannot fail, simply return 0 every time to signal succes...
I'm trying to connect to an USB device that's on a remote PC (because there is no 64-bit driver for it, remote PC is 32-bit). I know the commands that I need to send to make settings on the device but I don't know how I can get connected to it. Is there a C++ or C# library that makes it possible to connect to this de...
You might be able to build something using Microsoft'sRemoteFXtechnology, assuming Windows is your target platform.
I want to enumerate all the loaded segments of a module given a module handle. Are there any API functions I can call to do this? Or is the only way reading the PE header and working out which segments are loaded and which are not? If I have to end up reading the PE header, could someone help describe the structure o...
Read these MSDN articles by Matt Pietrek and follow their links: Peering Inside the PE: A Tour of the Win32 Portable Executable File FormatAn In-Depth Look into the Win32 Portable Executable File Format
I am creating an application where I need to push some element in the sequence, I am usingcvSeqPush, but I am not getting its second argumentconst void * element, I need to push a point of typecvPoint. How is this done in C?
That method is called to push on the sequence whatever data you have, but in your case as I guess your sequence is configured to contain CvPoints's you will have to point to that kind of data to have a correct program. ``` CvPoint pnt = cvPoint(x,y); cvSeqPush(srcSeq, (CvPoint *)&pnt); ``` Something like this should...
``` void openUpNow(FILE *x, FILE *y) { x = fopen("xwhatever", "r"); y = fopen("ywhatever", "r"); } int _tmain(int argc, _TCHAR* argv[ ]) { FILE *x, *y; openUpNow(x, y); } ``` warning C4700: uninitialized local variable 'x' used warning C4700: uninitialized local variable 'y' used Remedy?
I don't think that's what you want to do anyway. Assuming you wantopenUpNow()to open the files intoxandyyou should use: ``` void openUpNow(FILE **x, FILE **y) { *x = fopen("xwhatever", "r"); *y = fopen("ywhatever", "r"); } int _tmain(int argc, _TCHAR* argv[ ]) { FILE *x, *y; openUpNow(&x, &y); ...
If I don't return anything in a function which returns something, compiler will warn about the function is not returning anything. But If I callabort()in the function, compiler won't warn. How can I mark my own function like this.
__attribute__((__noreturn__))should do it for Clang or GCC. Since you've tagged your question for Objective-C, that should do it for you!
The Linux kernel uses struct pid to represent PID in kernel space.The C code is below. ``` struct pid { atomic_t count; /* lists of tasks that use this pid */ struct hlist_head tasks[PIDTYPE_MAX]; int level; struct upid numbers[1]; }; ``` I can not really understand why the member tasks can represent "the lists of t...
Because more than one task can be part of the same process. Consider, for example, a multi-threaded process using a 1-to-1 threading library like NPTL. It has a single process ID, is a single process, but consists of multiple entities scheduled by the kernel.
When I have an array in a struct, the meaning is totally clear to me: When the struct is defined, memory for the whole array is reserved and when I copy the struct, all the array contents is copied. ``` typedef struct { uint8_t type; struct { uint8_t length; uint8_t data[5]; } m; } s; ``` ...
An array of an incomplete type as the last member of a struct is a C99 feature called theflexible array memberfeature. In this statement the_s.m.data = something; you are trying to assign an array but in C, arrays cannot be assigned.
New to files in C, trying to read a file via fread Here's the content of the file: ``` line1 how ``` Code used: ``` char c[6]; fread(c,1,5,f1) ``` When outputting var 'c', the contents appear with a random character at the end (eg: line1*) Does fread not terminate the string or am I missing something?
No. Thefreadfunction simply reads a number of elements, it has no notion of "strings". You can add the NUL terminator yourselfYou can usefgets/fscanfinstead Personally I would go withfgets.
Does anyone know what theprlimit64()C function does? I don't seem to have it on my x86_64 Ubuntu machine but it exists in Arch, and I can't seem to find anyone or thing who knows what it does.
prlimitallows you to set or get rlimit resource restrictions (such as number of file handles, memory, etc.) foranotherprocess. It is Linux-specific. Normally, the restrictions you can set depend on the_FILE_OFFSET_BITSmacro, which is 64 on all modern systems. Therefore, the members of the structures used byprlimitand...
If you have a 64 bit OS, you have an address space of virtually unlimited size. So my question is, does on such systems freeing memory matters much? Even if you have limited RAM of say 4 GB, in a demand paging scheme (memory only brought in when touched), the little overhead you would get as compared to freeing memory...
overhead ... is a few extra page swaps ... as memory ... will automatically be swapped Automatically be swapped to where? The ether? Page files are finite, as is the storage they exist on. Do you think it's a good idea never to free memory in a long running service application?
I was reading about GTK+-2.0, and everthing seemed cool enough. Then when I actually got to programming, I realized I had now idea how to make a new window pop up with a button press. I suppose I could make the button "clicked" event fork/exec another GTK program, but come on, there's gotta be an easier way to do some...
Just another GTKWidget *window, display it once the signal for your button is called.
I'm in the process of teaching myself C (coming from Java). I appreciate the language a lot, and one of the main reasons I am learning it is so that I can utilize the JNI feature built into Java to write native code when necessary. My question is mainly about the Windows API. Can I use the functions and features of...
TheWindows API(aka Win32 API) is a pure C library.No you cannot use a Windows shared library on another non-Windows machine unless there is a software that supports Windows ABI - such asWineorReactOS.
I am working on a microcontroller project in C. The main.c file includes a header defining all of the registers as structures and chars. Unfortunately they name the registers unmeaning-full names like PORTA. Is it possible to rename the structures and variable defined in the header file to something more meaningful in...
Promoting comment to answer: The easiest way I can think of is to just use macros: ``` #define OUT PORTA ``` And these don't need to be in the header. EDIT : If the original names are actually names of variables (rather than types), then this is the way to go since the typedef method will not work.
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 need to take a 4 digit input from...
Read it as a string (char*). Pseudocode ``` char str[MaxLen]; Input str; possibly do some checking that the input string is in required format. int a0 = str[0] - '0'; int a1 = str[1] - '0'; etc. ```
i need to get a list or any other enumerable class with info about any connected SCSI-disks, with info just like/proc/scsi/sg/devicesPlease help me and thanks in advance
You've basically named a solution in your question -- just open/proc/scsi/sg/devicesand read from it.
Am working on a project where i require some packet creation, such as ICMP ECHO and other packets where I can start the TCP 3-way handshake. What is the best way to do it node.js? I don't see any packet manipulating libraries like scappy (python) in node.js. All i have for now is node-pcap which is used to monitor pac...
There is a module on npm that gives you access to raw sockets:https://npmjs.org/package/raw-socket
I compiled the code below with the VC++ 2010 compiler: ``` __declspec(dllexport) unsigned int __cdecl __mm_getcsr(void) { return _mm_getcsr(); } ``` and the generated code was: ``` push ECX stmxcsr [ESP] mov EAX, [ESP] pop ECX retn ``` Why is there apush ECX/pop ECXinstruction pair?
The compiler is making room on the stack to store the MXCSR. It could have equally well done this: ``` sub esp,4 stmxcsr [ESP] mov EAX, [ESP] add esp,4 retn ``` But "push ecx" is probably shorter or faster.
This question already has answers here:Closed11 years ago. Possible Duplicate:Linking 32-bit library to 64-bit program One of the libraries a program uses, which needs to be statically linked, is a 32-bit one. If compiled with a 64-bit compiler, it breaks, mostly because the variable types are of different length (l...
Basically, no, you can't link, statically or dynamically, 32bit and 64bit code, not on x86 anyway. What youcando is write a wrapper that runs in a separate process and uses RPC to "link" the library to your code.nspluginwrapperon Linux does something like that for Flash.
Is there any built in swap function in C which works without using a third variable?
No.C++ builtin swap function:swap(first,second);Check this:http://www.cplusplus.com/reference/algorithm/swap/ You can use this to swap two variable value without using third variable: ``` a=a^b; b=a^b; a=b^a; ``` You can also check this: https://stackoverflow.com/questions/756750/swap-the-values-of-two-variables-w...
here is the c code: ``` char **s; s[334]=strdup("test"); printf("%s\n",s[334]);` ``` i know that strdup does the allocation of "test", but the case s[334] where we will put the pointer to the string "test" is not allocated,however,this code works like a charm
Your code exhibits undefined behavior. That doesnotmean it will crash. All it means is that you can't predict anything about what will happen. A crash is rather likely, but not guaranteed at all, in this case.
The man page says: fgets() return s on success, and NULL on error or when end of file occurs while no characters have been read. I wrote a small C file which calls fgets to test its behavior. I particularly wanted to see what happens when EOF occurs after some characters have been inputted. I used the eof key combin...
The behavior you describe has nothing to do with fgets. The shell does not close the input stream until you press ctrl-D the 2nd time.
I am trying to add the float values of a ruby array in C with RubyInline (ruby 1.9.2). The expected output should be a float value. Here is my code: ``` require 'inline' class ArrayMath inline :C do |builder| builder.c " VALUE sum(VALUE arr){ int size = RARRAY_LEN(arr); VALUE *c_a...
xis anintin your C code. Change that to afloat(ordouble) if you don't want the result ofNUM2DBLtruncated. Or do away with that temporary altogether and write: ``` sum += NUM2DBL(c_arr[i]); ```
``` struct A { int i; }; ... A *p = (A*) (8); // or A *p = 0; p->i = 5; // Undefined Behavior according C/C++ standard ``` However, practically most of the systemwould crash (segmentation fault)for such code. Does it mean that all such Architectures/Systems have a hidden check for pointer indirection (i.e.p->) to...
There are generally no extra hidden checks, this is just an effect of using virtual memory. Some of the potential virtual addresses are just not mapped to physical memory, so translating things like 8 will likely fail.
It's pretty simple what I'm trying to do, and I'm merely having trouble figuring out the right syntax. I want my struct to look like this: ``` struct myStruct { functionPointer myPointer; } ``` Then I have another function somewhere else that passes a function to a function and returns an instance of my struct. ...
It's really no different to any other instance of a function pointer: ``` struct myStruct { int (*myPointer)(void *); }; ``` Although often one would use atypedefto tidy this up a little.
This question already has answers here:select vs poll vs epoll [closed](2 answers)Closed7 years ago. Are there some simple rules of thumb when to usepollvs.epollin a low-latency environment?epollshould have higher overhead if only few of file-descriptors is monitored. Please, give some insight, answers "check it your...
Always usepollunless all of the following are satisfied: You can ensure you're on a (Linux) system that hasepollor you provide a fallback for systems that don't.You have ahugenumber of file descriptors active (at least 1000-10000).The set of file descriptors you're working with is stable over a long time period (addi...
This question already has answers here:Closed11 years ago. Possible Duplicate:Good STL-like library for CAre there any open source C libraries with common data structures? Is there a "standard" library that C programmers use for frequently-used data structures (hash/tree-based sets/maps, heaps, etc.)? Or is there no...
See GLib or APR (Apache Portable Runtime) library, they are the most well-known C libraries for data structures. http://developer.gnome.org/glib http://apr.apache.org
Is there a way to replace the space character to 0 in printf padding for field width Code used ``` printf("%010s","this"); ``` Doesnt seem to work for strings!!
Indeed, the0flag only works for numeric conversions. You will have to do this by hand: ``` int print_padleftzeroes(const char *s, size_t width) { size_t n = strlen(s); if(width < n) return -1; while(width > n) { putchar('0'); width--; } fputs(s, stdout); return 0; ...
I need to implement in C the program ,which reads an unknown number of lines from stdin. I know that the maximum number of lines is 100. I tried to usegets,but I don`t know when to stop the loop. Can you advise me how to implement it?
This depends on when youwantyour program to stop. There are several common approaches: Never: you run an infinite loop until end-user hits^Cor otherwise terminates your program using the facilities of your operating systemUntil the user enters a special marker, i.e. a "keyword"QUIT,EXIT, etc. on a line by itselfUntil...
I write console application which performs several scanf for int And after it ,I performs getchar : ``` int x,y; char c; printf("x:\n"); scanf("%d",&x); printf("y:\n"); scanf("%d",&y); c = getchar(); ``` as a result of this I getc = '\n',despite the input is: ``` 1 2 a ``` How this problem can be solved?
This is becausescanfleaves the newline you type in the input stream. Try ``` do c = getchar(); while (isspace(c)); ``` instead of ``` c = getchar(); ```
I'm not used to C as I'm primarily a Java guy, with some knowledge of C++, so forgive me if this is a trivial question. I could not seem to find an answer while searching online. I'm initializing a char array... ``` char tcp[50]; ``` So that I can concatenate a const char and a char. In examples I saw an easy way t...
The array contents are undefined, assuming it is a local (automatic) array. Use: ``` char tcp[50] = ""; ``` Or: ``` char tcp[50] = {0}; ``` Or: ``` char tcp[50]; tcp[0] = 0; ``` Or: ``` char tcp[50]; memset(tcp, 0, sizeof(tcp)); ``` As you like.
I've been wondering which is implemented in terms of which. My guess goes to egfopenbeing implemented usingOpenFile. From what I can tell, the Win32 API is more complete than the MSVC C library implementation, so my guess would make sense. Is this correct, or is it the other way around?
Yes, Win32 is a "lower-level" API than the standard C-library ... basically the standard C-library on Windows is an abstraction of native Windows syscalls that allows certain standard operations to remain compatible across any series of platforms that support the C-standard library. Each platform will have it's own i...
OS: ubuntu 11.10 Webserver: Apache Code: PHP Hello I am trying to "exec" a C code through PHP web page. When I run the same C code directly on terminal, it works fine, but when I "exec" it through PHP, I get a segmentation fault. Any idea why such behavior? My C code is doing small "malloc"s at a few places. The cod...
Most likely it is a user permissions error. Your web server will run as a different user (nobody, wwwrun or similar). Try doing an su to the web server user, and running the C program as that user.
For a weekend project I'm looking for a micro web-framework like bottle.py (http://bottlepy.org) but for plain old C. Sadly Google was not very helpful. Any suggestions are welcome!
After some more search I foundlibSoup, which looks very nice and is really easy to use. But beware: libSoup is part of GNOME - so this might not be so micro after all when it comes to dependencies.
I keep getting bad pointers. Can anyone tell me what am I doing wrong? ``` int SearchString( char* arr[], char* key, int size ) { int n; for ( n = 0; n < size; ++n ) { if ( strcmp(arr[n], key) ) { return n; } } return -1; } ``` ``` char str[][16] = { "mov","cmp","add","sub","lea","not","clr","i...
Can't tell where yourwordoriginates from. You probably want toif (!strcmp(arr[n],key)) return n;(the reverse). And the type of array is probably not what you want. Try ``` const char *str[] = { "mov",.... }; ``` instead. You have an array of arrays of characters and pass it where you actually expect an array of poin...
``` psApdu->prgbCData = (byte_t*)malloc(APDU_BUFFER_LENGTH); memset((void*)psApdu->prgbCData, 0, APDU_BUFFER_LENGTH); byte_t prgData[] = { 0x01, 0x38, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02 }; memcpy((byte*)psApdu->prgbCData, prgData, sizeof(prgData)); free(psApdu->prgbCData); ``` 'free' statement failing here. What is...
Firstly, you shouldn't cast to and fromvoid *. Alsosizeofis an operator. You need to check thatsizeof prgData <= APDU_BUFFER_LENGTH. You could try this with a static assertion: ``` psApdu->prgbCData = malloc(APDU_BUFFER_LENGTH); memset(psApdu->prgbCData, 0, APDU_BUFFER_LENGTH); byte_t prgData[] = { 0x01, 0x38, 0x00...
Is there a way to create a True Type Font file programmatically inobjective-c? I found this reference,http://developer.apple.com/fonts/TTRefMan/index.html, but it doesn't seem there are any built in methods to accomplish this. Suggestions? Guidance?
No, there isn't any procedural font creation code. Your best bet would be to start with FontForge:http://fontforge.sourceforge.net/
I have a the generator polynomial which has to be converted to binary number to use in my CRC code.Like for example these are the one's that are converted correctly, I want to know how they are done. These are used for ROHC CRC computation: The polynomial to be used for the 3 bit CRC is: C(x) = 1 + x + x^3 this is ...
Those appear to be in reversed binary notation. When representing CRC polynomials, each term maps to one bit. Furthermore, the highest order term is implicit and is omitted. So breaking down your two examples: ``` 1 + x + x^3 = 1101 1 + x + x^2 + x^3 + x^6 + x^7 = 11110011 ``` Chopping off the ...
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
Seesuccess storiespage of CMake project. The most notable projects (IMO of course) areKDEandMySQL.
I want to have two threads to handle windows messages. One for key/mouse input in the client area (this thread also takes care of game logic) and one for the rest because I am making a game and some messages cause DefWindowProc() to block (thus freezing the game). How can I achieve this?
Contrary to what Cody wrote, you most definitely can process messages from multiple threads. However, this is not a customizable free-for-all. Rather, windows have thread affinity: each thread will receive the messages sent or posted to windows created by that thread. There's no way to have any window's messages de...
If I run "emacs -q" (prevents loading of user config, so I know it's not a problem with my setup) and open an empty buffer called foo.C and type: ``` case elSE: ``` And then hit ':', emacs insists on changing "elSE" to "Else". I have no ideawhyit's doing this; I assume it thinks I'm misspelling the "else" keyword, e...
This also happens for me on Emacs 24; it seems to be caused by abbrev-mode - tryM-x abbrev-modeto disable it.
I have to use theSNAPC-library. I compiled my file snap_test.c with the following command: ``` gcc -fopenmp -c -I/home/myName/SNAPDIR/include snap_test.c ``` And then linked it with the library: ``` gcc -fopenmp -o snap_test -L/home/myName/SNAPDIR/lib -lsnap snap_test.o ``` But running the program leads to an err...
You need to add/home/myName/SNAPDIR/libtoLD_LIBRARY_PATH. ``` $ export LD_LIBRARY_PATH+=:/home/myName/SNAPDIR/lib ```
This is a basically duplication ofthis question. However, I'm looking for the same answer that will work in C/C++ - some easy way to add comments to the functions with descriptions of all of the parameters. It was really easy to do in SLickEdit - just press Ctrl+SHift+D. All the answers and methods for the aforementio...
Try Doxygen. You can set it up as follows: Window->Preferences->C/C++ ->Editor->"Documentation tool" Here are more details: A doxygen eclipse plugIn automatically generating stub documentation?
I am trying to read a text file using fscanf.I am working in eclipse in OpenCV on ubuntu. Here are some sample values in the text file 0 5 7 0.547619047619048 1 0.0274509803921569 1 0 6 8 0.541666666666667 1 0.0313725490196078 1 0 8 10 0.533333333333333 1 0.0392156862745098 1 But all fsca...
testd[i][0], etc, is an rvalue. What you need is&testd[i][0].
I try to use fread to read a text file My code is only 2 lines ``` fid = fopen('1.txt', 'r'); c = fread(fid,'double', skipvalue); ``` I have tested different format like double, float32, float64 and different skipvalue from 0 to 8, but none of the combination work. The data is recorded by a c program code fprintf(...
Try thetextscanfunction orfscanf. freadis the counterpart tofwrite, notfprintf. fscanfis the counterpart tofprintf. If you absolutely must usefread, you'd read a string (character array) and then usesscanfto extract the numeric data from it.