question
stringlengths
25
894
answer
stringlengths
4
863
Is there any way to getnnumber of1s using only these binary operations (!,~,&,^,|,+,<<,>>) wherenis an input? Example, ``` n ---> output 0 ---> 0000 1 ---> 0001 2 ---> 0011 3 ---> 0111 4 ---> 1111 ... ```
You can do it like this: ``` // Since "-" is not on your list while "+" is, I'll add negative 1 // using `~0`; this assumes that your computer uses 2's complement // representation of negative numbers. (1 << n) + ~0; ``` The idea is that1 << nproduces a power of two:1,10,100,1000, and so on. Adding a negative one pr...
Is it possible for us to port a SDK written in C into android and used it to develop an apps? because I have a SDk written in C and wish to use it to develop an apps using it, how should I do?
Java talks to the native layer (C code) via theJava Native Interface (JNI). You can use you C SDK if you write JNI wrappers for you API. This way you will be able to import you native library into Java and call your native (meaning C) functions from it. That's what the wrappers are for. This will only work provided t...
Inside my WebKitGTK+ widget, I want to transparently replace some of the images of an HTML page with different image data I holdin memory. According to the documentation athttp://webkitgtk.org/reference/webkitgtk/stable/webkitgtk-webkitwebview.html#WebKitWebView-resource-request-starting, I've hooked into this signal...
figured out one way to do it: replacing the request URL with "data:image/jpeg;base64,[inline data]". Will do for me.
I have search around but have been unable to find what I was looking for. I know that getpid() returns the process ID of the calling process and getppid() returns the process ID of the parent of the calling process. But is there a function that can get the process ID of a program? Or is that what one of the two above ...
A program does not have aPID.PIDmeans process ID. A process is a running instance of a program. So only when the program is executed it gets aPID.
In Qt debug mode, we can watch and edit any variable. My question: is there any existing class that can do the same thing which mean can display all the members of a C structure variable in a table and can edit value of members?
If I get right what you mean answer in NO. Seems to me you are looking for an ability to show any struct{} variable/array in QTableView using generic model class. That can be achieved if C++ had a mechanisms similar to Java Reflection. In your case one of solution can be to change struct's to classes with fields defi...
I understand that in pipinga < b > cmeans to use the data of file b for input to program a instead of stdin, and write the output of program b to the file c instead of stdout. What I dont understand is how to give a piping command to use the data of file b for input to program a instead of stdin and write the output...
You should do this: ``` a < b > c ``` as you mentioned in your question. This does not do what you mean it does: it does not use b as input for a and c as output for b. This uses b as input for a and c as output for a.
``` typedef struct Stack_t* Stack; typedef void* Element; typedef Element (*CopyFunction)(Element); typedef void (*FreeFunction)(Element); ``` Can you please explain me the meaning of the third line ?thanks
This is afunction pointeryou can address a function to that takes anElementand returns anElement, like ``` Element ReturnElem(Element el){ } //define function CopyFunction = ReturnElem; //assign to function pointer Element el = ....; Element el2 = CopyFunction(el); //call function using function-pointer ``` Seeh...
This one is annoying me, but I want to avoid the obvious solution of just using memcpy. ``` struct Person { //Some variables }; void doSomething(char* pointerToSomeone) { struct Person bob; //Assign pointerToSomeone to bob, somehow... } ``` In the above, pointerToSomeone is a pointer to a Person struct...
You cannot assign a pointer tocharto astruct, but you can copy the content pointed to by thechar*into astruct, like this: ``` memcpy(&bob, pointerToSomeone, sizeof(struct Person)); ``` In cases when thepointerToSomeoneis untyped, it is more common to usevoid*instead ofchar*.
What I want it not the normalfopen()function. I want to open the image, as in, when I double click on the image, then the way it opens in the imageViewer. I want to open it like that. Is there any way of doing that through a C code? So basically I want it to pop open and view itself. I am on Ubuntu.
It depends of theimageViewerprogram. If theimageViewerprogram could be called in this way in your linux command line interface ``` $imageViewer myfile.bmp ``` then in your C code you can use system to open your file withimageViewerprogram ``` system("imageViewer myfile.bmp"); ```
Say I have the following program that simply outputs "Hello World": ``` //DEMO.c #include<stdio.h> int main() { printf("HELLO World"); } ``` Now I want to display it both to the screen and to a fileoutput.txt.So I enter the following command in the command prompt(I use CodeBlocks on Windows XP and have configured i...
You will need to download ateecommand for Windows.teeis a UNIX/Linux command that copies the standard input to standard output and also outputs to a file. Then, you can do this: ``` demo.exe | tee output.txt ``` Here is one port ofteefor Windows.
I referred to two reliable sources for the information and both seems to have different definitions of the same thing: http://www.cplusplus.com/reference/clibr%E2%80%A6 http://www.ocf.berkeley.edu/~pad/tigcc/doc/html/stdio_fputchar.html The first source saysputchar()is a function, as isgetchar(), but in the second...
getcharandputcharare functions, but may additionally be defined as macros. Whether they are or not depends on the implementation. The C standard says regarding standard library functions (C99, 7.1.4@1): Any function declared in a header may be additionally implemented as a function-like macro defined in the header.
I need to modify the process name of my program in C language.I precise, this is not the name of a thread that I want to change.I want to change the name of my program, but the only solution I found, is to modify the value ofargv[0].I also found another solution withprctl(PR_SET_NAME, "newname"), but this solution doe...
The differences between invokingprctland modifyargv[0]are: modifyargv[0]changes information in/proc/$pid/cmdlineinvokingprctl(PR_SET_NAME)changes information in/proc/$pid/status That means you will get difference name of your process issuingps -aandps -ax. If you expects same process name for different arguments wh...
Hey guys I'm trying to initialize a 2D char array but am having trouble. ``` int size = 300 * 400; char * frame[3] = malloc(sizeof(char *)*size*3); ``` Gives m:error: invalid initializer. So I tried: ``` int size = 300 * 400; char frame[3][size] = malloc(sizeof(char *)*size*3); ``` But then I geterror: variable-si...
You can try: ``` int size = 300 * 400; const int rows_number = 3; char* frame[ rows_number ]; // crate array with 3 elements, each of them `char*` for( unsigned ii = 0; ii < rows_number; ++ii ) { // allocate `size` char`s for each "row" frame[ ii ] = malloc( sizeof(char) * size ); // do not forget to fre...
I'm compiling my C code using Microchip's C18 compiler. I'm getting a warning[2054] suspicious pointer conversionin this code: ``` unsigned char ENC_MAADR1 = 0x65; unsigned char ENC_ReadRegister(unsigned char address); // ... puts(ENC_ReadRegister(ENC_MAADR1)); // <-- warning on this line ``` What does this warning ...
putsrequiresconst char*, you are deliveringunsigned char, not even a pointer. Fromhere: ``` #include <stdio.h> int puts(const char *s); ``` Theputs()function writes the string pointed to bysto standard output stream stdout and appends a newline character to the output. The string's terminating null character is n...
I want to use an exist function in CUDA, but it contains many class and other functions. Adding__host__ __device__before every function is trivial. So, is there an automatic method to do this? Or how to let nvcc compile all functions as__device__ __host__?
Basically, GPU programming is all about massive parallelism. It is a totally different paradigm than normal single threaded programming. Unless you just want to apply these functions at the same time to individual elements of large arrays, there is no benefit of coding it into the GPU. In fact, GPU core clock is much ...
This question already has answers here:Calling C from Objective C(3 answers)Closed10 years ago. Hi I am trying to use some pure C library in an iOS app, however I have no clue how to call and pass the parameters. Here are 2 functions, Node is a struct: ``` Node *parse(FILE *f); void add_subnode(Node *t, Node *parent...
You could call C functions like this: ``` Node *node = parse(f); // node will hold return value add_subnode(t, parent); ```
3 bits can hold up to a maximum number of 7 (4 + 2 + 1). I'm trying to calculate this using a bitwise operation. ``` 3 is 0b011 ~3 is 0b100 ``` Doing a bitwise OR I would expect 0b111 (i.e. 7). Instead I get ``` int result = (~3) | 3; printf("%i\n", result); ``` -1 What am I doing wrong?
You are doing everything right:N | ~Nresults in a number with binary representation consisting of all ones. Such number is interpreted as-1intwo's complimentrepresentation of negative numbers.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question I'm programming a irc client in GTK, but i'm asking what is the best widget for the ...
A textbox is necessary for user input. Some people like to copy/paste from the room buffer. Whichever control you use for that, try to keep that in mind. I suggest a treeview for the nicklist. Represent servers at the first level, channels and private messages at the second level and the nicklists for channels at th...
I want to use an exist function in CUDA, but it contains many class and other functions. Adding__host__ __device__before every function is trivial. So, is there an automatic method to do this? Or how to let nvcc compile all functions as__device__ __host__?
Basically, GPU programming is all about massive parallelism. It is a totally different paradigm than normal single threaded programming. Unless you just want to apply these functions at the same time to individual elements of large arrays, there is no benefit of coding it into the GPU. In fact, GPU core clock is much ...
This question already has answers here:Calling C from Objective C(3 answers)Closed10 years ago. Hi I am trying to use some pure C library in an iOS app, however I have no clue how to call and pass the parameters. Here are 2 functions, Node is a struct: ``` Node *parse(FILE *f); void add_subnode(Node *t, Node *parent...
You could call C functions like this: ``` Node *node = parse(f); // node will hold return value add_subnode(t, parent); ```
3 bits can hold up to a maximum number of 7 (4 + 2 + 1). I'm trying to calculate this using a bitwise operation. ``` 3 is 0b011 ~3 is 0b100 ``` Doing a bitwise OR I would expect 0b111 (i.e. 7). Instead I get ``` int result = (~3) | 3; printf("%i\n", result); ``` -1 What am I doing wrong?
You are doing everything right:N | ~Nresults in a number with binary representation consisting of all ones. Such number is interpreted as-1intwo's complimentrepresentation of negative numbers.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question I'm programming a irc client in GTK, but i'm asking what is the best widget for the ...
A textbox is necessary for user input. Some people like to copy/paste from the room buffer. Whichever control you use for that, try to keep that in mind. I suggest a treeview for the nicklist. Represent servers at the first level, channels and private messages at the second level and the nicklists for channels at th...
I want to use an exist function in CUDA, but it contains many class and other functions. Adding__host__ __device__before every function is trivial. So, is there an automatic method to do this? Or how to let nvcc compile all functions as__device__ __host__?
Basically, GPU programming is all about massive parallelism. It is a totally different paradigm than normal single threaded programming. Unless you just want to apply these functions at the same time to individual elements of large arrays, there is no benefit of coding it into the GPU. In fact, GPU core clock is much ...
This question already has answers here:Calling C from Objective C(3 answers)Closed10 years ago. Hi I am trying to use some pure C library in an iOS app, however I have no clue how to call and pass the parameters. Here are 2 functions, Node is a struct: ``` Node *parse(FILE *f); void add_subnode(Node *t, Node *parent...
You could call C functions like this: ``` Node *node = parse(f); // node will hold return value add_subnode(t, parent); ```
3 bits can hold up to a maximum number of 7 (4 + 2 + 1). I'm trying to calculate this using a bitwise operation. ``` 3 is 0b011 ~3 is 0b100 ``` Doing a bitwise OR I would expect 0b111 (i.e. 7). Instead I get ``` int result = (~3) | 3; printf("%i\n", result); ``` -1 What am I doing wrong?
You are doing everything right:N | ~Nresults in a number with binary representation consisting of all ones. Such number is interpreted as-1intwo's complimentrepresentation of negative numbers.
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question I'm programming a irc client in GTK, but i'm asking what is the best widget for the ...
A textbox is necessary for user input. Some people like to copy/paste from the room buffer. Whichever control you use for that, try to keep that in mind. I suggest a treeview for the nicklist. Represent servers at the first level, channels and private messages at the second level and the nicklists for channels at th...
Is there any methods in C standard libraries making the same thing with union() or difference() methods in Python? I have googled some, but find nothing. Any help will be appreciated. Thanks.
The C standard libraries do not implement set operators (as stated in response tothis prior SO question).This prior SO questionsuggestspblsetas an alternative, and I'm sure there are others, but that's not a direct answer to your question (the direct answer is "no").This SO questionaddresses array comparisons using a ...
First of all, is it possible to do that? If yes what am i doing wrong in the below declaration? ``` struct mybitfields { uint8_t a : 4; uint16_t c : 12; } test; ```
Although what you are doing ispossible, it is notportable: C99 standard says that bit-field base type must be a_Bool,signed int, orunsigned int, allowing implementation-defined types to be used with bit-fields (C90 requires a signed on an unsignedintas bit-field's base type; no other types are allowed). Seethis answe...
hey I would like to open and read a file using system calls and print the data in it letter by letter I have the function system_call in an assembly file and I want to "save" to pointer to the file descriptor from the system_call(SYS_OPEN to use it. the purpose is not using #include directory my code is ``` system_...
That's a list of system calls (may be a but outdated, but will work for you)http://asm.sourceforge.net/syscall.html.You can check an implementation details and usage of system_call in appropriate linux kernel sources for sys_open, sys_read, sys_write etc..
This question already has answers here:How to split a string to 2 strings in C(8 answers)Closed10 years ago. this might be some basic question, but I really can't find an answer: I need to split a string that has two numbers, into two strings in C. Example: 1->2 into 1 and 2 I'm using strtok, but it takes a series...
Use 'sscanf()'. Don't ask someone to do it for you as it's too easy if you give a few minutes to understand it, especially its format specifier string nuances.Here's a link that would suffice : http://www.cplusplus.com/reference/cstdio/sscanf/ Hint :sscanf (source_string,"%d->%d",&num1,&num2);
I know that Java has a functionSystem.arraycopy();to copy an array. I was wondering if there is a function in C or C++ to copy an array. I was only able to find implementations to copy an array by usingforloops, pointers, etc. But is there a library function that I can use to copy an array?
Since you asked for a C++ solution... ``` #include <algorithm> #include <iterator> const int arr_size = 10; some_type src[arr_size]; // ... some_type dest[arr_size]; std::copy(std::begin(src), std::end(src), std::begin(dest)); ```
I use Qt-Creator 2.5.2 SDK to develop C code on Linux. How is it possible to run the codes as root when it is run from the SDK interface (e.g., ctrl + R)?
Most simple solution to run Qt-Creator as root Honestly thats not a trivial task (as long as I tried to do it myself while ago). Are you sure you really need to run debug under root? If it's about access to some device nodes, may be it's easier to adjust rights on them? Another solution (keeping QT creator running u...
I run the code below, ``` int main() { char settime_parameters[13]= "042122142013"; char command[25]; sprintf(command, "date %s", settime_parameters ); printf("%s\n",command); system("commad"); } ``` and I get this output: ``` date 042122142013 sh: 1: commad: not found ``` however, if I rundate 042122142...
You need this: ``` system(command); ``` without the quotes.
Is there any alternative to usingfstat()function if you just need is the file size and creation date?I know we can useftell()to get the file size but I want the creation time and date too. The reason I dont want to usefstat()is that it takes a lot of time if the file list is long.
If the file is open, usefstatif you just have the file name and don't care about opening the file, usestat. It's as fast as it can get. Whatever other function you'd use will usestatorfstatinternally or at least their equivalents inside the kernel. Those system calls need to read in the metadata from the filesystem an...
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. Doesmemcpyadjust the pointer to the...
no, memcpy blindly copies x bytes from source to destination. See for instance:http://man7.org/linux/man-pages/man3/memcpy.3.html
I have a code which finds contours in the image. This works fine and the contours found are stored and CvPoints are used to draw lines around the contours. Now I want to set the ROI for the image and I don't know how to refer to the X/Y points of the CvPoint to use. The points pt all have defined values. ``` CvPoint...
The error in your case can be explained by the fact that*has lower priority than.Thus you are trying todereference the integer. That causes the issue. Thus you should use: ``` pt[0]->x; ``` or ``` *(pt[0]).x; ```
Is there a way to let the C18 compiler throw an own, customized error message during compiling? For example, consider a situation with two user-defined settings: ``` #define SETTING_A 0x80 #define SETTING_B 0x3f ``` Assume these settings can't beboth0x00. Is there a way to let the compiler throw an error (or at lea...
Consider using#ifand#error: ``` #if (SETTING_A == 0) && (SETTING_B == 0) #error SETTING_A and SETTING_B can't both be 0! #endif ```
Hey guys so I have acharand I want to add some integer/double to it. The char must be a signed char, so I can't just make it an int. ``` char var = -55; printf("Char is %d, add, char is now: %d\n", var, var+2); ``` That code works, but as soon as I want to add a fraction or something... ``` printf("Char is %d, add,...
Try this ``` printf("Char is %d, add, char is now: %d\n", var, (int)(var+2/3.0*2)); ```
I'm trying to program a simple "typewriter" effect in C, where text appears one letter at a time with a delay. Here's the function I have: ``` #include <stdio.h> #include <unistd.h> void typestring(const char *str, useconds_t delay) { while (*str) { putchar(*(str++)); usleep(delay); } } ``` ...
The output tostdoutis buffered. Using\nyou are forcing a flush. If you want to change this, you will need to change the settings of the terminal (for Linux lookhere) or use ``` void typestring(const char *str, useconds_t delay) { while (*str) { putchar(*(str++)); fflush(stdout); usleep(del...
hey I would like to open and read a file using system calls and print the data in it letter by letter I have the function system_call in an assembly file and I want to "save" to pointer to the file descriptor from the system_call(SYS_OPEN to use it. the purpose is not using #include directory my code is ``` system_...
That's a list of system calls (may be a but outdated, but will work for you)http://asm.sourceforge.net/syscall.html.You can check an implementation details and usage of system_call in appropriate linux kernel sources for sys_open, sys_read, sys_write etc..
This question already has answers here:How to split a string to 2 strings in C(8 answers)Closed10 years ago. this might be some basic question, but I really can't find an answer: I need to split a string that has two numbers, into two strings in C. Example: 1->2 into 1 and 2 I'm using strtok, but it takes a series...
Use 'sscanf()'. Don't ask someone to do it for you as it's too easy if you give a few minutes to understand it, especially its format specifier string nuances.Here's a link that would suffice : http://www.cplusplus.com/reference/cstdio/sscanf/ Hint :sscanf (source_string,"%d->%d",&num1,&num2);
I know that Java has a functionSystem.arraycopy();to copy an array. I was wondering if there is a function in C or C++ to copy an array. I was only able to find implementations to copy an array by usingforloops, pointers, etc. But is there a library function that I can use to copy an array?
Since you asked for a C++ solution... ``` #include <algorithm> #include <iterator> const int arr_size = 10; some_type src[arr_size]; // ... some_type dest[arr_size]; std::copy(std::begin(src), std::end(src), std::begin(dest)); ```
I use Qt-Creator 2.5.2 SDK to develop C code on Linux. How is it possible to run the codes as root when it is run from the SDK interface (e.g., ctrl + R)?
Most simple solution to run Qt-Creator as root Honestly thats not a trivial task (as long as I tried to do it myself while ago). Are you sure you really need to run debug under root? If it's about access to some device nodes, may be it's easier to adjust rights on them? Another solution (keeping QT creator running u...
I run the code below, ``` int main() { char settime_parameters[13]= "042122142013"; char command[25]; sprintf(command, "date %s", settime_parameters ); printf("%s\n",command); system("commad"); } ``` and I get this output: ``` date 042122142013 sh: 1: commad: not found ``` however, if I rundate 042122142...
You need this: ``` system(command); ``` without the quotes.
I have these 2 structs : ``` typedef struct { char name[20]; int num; int score; } player; typedef struct { char name[20]; player *players; } team; ``` I need to know the amount of elements stored per every*playersinside myteamstruct. Thanks!
You can't.playersis a pointer to Nplayerinstances. It carries no more information than an address. It is not an array; it is a pointer. You will have to store the number of elements in the struct separately. ``` typedef struct { char name[20]; player *players; size_t num_players; } team; ``` On a side...
I can't find out why crt0.o or crt1.o are not provided for i386 targets by newlib as it is the case for powerpc, arm, etc. targets. ld requires it (and so do I to call static constructors).
Question directly asked on newlib's mailing list:http://sourceware-org.1504.n7.nabble.com/Question-i386-s-crt0-tp229290p229999.html
I have been reading about accessing Memory Mapped Registers of peripheral devices and it seems you can do multiple ways. For example: Method 1: ``` #define MyReg 0x30610000 volatile int *ptrMyReg; ptrMyReg = (volatile int *) MyReg; *ptrMyReg = 0x7FFFFFFF; /* Turn ON all bits */ ``` Method 2: ``` #define MyReg 0x...
*ptrMyReg = 0x7FFFFFFF; In the second case,*ptrMyRegis of typeunsigned charso0x7FFFFFFFwill be converted tounsigned char(i.e., value after conversion will be0xFF) before assignment and only one byte will be written. I don't think this what you want if you originally intended to write 4 bytes.
The usual form of function pointer definitions is: ``` int function(int, int); int (*ptr)(int, int); ``` but I saw a form today which I didn't understand. Can anyone explain this please? ``` int (*close) __P((struct __db *)); ```
The__P()macro is usually used to support C implementations from the days of K&R C, when there were no prototypes (which were introduced to C with C89). Basically the logic is ``` #if SOME_LOGIC_TO_TEST_WHETHER_IMPLEMENTATION_SUPPORTS_PROTOTYPES # define __P(argument_list) argument_list #else # define __P(argument_l...
``` #include <stdio.h> main() { unsigned a = -20; unsigned b = 10; printf("%d\n", (a % b)); printf("%d\n", (-20 % 10)); } Output: 6 0 ``` The second printf prints the expected value of 0 while the first printf prints 6. Why this unexpected output with unsigned ints?
unsigned intcan hold values from 0 toUINT_MAX, no negative values. So-20is converted to-20 + UINT_MAX + 1. On your system: ``` (-20 + UINT_MAX + 1) % 10 != -20 % 10 ```
``` Display *display; display = XOpenDisplay(NULL); Window window; XGetInputFocus(display, &window, RevertToNone); ``` in XGetInputFocus segmentation fault happen; anything wrong ? (program compile with xlib and don't any problem with compiling)
int revert; XGetInputFocus(display, &window, &revert);should fix it.
Basically what I want to achieve is to share a dynamically allocated array of state flags among different threads to control the interactions between threads. Are there any library that can achieve this flawlessly in Windows OS? I tried Open MP, and it gives me all kinds of weird bugs and lots headache, even with om...
Threads of the same process share the same heap, so memory allocated on this heap can be shared between those threads. All the program needs to asure is protecting such "shared" memory against concurrent access. The latter can be achieved by using locks, like mutexes.
I'm trying to format my string, becouse i have two strings one that contain: "1" and the second that contain: "test" and want to output the whole string with space as: 1 test i did that by saying: ``` printf("%-10s %s", "1", "test"); ``` but how do i change the space " %-10s " without changing the format? ``...
``` printf("%-*s %s", amount_of_space, "1", "test" ) ; ``` The * comes first in the format string - hence the parameteramount_of_spacehas to come first after the comma. i.e in the format string the order is *, s & s - so after the comma, you need whatever fills in for *, the first string and then the 2nd string.
I am using the SLRE (http://slre.sourceforge.net/) for doing REGEX checking in a C program. I am including the headerfile and then I do following: ``` void checkRegex() { struct slre slre; struct cap captures[4+1]; if(!slre_compile(&slre, "regularexpression") { printf("error"); } } ``` I am ...
I looked at the library and it consists of slre.c and slre.h so you probably compile it like ``` gcc slre.c -o slre.o -c gcc example1.c slre.o -o test.cgi -L -lconfig ```
I have a shell program where a fork is created and then used two if else statements to separate the parent and the child process. My sample program is here and i got a few questions ``` while(true) { /* read command line input */ x = fork(); if( x > 0) { wait(&status); } ...
This should give you a better idea of how the fork() system call works.
Is it possible to copy the output of a command used onsystem()function on Linux? E.g., If I run ``` #include <stdlib.h> int main(int argc,char *argv[]){ char date[8]; //e.g., 20130421 yyyymmdd char time[4]; // e.g., 0204 hhmm system("ntpdate"); return 0; } ``` it outputs: 21 Apr 02:12:56 ntpdate[32...
systemdoes not allow such a thing, you have to usepopen("ntpdate", "r"), which returns aFILE *from which you can read the command output.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I have a task of searching for opco...
You may take a look atROPGadgetor atrp, both software contain code that do what you want (and more).
I want to treatWM_PAINTmessage. But at first, I want to let system to do the default drawing, then I draw something else manually. For example: ``` case WM_PAINT: CallWindowProc(DefWndProcTabControl, hwnd, message, wParam, lParam); TabControlOnPaint(hwnd); return 0; ``` This works, but is n...
If the window you're painting supports it, useWM_PRINTorWM_PRINTCLIENTto do the default painting into a memory DC. (Trying to do that viaCallWindowProcis unlikely to work.)
The usual form of function pointer definitions is: ``` int function(int, int); int (*ptr)(int, int); ``` but I saw a form today which I didn't understand. Can anyone explain this please? ``` int (*close) __P((struct __db *)); ```
The__P()macro is usually used to support C implementations from the days of K&R C, when there were no prototypes (which were introduced to C with C89). Basically the logic is ``` #if SOME_LOGIC_TO_TEST_WHETHER_IMPLEMENTATION_SUPPORTS_PROTOTYPES # define __P(argument_list) argument_list #else # define __P(argument_l...
``` #include <stdio.h> main() { unsigned a = -20; unsigned b = 10; printf("%d\n", (a % b)); printf("%d\n", (-20 % 10)); } Output: 6 0 ``` The second printf prints the expected value of 0 while the first printf prints 6. Why this unexpected output with unsigned ints?
unsigned intcan hold values from 0 toUINT_MAX, no negative values. So-20is converted to-20 + UINT_MAX + 1. On your system: ``` (-20 + UINT_MAX + 1) % 10 != -20 % 10 ```
``` Display *display; display = XOpenDisplay(NULL); Window window; XGetInputFocus(display, &window, RevertToNone); ``` in XGetInputFocus segmentation fault happen; anything wrong ? (program compile with xlib and don't any problem with compiling)
int revert; XGetInputFocus(display, &window, &revert);should fix it.
Basically what I want to achieve is to share a dynamically allocated array of state flags among different threads to control the interactions between threads. Are there any library that can achieve this flawlessly in Windows OS? I tried Open MP, and it gives me all kinds of weird bugs and lots headache, even with om...
Threads of the same process share the same heap, so memory allocated on this heap can be shared between those threads. All the program needs to asure is protecting such "shared" memory against concurrent access. The latter can be achieved by using locks, like mutexes.
I'm trying to format my string, becouse i have two strings one that contain: "1" and the second that contain: "test" and want to output the whole string with space as: 1 test i did that by saying: ``` printf("%-10s %s", "1", "test"); ``` but how do i change the space " %-10s " without changing the format? ``...
``` printf("%-*s %s", amount_of_space, "1", "test" ) ; ``` The * comes first in the format string - hence the parameteramount_of_spacehas to come first after the comma. i.e in the format string the order is *, s & s - so after the comma, you need whatever fills in for *, the first string and then the 2nd string.
I am using the SLRE (http://slre.sourceforge.net/) for doing REGEX checking in a C program. I am including the headerfile and then I do following: ``` void checkRegex() { struct slre slre; struct cap captures[4+1]; if(!slre_compile(&slre, "regularexpression") { printf("error"); } } ``` I am ...
I looked at the library and it consists of slre.c and slre.h so you probably compile it like ``` gcc slre.c -o slre.o -c gcc example1.c slre.o -o test.cgi -L -lconfig ```
I have a shell program where a fork is created and then used two if else statements to separate the parent and the child process. My sample program is here and i got a few questions ``` while(true) { /* read command line input */ x = fork(); if( x > 0) { wait(&status); } ...
This should give you a better idea of how the fork() system call works.
When an error occurs, I would like my C code to store the error before exiting the program. Is it advised to store thestderrto a file (e.g., /home/logs.txt) or would it be advised to use a different method to keep the logs/error report (considering the programming environment isLinux). E.g., for the code below, how I ...
Ifstderris always used to print out all your error message, so, you can redirect output to a specific file. ``` $ program 2>~/logs.txt ``` For a better logging tool, you can use: syslogstandard function.log4clibrary.
I write a simple program When you run this program, if you are notrootuser, inputrootpassword, then change uid to root ``` if (getuid()) { char *pass = getpass(""); //how to change uid to root ? } ``` How to change uid to root when you gotrootpassword?
There is no way to change from a non-root user to root. That's the whole point. Programs likelogin,sshd, orsuwork by initiallystarting as root, either because of their ancestry or by having the suid bit on the executable file, and carefully restricting what you can do until you authenticate with a password or other me...
I am new to C/C++, but was curious to know about the issue i am seeing. ``` typedef union { int a; float c; char b[20]; } Union; int main() { Union y = {100}; printf("Union y :%d - %s - %f \n",y.a,y.b,y.c); } ``` And output is ``` Union y :100 - d - 0.000000 ``` My question is ...why is 'd' getting pri...
The ASCII code for'd'is 100. Settingato 100 amounts to settingbto{'d', '\0', '\0', '\0', …noise…}(on a 32-bit little-endian machine), whichprintftreats as"d".
This question already has answers here:What's the behavior of an uninitialized variable used as its own initializer?(3 answers)Closed4 years ago. I finally trace down a typo bug, which is something similar to the following code. But shouldn't the compiler detect this (by default options)? ``` #include <stdio.h> int...
I don't see why it wouldn't compile. Definition happens prior to initialization. Of course this initialization is pointless, however, there's no reason it wouldn't work from the compilers stand point. C does not have the same types of protections that more modern languages like C# have. The C# compiler would give an ...
Sorry for the title. Feel free to edit it to anything more clear. I have a string and I have to check that the first char of this string is equal to at least one between other given char, for example B, Z and K (in my case I've about 10 char to check and they are not classifiable as a range). I'm doing the check as ...
One possible approach would be to list your target chars in a string and usestrchr ``` const char* matches = "ZKB..."; if (strchr(matches, string[0]) != NULL) { /* do something */ } ```
I am getting some errors. Any clues where I am going wrong? I think I am applying the right logic. ``` int* adderFunction(int a, int b) { int result; int *pResult; pResult = &result; result = a + b; return (pResult); } ```
No. You are trying to return pointer on local variable, which is destructed after return from function.
I have two variables(which are actually elements of two different matrices). For example i want to multiply ``` a[i][k]*b[k][j] ``` using bit manipulation, how can i do that. I saw references to multiply constants, not variables like 3*2, 3*4, 3*8, etc. But how can i apply same techniques to multiplying variables? ...
Given two integral variables ``` unsigned X, Y; ``` And given a Commodore 64, Apple ][, or some other architecture that doesn't have its own multiply instruction, this will multiply the numbers. ``` unsigned answer = 0; while ( X ) { answer <<= 1; if ( X & 1 ) answer += Y; X >>= 1; } ```
This question already has answers here:zero length arrays [duplicate](3 answers)Closed10 years ago. I tried declaring an arrayaof size 0: ``` int a[0]; ``` My VC++ 6 compiler throws an error of not being able to create an array of zero size. If I try the same of declaring inside a structure, I do not get any error...
The struct is a special case. It is a common pattern to declare an empty array as the last member of a struct, where the struct is actually part of a larger block of memory of variable length. SeeEmpty arrays in structsfor more explanation.
By definition, in C, a string is an array of characters ``` int main() { char *name="David Bolton"; printf("My name is %s\r\n",name) ; return 0; } ``` The linechar * name="David Bolton";defines name as a pointer to the first character in the string i.e 'D' .So ,the pointer name should hold address but it print...
Because you use%s, C will know that you want to print a string, so, it will print character by character to screen, until it meets symbol\0.
What are the equivalent for java byte in C,C++ ``` byte[] itemsArray; itemsArray = new byte[items *no]; itemsArray[x] = (byte) xyz; unsigned char * itemsArray; itemsArray = (unsigned char*) malloc (items*no); ``` How to assign bytes toitemsArray(likeitemsArray[x] = (byte) xyz) in C++ with endianess to ensure the p...
Usememcpy()to copy buffers between memories inC.
How to ask gcc to reset an asm inline input value?%0in the following example is not reset to42after the first loop. So when i = 1,%0value is still0. ``` for (int i = 0; i < N; ++i) asm("label: substract_immediate_value %0,%0,1;" "compare_immediate_value %0,0;" "branch_not_equal label" : /* no outp...
I've not tried this, but it looks right: ``` for (int i = 0; i < N; ++i) { int n = 42; asm("label: substract_immediate_value %0,%0,1;" "compare_immediate_value %0,0;" "branch_not_equal label" : "+r" (n)); } ``` I presume this is a simplified example, because I can't imagine why y...
I have a table that I'm implementing with data structures. An important block of my code looks like this(h is a data structure, table is a table that stores other structures): ``` (h->table[hash(key, h->size)] ``` While my code is running, some table[i]'s will be initialized, and some aren't. Whenever I test my code...
You can't. To fix the problem, always initialize the struct before using it (even if all the initialization does is set the struct to a known "blank"/"not populated" state).
I'm creating a CvMat structure by calling ``` cvCreateMat(1,1,CV_32FC3); ``` This structure is filled by a subsequent OpenCV function call and fills it with three values (as far as I understand it, this is a 1x1 array with an additional depth of 3). So how can I access these three values? A normal call to ``` CV_M...
The general way to access a cv::Mat is ``` type value=myMat.at<cv::VecNT>(j,i)[channel] ``` For your case: ``` Mat mymat(1,1,CV_32FC3,cvScalar(0.1,0.2,0.3)); float val=mymat.at<Vec3f>(0,0)[0]; ``` All of the types are defined using the class cv::VecNT where T is the type and N is the number of vector elements.
EDIT: These structure definitions were given to me and cannot be altered in any way. Let's say instruct DBI would like to access the name of 3rd element in db. How would I go about that? I would think I would be able to do this: ``` DB->db[2].name; ``` but that doesn't work. Also, how would I define one of these s...
First you have to create object for structDB. Then you can access it's members. ``` DB obj; strcpy(obj.db[2].name, "abc"); ```
In theClanguage, why use the following line to define a constant with all bits set to 1?: ``` #define EXTENDED_MEM_END ((unsigned) -1) ``` Instead of using the following?: ``` #define EXTENDED_MEM_END 0xFFFFFFFF ``` Or just this?: ``` #define EXTENDED_MEM_END -1 ``` Does it have something to do with por...
``` #define EXTENDED_MEM_END 0xFFFFFFFF ``` isn't right if ints aren't 32 bits; ``` #define EXTENDED_MEM_END -1 ``` isn't unsigned.
I'm trying to determine the runtime of a function in C usingclock(). This is the code so far: ``` time_t start, end; start = clock(); // Function here end = clock(); printf("Time was: %lf\n", ((double)(end-start)/CLOCKS_PER_SEC)); ``` And it returnsTime was: 0.030000. If I add a delay of a few seconds it then displa...
To display time in milliseconds, multiply the time in seconds by1000: ``` printf("Time was: %d\n", (1000*(end-start)/CLOCKS_PER_SEC)); ``` The above code truncates the time to the smallest millisecond.
For example, suppose I want to copy thing the string "str1" to a new string, "str2": ``` void function(const char* str1){ char* str2; str2 = (char *) malloc(sizeof(char) * (strlen(str1) + 1)); strcpy(str2, str1); ... } ``` Should the argument to malloc be: ``` sizeof(char) * (strlen(str1)+1) ``` or...
Yes, you need to +1 —strlenreturns the string length; to store a string you need storage for its length plus an extra spot for theNULLterminator. That being said, in this specific example (which I'm sure is just that: an example to make the point), you can just usestrdup.
I have a table that I'm implementing with data structures. An important block of my code looks like this(h is a data structure, table is a table that stores other structures): ``` (h->table[hash(key, h->size)] ``` While my code is running, some table[i]'s will be initialized, and some aren't. Whenever I test my code...
You can't. To fix the problem, always initialize the struct before using it (even if all the initialization does is set the struct to a known "blank"/"not populated" state).
I'm creating a CvMat structure by calling ``` cvCreateMat(1,1,CV_32FC3); ``` This structure is filled by a subsequent OpenCV function call and fills it with three values (as far as I understand it, this is a 1x1 array with an additional depth of 3). So how can I access these three values? A normal call to ``` CV_M...
The general way to access a cv::Mat is ``` type value=myMat.at<cv::VecNT>(j,i)[channel] ``` For your case: ``` Mat mymat(1,1,CV_32FC3,cvScalar(0.1,0.2,0.3)); float val=mymat.at<Vec3f>(0,0)[0]; ``` All of the types are defined using the class cv::VecNT where T is the type and N is the number of vector elements.
EDIT: These structure definitions were given to me and cannot be altered in any way. Let's say instruct DBI would like to access the name of 3rd element in db. How would I go about that? I would think I would be able to do this: ``` DB->db[2].name; ``` but that doesn't work. Also, how would I define one of these s...
First you have to create object for structDB. Then you can access it's members. ``` DB obj; strcpy(obj.db[2].name, "abc"); ```
In theClanguage, why use the following line to define a constant with all bits set to 1?: ``` #define EXTENDED_MEM_END ((unsigned) -1) ``` Instead of using the following?: ``` #define EXTENDED_MEM_END 0xFFFFFFFF ``` Or just this?: ``` #define EXTENDED_MEM_END -1 ``` Does it have something to do with por...
``` #define EXTENDED_MEM_END 0xFFFFFFFF ``` isn't right if ints aren't 32 bits; ``` #define EXTENDED_MEM_END -1 ``` isn't unsigned.
I'm trying to determine the runtime of a function in C usingclock(). This is the code so far: ``` time_t start, end; start = clock(); // Function here end = clock(); printf("Time was: %lf\n", ((double)(end-start)/CLOCKS_PER_SEC)); ``` And it returnsTime was: 0.030000. If I add a delay of a few seconds it then displa...
To display time in milliseconds, multiply the time in seconds by1000: ``` printf("Time was: %d\n", (1000*(end-start)/CLOCKS_PER_SEC)); ``` The above code truncates the time to the smallest millisecond.
For example, suppose I want to copy thing the string "str1" to a new string, "str2": ``` void function(const char* str1){ char* str2; str2 = (char *) malloc(sizeof(char) * (strlen(str1) + 1)); strcpy(str2, str1); ... } ``` Should the argument to malloc be: ``` sizeof(char) * (strlen(str1)+1) ``` or...
Yes, you need to +1 —strlenreturns the string length; to store a string you need storage for its length plus an extra spot for theNULLterminator. That being said, in this specific example (which I'm sure is just that: an example to make the point), you can just usestrdup.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. I want to write some code with the ...
For me, it's the third one. Since the condition is simpler to evaluate.
Is there any difference on how the compiler will generate the code for the following two. Secondly, will they produce the same return values. ``` static inline float fix2float(int64_t f) { return (float)f / ((int64_t)1 << 60); } ``` and this ``` static inline float fix2float(int64_t f) { return (floa...
These two functions are very different: the second one performs integer division, while the first one does floating-point. In particular, the return value of the second version is always going to be an integer in the range [-8, 7]. Update:Of course this is only true if you first correctthe typo that unwind caught.
I am confused about the process switching between two processes. When a new process is created using fork, what are the general rules applicable for switching between processes. Is it only when one processes goes to idle state? I have few doubts What will happen when parent and child in both infinite loop and having ...
Mostpreemptiveschedulers will, highly simplified, allocate a certain maximum time to each process. When that time expires (for instance 10 ms), it will re-schedule so that other processes get some CPU. If the timerdoesn'texpire before the process hits some other wait condition (such as doing I/O), it will re-schedul...
I want to have an array ofk2-element arrays of ints. My code: ``` int **pipe_fd_ptr; pipe_fd_ptr = malloc(k*sizeof(int*)); for(i = 0; i < k; i++) { pipe_fd_ptr = malloc(2*sizeof(int)); } // this is just for testing for(i = 0; i<k; i++) { for(j=0;j<2;j++) pipe_fd_ptr[i][j] =j; } ``` I get segfault. W...
Should be ``` for(i = 0; i < k; i++) { pipe_fd_ptr[ i ] = malloc(2*sizeof(int)); } ``` Withpipe_fd_ptr = malloc(k*sizeof(int*));you allocated space for k pointers to int then you iterate trough the array and allocate memory for each pointer withpipe_fd_ptr[ i ] = malloc(2*sizeof(int));
In C programming language why do we need a special sem_t type for defining the semaphore? Couldn't that been an integer?How is sem_t defined? How is the functions sem_post and sem_wait implemented? EDIT:An example implementation like GNU C library will be great.
Semaphores are OS kernel managed objects, so sem_t will be OS-specific, as will be the signal/wait calls since they also necessarily call into the OS kernel. Usually, the semaphores are implemented by a unit count and a queue for any waiting threads.
I have a string with the following format: ``` start 123 ``` I am parsing it that way: ``` if (strstr(line, "start") == line) { int number = -1; if (sscanf(line + strlen("start "), "%d", &number) == 1) { printf("start %d\n", number); } } ``` Is there any better way in C?
yes you can use only this: ``` if (sscanf(line, "start %d", &number ) == 1) { ``` no need for ``` if (strstr(line, "start") == line) { ``` any more If you want to check more: Check that there is no extra characters after the number , then you can use the following format: ``` char c; if (sscanf(line, "start %d%c...
I have a struct variable ``` struct Var var; ``` and a function which is from a library ``` void func(struct Var ** ){} ``` now I want to call this function can I use ``` func(&&var); ``` if so, is there anything to be cautious? if not, any solutions? thanks!
A function with an argument of typeT**is probably going to be reassigning the pointer to a different value. This means that the address of aT*must be passed in: ``` struct Var* var; func(&var); void func(struct Var ** a_var) { *a_var = malloc(sizeof(struct Var)); } ```
I am trying to disable sse and sse2 instructions. I am cross compiling for x86 in a x64 system. I am also using -static to statically link with libc. Although I use -mno-sse and -mno-sse2, when I disassemble the binary I still see a call to strcpy_sse2, any solution?
For 64 bit Use -mno-sse gcc option
I'm using zlib to write a program that compress data in several threads. so I can't use gzwrite. I'm using compress2(). ``` *dest_len = compressBound(LOG_BUFF_SZ); err = compress2((Bytef*)compressed_buff->buff, dest_len, (Bytef*)b->buff, size, GZ_INT_COMPRESSION_LEVEL); write(fd, compressed_buff->buff, compressed_buf...
compress()andcompress2()compress to thezlib format, not thegzip format. You need to use the lower-level functions to be able to select the gzip format. Those aredeflateInit2(),deflate()anddeflateEnd(). Read the documentation inzlib.hfor those functions. After that, you should also look at theheavily documented exa...
I have a string with the following format: ``` start 123 ``` I am parsing it that way: ``` if (strstr(line, "start") == line) { int number = -1; if (sscanf(line + strlen("start "), "%d", &number) == 1) { printf("start %d\n", number); } } ``` Is there any better way in C?
yes you can use only this: ``` if (sscanf(line, "start %d", &number ) == 1) { ``` no need for ``` if (strstr(line, "start") == line) { ``` any more If you want to check more: Check that there is no extra characters after the number , then you can use the following format: ``` char c; if (sscanf(line, "start %d%c...
I have a struct variable ``` struct Var var; ``` and a function which is from a library ``` void func(struct Var ** ){} ``` now I want to call this function can I use ``` func(&&var); ``` if so, is there anything to be cautious? if not, any solutions? thanks!
A function with an argument of typeT**is probably going to be reassigning the pointer to a different value. This means that the address of aT*must be passed in: ``` struct Var* var; func(&var); void func(struct Var ** a_var) { *a_var = malloc(sizeof(struct Var)); } ```
I am trying to disable sse and sse2 instructions. I am cross compiling for x86 in a x64 system. I am also using -static to statically link with libc. Although I use -mno-sse and -mno-sse2, when I disassemble the binary I still see a call to strcpy_sse2, any solution?
For 64 bit Use -mno-sse gcc option
I'm using zlib to write a program that compress data in several threads. so I can't use gzwrite. I'm using compress2(). ``` *dest_len = compressBound(LOG_BUFF_SZ); err = compress2((Bytef*)compressed_buff->buff, dest_len, (Bytef*)b->buff, size, GZ_INT_COMPRESSION_LEVEL); write(fd, compressed_buff->buff, compressed_buf...
compress()andcompress2()compress to thezlib format, not thegzip format. You need to use the lower-level functions to be able to select the gzip format. Those aredeflateInit2(),deflate()anddeflateEnd(). Read the documentation inzlib.hfor those functions. After that, you should also look at theheavily documented exa...