question
stringlengths
25
894
answer
stringlengths
4
863
I am programming in C against a third party library (in HP/Mercury Loadrunner). I am trying to work out the code needed to dynamically call another function. See example below. Can someone assist with the code that will make this work? ``` HomePage() { // Load Runner code to conduct home page call } SearchResults...
if you are looking for pointer to functions: ``` FunctionCall(void(*function)(void)) { function(); } Main() { FunctionCall(HomePage); FunctionCall(SearchResults); } ```
``` char buf[BUF_LEN]_attribute_((aligned(4))); ssize_t len, i = 0; /* read BUF_LEN bytes' worth of events */ len = read (fd, buf, BUF_LEN); /* loop over every read event until none remain */ while (i < len) { struct inotify_event *event = (struct inotify_event *) &buf[i]; Monitoring File Events | 239 printf ("wd=%d m...
``` char buf[BUF_LEN]_attribute_((aligned(4))); ``` It specifies a minimum alignment for the variablebuf, measured in bytes.It causes the compiler to allocate the variablebufon a 4-byte boundary. Thisshould be a good read.
I need to shift an unsigned int to the right more than 32 times and still get a proper answer of zero instead of the random or original number. E.g 8 >> 40 should = 0 but it returns a random number. I understand a loop that shifts one place right at a time would solve this problem as it would fill in zeros as it went...
You want to usea >>= 1;ora = a >> 1;this is becausea >> 1shifts a to the right once and returns the result. It doesn't assign the result toa
Does anyone know how to apply this in specifically in NetBeans IDE? I have tried to include -lgtk+-2.0 or same line as additional option but always it shows gcc: error: gtk+-2.0: No such file or directory If i do like this manually it works. But i want to apply it in IDE way: ``` gcc $(pkg-config --cflags --libs gt...
In Project Properties -> Build -> C Compiler, you can set as 'Additional Options' ``` $$(pkg-config --cflags --libs gtk+-2.0 more) ``` note the double-$, otherwise NetBeans will treat it like one of its own parameters. It seems like you'd still need to include the additional include directory (e.g. /usr/include/gtk...
Is there a way to traverse character by character or extract a single character from char* in C? Consider the following code. Now which is the best way to get individual characters? Suggest me a method without using any string functions. ``` char *a = "STRING"; ```
Another way: ``` char * i; for (i=a; *i; i++) { // i points successively to a[0], a[1], ... until a '\0' is observed. } ```
``` void dispatch_for(dispatch_queue_t *queue, long number, void (* work)(long)){ int loop = number; int i; task_t *ctask; for(i = 0; i<loop;i++){ ctask = create_task((void *)work,number,"for_test"); dispatch_async(queue,ctask); } } task_t *task_create(void (* work)(void *), vo...
name of the function without the parentheses is the pointer to that function : ``` void work(void) { ...; } void main(void) { task_create(work, void, void); } ```
When I try to compile a function with return typeboolin GCC compiler, the compiler throws me this error. ``` error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘comp’ ``` But when I change the return type toint, it is getting compiled successfully. The function is as below. ``` bool comp(struct node *n...
booldoes not exist as a keyword pre-C99. In C99, it should work, but as @pmg points out below, it's still not a keyword. It's a macro declared in<stdbool.h>.
This question already has answers here:Closed12 years ago. Possible Duplicate:Complex Declarations Can someone help me to break this down, and help me to understand? ``` 1) char *(*(*a[N])( ))( ); 2) char (* (*x[3]) ( ))[5]; 3) char (*(*f( ))[ ]) ( ); ```
The golden rule is. just usehttp://cdecl.org/: declare a as array 5 of pointer to function returning pointer to function returning pointer to char(I replacedNwith5)declare x as array 3 of pointer to function returning pointer to array 5 of chardeclare f as function returning pointer to array of pointer to function re...
I have a program(A) and there is anather executable file(B) in the same folder. I must call function from this anther program(B) in my program(A). And all this must be done in dos. How can i do it or what i should read to do this? Please help.
If your two programs are separate executables files then will most likely run in two different processes, You cannot just call functions accross two different processes, you need to use someInter Process communicationmechansim. You need to start understanding the basics & make a start somewhere andthisseems to be a g...
I what to know that what is the base on which the size of any datatype is decided. For eg. size of intger datatype in java is 4 bytes. So why its exactly 4 and not anything else. More over maximum number that can be stored with int type is 2,147,483,648. When this number come from? I mean what is the formula to get th...
Because 4 bytes is 4*8 = 32 bits. 2^32 = 4294967296 For unsigned int that is the max number, for signed int it's 2^32/2, which is your number. The number of bytes on which a datatype is represented is decided by the architecture. For C++, only sizeof(char) is guaranteed to be 1.
I am trying to get cs (current segment) register value by using c language. I tried it bay assembler by this code: ``` __asm__("movw %%eax, %%ecs;" : "=r" ( cur_seg )); ``` but my project did not recognise __asm__. May be there is other way to this? Please help.
Your code is gcc-specifics, are you using gcc under dos? If not try to use __asm {}, _asm {} or asm {} syntax. See more athttp://msdn.microsoft.com/en-us/library/45yd4tzz(v=vs.80).aspx,http://www.daniweb.com/software-development/cpp/threads/4927,
I need to create a C program that will copy one folder content to another. The folder and destination will be provided by the user. I need it to be in C 'cause I'm gonna run it on terminal. Thanks in advance for any help.
You don't need to write it inCbecause it is going to run on a terminal.BASH(on Unix) orPowerShell(on Windows) are ideal tools for what you are trying to accomplish. If you absolutelymustwrite it onCthe answer would depend on whether you are allowed to run external processes within yourCprogram or not. If youareallow...
The following simple code ``` int generated; generated = (random() % 100) + 1; ``` gives a warning flag for loss of precision, 'long' to 'int', so I have been correcting it by rewriting the assignment code as ``` generated = ((int)random() % 100) + 1; ``` Is this a valid way of correcting the problem or am I just ...
You can also use long for your constants: ``` generated = (random() % 100L) + 1L; ``` Note that this assume that generated is long. EDIT:Since generated is an int, you just need to cast it after you are done: ``` generated = (int)((random() % 100L) + 1L); ```
Is there a way to traverse character by character or extract a single character from char* in C? Consider the following code. Now which is the best way to get individual characters? Suggest me a method without using any string functions. ``` char *a = "STRING"; ```
Another way: ``` char * i; for (i=a; *i; i++) { // i points successively to a[0], a[1], ... until a '\0' is observed. } ```
``` void dispatch_for(dispatch_queue_t *queue, long number, void (* work)(long)){ int loop = number; int i; task_t *ctask; for(i = 0; i<loop;i++){ ctask = create_task((void *)work,number,"for_test"); dispatch_async(queue,ctask); } } task_t *task_create(void (* work)(void *), vo...
name of the function without the parentheses is the pointer to that function : ``` void work(void) { ...; } void main(void) { task_create(work, void, void); } ```
When I try to compile a function with return typeboolin GCC compiler, the compiler throws me this error. ``` error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘comp’ ``` But when I change the return type toint, it is getting compiled successfully. The function is as below. ``` bool comp(struct node *n...
booldoes not exist as a keyword pre-C99. In C99, it should work, but as @pmg points out below, it's still not a keyword. It's a macro declared in<stdbool.h>.
This question already has answers here:Closed12 years ago. Possible Duplicate:Complex Declarations Can someone help me to break this down, and help me to understand? ``` 1) char *(*(*a[N])( ))( ); 2) char (* (*x[3]) ( ))[5]; 3) char (*(*f( ))[ ]) ( ); ```
The golden rule is. just usehttp://cdecl.org/: declare a as array 5 of pointer to function returning pointer to function returning pointer to char(I replacedNwith5)declare x as array 3 of pointer to function returning pointer to array 5 of chardeclare f as function returning pointer to array of pointer to function re...
I have a program(A) and there is anather executable file(B) in the same folder. I must call function from this anther program(B) in my program(A). And all this must be done in dos. How can i do it or what i should read to do this? Please help.
If your two programs are separate executables files then will most likely run in two different processes, You cannot just call functions accross two different processes, you need to use someInter Process communicationmechansim. You need to start understanding the basics & make a start somewhere andthisseems to be a g...
I what to know that what is the base on which the size of any datatype is decided. For eg. size of intger datatype in java is 4 bytes. So why its exactly 4 and not anything else. More over maximum number that can be stored with int type is 2,147,483,648. When this number come from? I mean what is the formula to get th...
Because 4 bytes is 4*8 = 32 bits. 2^32 = 4294967296 For unsigned int that is the max number, for signed int it's 2^32/2, which is your number. The number of bytes on which a datatype is represented is decided by the architecture. For C++, only sizeof(char) is guaranteed to be 1.
I am trying to get cs (current segment) register value by using c language. I tried it bay assembler by this code: ``` __asm__("movw %%eax, %%ecs;" : "=r" ( cur_seg )); ``` but my project did not recognise __asm__. May be there is other way to this? Please help.
Your code is gcc-specifics, are you using gcc under dos? If not try to use __asm {}, _asm {} or asm {} syntax. See more athttp://msdn.microsoft.com/en-us/library/45yd4tzz(v=vs.80).aspx,http://www.daniweb.com/software-development/cpp/threads/4927,
I need to create a C program that will copy one folder content to another. The folder and destination will be provided by the user. I need it to be in C 'cause I'm gonna run it on terminal. Thanks in advance for any help.
You don't need to write it inCbecause it is going to run on a terminal.BASH(on Unix) orPowerShell(on Windows) are ideal tools for what you are trying to accomplish. If you absolutelymustwrite it onCthe answer would depend on whether you are allowed to run external processes within yourCprogram or not. If youareallow...
Is there a way to traverse character by character or extract a single character from char* in C? Consider the following code. Now which is the best way to get individual characters? Suggest me a method without using any string functions. ``` char *a = "STRING"; ```
Another way: ``` char * i; for (i=a; *i; i++) { // i points successively to a[0], a[1], ... until a '\0' is observed. } ```
``` void dispatch_for(dispatch_queue_t *queue, long number, void (* work)(long)){ int loop = number; int i; task_t *ctask; for(i = 0; i<loop;i++){ ctask = create_task((void *)work,number,"for_test"); dispatch_async(queue,ctask); } } task_t *task_create(void (* work)(void *), vo...
name of the function without the parentheses is the pointer to that function : ``` void work(void) { ...; } void main(void) { task_create(work, void, void); } ```
When I try to compile a function with return typeboolin GCC compiler, the compiler throws me this error. ``` error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘comp’ ``` But when I change the return type toint, it is getting compiled successfully. The function is as below. ``` bool comp(struct node *n...
booldoes not exist as a keyword pre-C99. In C99, it should work, but as @pmg points out below, it's still not a keyword. It's a macro declared in<stdbool.h>.
This question already has answers here:Closed12 years ago. Possible Duplicate:Complex Declarations Can someone help me to break this down, and help me to understand? ``` 1) char *(*(*a[N])( ))( ); 2) char (* (*x[3]) ( ))[5]; 3) char (*(*f( ))[ ]) ( ); ```
The golden rule is. just usehttp://cdecl.org/: declare a as array 5 of pointer to function returning pointer to function returning pointer to char(I replacedNwith5)declare x as array 3 of pointer to function returning pointer to array 5 of chardeclare f as function returning pointer to array of pointer to function re...
I have a program(A) and there is anather executable file(B) in the same folder. I must call function from this anther program(B) in my program(A). And all this must be done in dos. How can i do it or what i should read to do this? Please help.
If your two programs are separate executables files then will most likely run in two different processes, You cannot just call functions accross two different processes, you need to use someInter Process communicationmechansim. You need to start understanding the basics & make a start somewhere andthisseems to be a g...
I what to know that what is the base on which the size of any datatype is decided. For eg. size of intger datatype in java is 4 bytes. So why its exactly 4 and not anything else. More over maximum number that can be stored with int type is 2,147,483,648. When this number come from? I mean what is the formula to get th...
Because 4 bytes is 4*8 = 32 bits. 2^32 = 4294967296 For unsigned int that is the max number, for signed int it's 2^32/2, which is your number. The number of bytes on which a datatype is represented is decided by the architecture. For C++, only sizeof(char) is guaranteed to be 1.
I am trying to get cs (current segment) register value by using c language. I tried it bay assembler by this code: ``` __asm__("movw %%eax, %%ecs;" : "=r" ( cur_seg )); ``` but my project did not recognise __asm__. May be there is other way to this? Please help.
Your code is gcc-specifics, are you using gcc under dos? If not try to use __asm {}, _asm {} or asm {} syntax. See more athttp://msdn.microsoft.com/en-us/library/45yd4tzz(v=vs.80).aspx,http://www.daniweb.com/software-development/cpp/threads/4927,
I need to create a C program that will copy one folder content to another. The folder and destination will be provided by the user. I need it to be in C 'cause I'm gonna run it on terminal. Thanks in advance for any help.
You don't need to write it inCbecause it is going to run on a terminal.BASH(on Unix) orPowerShell(on Windows) are ideal tools for what you are trying to accomplish. If you absolutelymustwrite it onCthe answer would depend on whether you are allowed to run external processes within yourCprogram or not. If youareallow...
Typically you have a server and client pair or two peers that connect to each other through a socket. This is a 1 to 1 relationship. Lets say you had 6 peers. Is there a way for them to be "grouped" together without a "server" so that 1 peer can send a udp/tcp message directly to another? I'm basically looking for a...
No easy way with TCP, but with UDP you havemulticast.
I'm not very strong in C, but I'm working with the NDK right now and I need help logging address of a variable in hex. I've been using__android_log_printto print generic log messages, but how do I tell C to convert address of a variable to a char array?
I never worked with android NDK, but I'm assuming__android_log_printworks with printf format characters. In that case you may use%p. Let's say we have a variableint a = 10;. To print its address: ``` printf("%p\n", &a); //This will print in hexadecimal ``` EDIT: Accepted answer: ``` __android_log_print(SOME_PRIO...
I am trying to find out if there is an alternative way of converting string to integer in C. I regularly pattern the following in my code. ``` char s[] = "45"; int num = atoi(s); ``` So, is there a better way or another way?
There isstrtolwhich is better IMO. Also I have taken a liking instrtonum, so use it if you have it (but remember it's not portable): ``` long long strtonum(const char *nptr, long long minval, long long maxval, const char **errstr); ``` You might also be interested instrtoumaxandstrtoimaxwhich are standard ...
In the proccess of learning C, I'm trying to write a program that accepts one of your environment variable as input, and outputs its value. The question is, is there any way to know the length of envp? I mean, how many envp is there? I'm aware that it is a char** - an array of string. Andfinding the size of array in ...
It's terminated by a NULL pointer. You have to count it if you want to know the length.
I would like to Monitor the creation of windows (HWND) in C. I'd like to know if there's some kind of event that the WINAPI provides to handle the creation of a window.
If you are concerned only with top-level windows, you can useSetWindowHookExto register aShellProcand watch forHSHELL_WINDOWCREATED. If you need notification of the creation ofanywindow, you can use aCallWndProcand watch forWM_CREATEmessages.
This is the string I want to match str = "hello_my_world"; ``` regex_t reg; if (regcomp(&reg, pattern, REG_EXTENDED | REG_ICASE) != 0) { exit (-1); } if (regexec(&reg, str, 0, NULL, 0) != 0) { regfree(&reg); /* did not match */ } r...
You need to read up on regex syntax. The patternhello_*_worldwill match "hello", followed by zero or more underscores, followed by yet an underscore, followed by "world". What you want for a pattern ishello_.*_world, which maches "hello_" followed by zero or more arbitrary chraracters, followed by "_world". The patt...
I need to see if mystringmatches "hello X" where X is anyint. Basically I want to catch if its "hello 1" or "hello 100". How best can I do it? Edit 0 Thanks Andrea Bergia. I am using your code like this: ``` int dummy; if (sscanf(string, "hello %d", &dummy)) /* matched */ ```
``` int dummy; int n = sscanf(string, "hello %d", &dummy); if (n == 1) { // Matched } ```
I have some C code in an iOS project that I would like to optimize using GCD. Currently I can only get my code to compile if change my C file to an Objective-C file and import the Foundation framework. What do I have to include in my C file to get access to GCD? I've tried: ``` #include <dispatch/dispatch.h> ``` bu...
You'll need to tell the compiler to enable Blocks with the-fblocksflag. You'll also need to use a compiler that understands blocks (Clang, for one).
Let assume a,bare_int64variables. Need to calculatesqrt((long double)a)*sqrt((long double)b)in high precision 80 bit floating point. Example.(__int64)(sqrt((long double)a)*sqrt((long double)a) + 0.5) != ain many cases as should be. Which win32 C/C++ compiler can manage 80 bit floating point arithmetic?
You probably should not be using floating point to take the square root of an integer, especiallylong doublewhich is poorly supported and might have an approximate (not accurate)sqrtlon some systems. Instead look up integer square root algorithms.
Why my compiler(GCC) doesnt implicitly cast fromchar**toconst char**? Thie following code: ``` #include <iostream> void print(const char** thing) { std::cout << thing[0] << std::endl; } int main(int argc, char** argv) { print(argv); } ``` Gives the following error: ``` oi.cpp: In function ‘int main(int, ...
Such a conversion would allow you to put aconst char*into your array ofchar*, which would be unsafe. Inprintyou could do: ``` thing[0] = "abc"; ``` Nowargv[0]would point to a string literal that cannot be modified, whilemainexpects it to be non-const (char*). So for type safety this conversion is not allowed.
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.Closed12 years ago. ``` enum ENU{YES=0,NO,DONTKNOW}; v...
``` cout<<e.YES; cout<<e.NO; ``` eis a variable. When you doe.YESyou are trying to depict thatYESis a member ofe; which isnot correct. I think you wanted ``` cout<<YES; cout<<NO; ```
We have a "library" (a selection of code we would rather not change) that is written from the perspective that it has access to 2 files directly. It uses "open", "read" and "seek" posix calls directly on a file descriptor. However, now we have a proprietary file system that cannot be accessed through standard IO call...
When you say you don't want to change the library code, do you mean you want to use existing binary code, or just source? If you have the source and can recompile, I would simply pass-Dread=my_read -Dopen=my_openetc. to the compiler when building the library, and then provide your ownmy_readetc. functions.
I have a file of the following form ``` -1,1.2 0.3,1.5 ``` Basically a list of vectors, where the dimension of the vectors is known but the number of vectors isn't. I need to read each vector into an array. In other words I need to turn ``` -1,1.2 ``` into an array of doubles so that vector[0] == -1 , vector[1] ==...
There's three parts to the problem: Getting access to the data in the file, i.e. opening itReading the data in the fileTidying up, i.e. closing the file The first and last part is covered inthis tutorialas well as a couple of other things. The middle bit can be done using formatted input,here's a example. As long a...
I want to write a program in C# that uses a library to parse C source files, and provides me with a data structure containing all the functions and parameters associated found in it. I don't need to know what is actually inside the function or anything else for that matter. What would be a good library to do that?
ANTLR can do what you'd like. It has a C preprocessor and ANSI C grammar. (http://www.antlr.org/grammar/list)
I would like to determine if the OS that my program currently running on is Windows Error Reporting capable. I would like to do this using some kind of API. Windows Error Reporting was introducing from Vista onwards, but I just can't check if(osType == Vista) because, my code runs on WES 7 and WES 2009 (Windows ...
Just attempt to do a LoadLibrary for "wer.dll". If it succeeds, you have WER. ``` BOOL IsWindowsErrorReportingAvailable() { BOOL fRet = FALSE; HMODULE hMod = LoadLibrary("wer.dll"); fRet = (hMod != NULL); if (fRet) { // make sure the APIs from WER we want to use are available f...
I have java program which receives encrypted message through TCP/IP from one component of the system.It has to send this message to a HSM (Hardware Security Module) which will decrypt the message. Now this HSM talks C as far as I know.I am thinking of putting a Message Queue in between where Java program will put text...
You can also write a c function to access the HSM and call it via Java Native Interface (JNI). Here is a link to a SunJNI Tutorial.
I used GCC and need to define big array of text, like ``` const char* myArray[1000] = {"red", "blue", "green", "yellow", ...}; ``` I have a array of pointers and big heap of text like"red\0blue\0green\0..."somewere in memory. I want to change memory region for that text. I used__attribute__((section(...)))GCC direct...
You can use -fdata-sections with gcc. That will create a unique section for each global variable in the object-file. Then you can create a LdScript-file which will tell the linker (ld) to put the sections into the desired memory region. Anonymous strings are in the .rodata-section of the object-file. An LdScript-exa...
I am tweaking code residing in the/netdirectory of linux kernel. I was trying things like printing but I see that there are no relevant headers (likestdlib.h,stdio.hetc). So how can I do this at the kernel level?
You cannot use any user space library functions in kernel, You should use only functions exported by the kernel. So, there will not bestdio.h,stdlib.h, etc. If you want to print something in the kernel, you have theprintk()function, this is equivalent toprintf()in user space. See also my blog postsLinux Module Progra...
I've got adoublethat prints as0.000000and I'm trying to compare it to0.0f, unsuccessfully. Why is there a difference here? What's the most reliable way to determine if your double is zero?
To determine whether it's close enough to zero that it will print as0.000000to six decimal places, something like: ``` fabs(d) < 0.0000005 ``` Dealing with small inaccuracies in floating-point calculations can get quite complicated in general, though. If you want a better idea what value you've got, try printing wi...
I havedispatchQueue.c:215: warning: control reaches end of non-void functionwarning from the code below..Can anyone please explain why? ``` void *dispatcher_threadloop(void *arg){ //thread loop of the dispatch thread- pass the tast to one of worker thread dispatch_queue_thread_t *dThread = arg; dispatch_queue_t *dQ...
Because you are declaring itvoid *(notvoid) andnot returning anything. ReturnNULLif you don’t need any return value. ``` void *dispatcher_threadloop(void *arg) ```
I have the following code: ``` typedef unsigned char some_type[6]; int main() { some_type some_var1; some_type some_var2; some_var1 = some_var2; return 0; } ``` And when i try to compile it, I get the following error message: ``` incompatible types when assigning to type 'some_type'...
You can't assign arrays to each other like that. If these are strings, use strcpy: ``` strcpy(some_var1, some_var2); ``` If not, use memcpy: ``` memcpy(&some_var1, &some_var2, sizeof (some_type)); ```
Why does the following code behave as it does in C? ``` float x = 2147483647; //2^31 printf("%f\n", x); //Outputs 2147483648 ``` Here is my thought process: ``` 2147483647 = 0 1001 1101 1111 1111 1111 1111 1111 111 (0.11111111111111111111111)base2 = (1-(0.5)^23)base10 => (1.11111111111111111111111)b...
The value to be represented would be 2147483647. the next two values which can be represented this way are 2147483520 and 2147483648. As the latter is closer to the unrepresentable "ideal one", it gets used: in floating point, the values get rounded, not truncated.
Can anyone please tell me why I have segmentation fault here? ``` void *dispatcher_threadloop(void * queue){ //thread loop of the dispatch thread- pass the tast to one of worker thread dispatch_queue_t *dQueue; printf("message-boss1"); dQueue = (dispatch_queue_t *)queue; if (dQueue->HEAD!=NULL){ for(;;){ ...
queueis probably 0 or points to some invalid location in memory. If you want more help, seehttp://sscce.org/
I was tokenizing, and used strtok on a text file (which has been read into an array 'store') with the delimiter '=' so there was a statement in the file :TCP.port = 180 And I did: ``` str = strtok(store, "="); str= strtok(NULL, "="); ``` Now if I do*str, it gives me '82' (probably some junk value) butatoi(str);gi...
Compile and run this program. It should give you a better idea of what's going on. ``` #include <stdlib.h> #include <stdio.h> int main(void) { const char *s = "180"; printf("s = \"%s\"\n", s); printf("atoi(s) = %d\n", atoi(s)); printf("*s = %d = '%c'\n", *s, *s); return 0; } ``` Here...
If there's a structure with a pointer to a struct declared within it, how do you determine the size of the sub-struct? ``` typedef struct myStruct { int member; struct subStruct { int a; int b; } *subStruct_t; } myStruct_t; ``` How do you allocate space for thesubStruct_tpointer? I was thinking somethi...
``` M.subStruct_t = calloc(1,sizeof(*M.subStruct_t)); ``` Note: allocate for the size of the structure, not for the pointer
On my linux (Ubuntu 11.04) development machine. I often need to install libraries from source. This always causes problems for me because the package manager doesn't consider packages installed from source when it checks dependencies. This makes the package manager worthless to me since once I install one set of libs ...
Alternatively, you should look into theequivspackage, which is made exactly for the purpose of creating empty .debs that will make apt/dpkg think a certain package is installed when it isn't.
I've seen many times code like this: ``` void func(){ #define a ... ... #undef a } ``` Is the#undefnecessary at all?
It is not necessary, but the scope of a#defineis global after the line it was defined. It will not obey the function scope, if you are thinking it will.
This question already has answers here:Execution of printf() and Segmentation Fault(4 answers)Closed1 year ago. When a segmentation fault occurs, the printf() before it does not execute. ``` main() { printf( "something" ); statement; //this statement causes a segmentation fault } ``` In the situation above, why ...
Make sure you include a newline"\n"in your printf statement. Normally, at least in UNIX systems,stdoutis line-buffered so newline character makes the line to appear immediately. You probably omitted"\n"(or your output is not flushed for other reason) and that's why you can't see the printed string. Another option is ...
what does this regex match? How can I use this regex in C? I am getting error if I do: ``` if (regcomp(&reg, "/[^\\]\]/", REG_EXTENDED | REG_ICASE) != 0) ``` error: ``` warning: unknown escape sequence '\]' ``` Thanks in advance.
I think you need to escape your backslashes: ``` from "/[^\\]\]/" to "/[^\\\\]\\]/" ```
my string looks like this: ``` abcd "efgh [data\]" pqrl 12fgd] ``` I want to parse till ']' which is not proceeded by a backslash '\' Can I do it withstrtok_r? If not than how should I do it?
You could do it withstrchr. Here is how I would try to do it (untested): ``` p = str; while ((p = strchr(p, ']')) { if (p > str && *(p-1) != '\') /* This is it. */ ```
I have got a binary number of length 8 for eg 00110101 There are 8 bits set. I need a fast bit count to determine the number of set bits. Running the algo like this x=x&(x-1) will limit it to the number of set bits in the number contains but I am not very sure as to how to use it.A little help would be appreciable!!
Thisx=x&(x-1)removes the lowest set bit from the binary string. If you count the number of times you remove the lowest bit before the number becomes 0, you'll get the number of bits that were set. ``` char numBits(char x){ char i = 0; if(x == 0) return 0; for(i = 1; x &= x-1; i++); return i; }...
I run a program using Makefile and it is giving me a strange error, although successfully executed.make: *** [test] Error 10 Here is my Makefile code ``` 30 31 test: 32 @ echo 33 @ echo "Testing Electric Fence." 34 @ echo "After the last test, it should print that the test has PASSED." 35 ...
To workaround that (in case you cannot modify the (return/exit) behaviour of your binaries) use ``` ./exec || /bin/true ``` .
what is the purpose of signed char if both char and signed char ranges from -127 - 127? what is the place where we use signed char instead of just char?
unsigned charis unsigned.signed charis signed.charmay be unsignedorsigned depending on your platform. Usesigned charwhen you definitely want signedness. Possibly related:What does it mean for a char to be signed?
i am trying to run a very simple C program using XCode which is typed below ``` 1) #include <stdio.h> 2) int main () 3) { 4) printf("Hello, World!\n"); 5) func(); 6) return 0; 7) } 8) void func() 9) { 10) printf("xxxx"); 11) } ``` In line number 5 i am getting warning "Implicit declaratio...
You need to declarefunc();before using it (in main), otherwise it is declared as a function that returnsint, and when the compiler gets to line 8, it sees a different declaration of the same function that returnsvoid. ``` #include <stdio.h> void func(void); int main () ```
my string is: ``` He is a "funny" guy ``` How can I extract that usingstrtok_r? ``` strtok_r(str, "\"", &last_pointer); ``` Is this a correct way of doing it? will the statement above skip first"?
My documentation forstrtok_rsays char *strtok_r(char *str, const char *delim, char **saveptr);On the first call tostrtok_r(),strshould point to the string to be parsed, and the value ofsaveptris ignored. In subsequent calls,strshould beNULL, andsaveptrshould be unchanged since the previous call. So you should c...
In linux using gcc when I write a loop like this while(1 || 0) It enters the loop but when I write the loop like this while(0 || 1) it doesn't enter the loop. What is the differrence?
There is no any difference. Execution should enter the loop in both expressions.
Which is the best way to find out whether the division of two numbers will return a remainder? Let us take for example, I have an array with values {3,5,7,8,9,17,19}. Now I need to find the perfect divisor of 51 from the above array. Is there any simpler way to solve this?
You can use the%operator to find the remainder of a division, and compare the result with0. Example: ``` if (number % divisor == 0) { //code for perfect divisor } else { //the number doesn't divide perfectly by divisor } ```
I am working on a C function to split a string of letters into an array, however it keeps seg faulting and I have no idea why. I have run it through DDD a few times, it was not of much help. ``` char* stringToArray(const char *desc) { int i = 0; int j = 0; char *array[5][10] = {{0}};/*5 words, 10 chars e...
You will need to make your array static or allocate some memory for it - returning a pointer to a local array won't work. You also might want to check out strtok.
Trying to find out what the (float) in this function means: ``` static float avgEndpoints (int i, int stride, float *fa) { return ((float) (fa[i-stride] + fa[i+stride]) * .5f); } ``` The reason I'm confused is the function already returns floating point (or appears to), so what is the (float) do...
The(float)is a cast, which in this example casts the expression(fa[i-stride] + fa[i+stride])to floating point. In this case the cast is redundant and not required (as the expression will be a float anyway due to the*.5f)
Which is the best way to find out whether the division of two numbers will return a remainder? Let us take for example, I have an array with values {3,5,7,8,9,17,19}. Now I need to find the perfect divisor of 51 from the above array. Is there any simpler way to solve this?
You can use the%operator to find the remainder of a division, and compare the result with0. Example: ``` if (number % divisor == 0) { //code for perfect divisor } else { //the number doesn't divide perfectly by divisor } ```
I am working on a C function to split a string of letters into an array, however it keeps seg faulting and I have no idea why. I have run it through DDD a few times, it was not of much help. ``` char* stringToArray(const char *desc) { int i = 0; int j = 0; char *array[5][10] = {{0}};/*5 words, 10 chars e...
You will need to make your array static or allocate some memory for it - returning a pointer to a local array won't work. You also might want to check out strtok.
Trying to find out what the (float) in this function means: ``` static float avgEndpoints (int i, int stride, float *fa) { return ((float) (fa[i-stride] + fa[i+stride]) * .5f); } ``` The reason I'm confused is the function already returns floating point (or appears to), so what is the (float) do...
The(float)is a cast, which in this example casts the expression(fa[i-stride] + fa[i+stride])to floating point. In this case the cast is redundant and not required (as the expression will be a float anyway due to the*.5f)
This question already has answers here:Closed12 years ago. Possible Duplicate:C String literals: Where do they go? Here is a piece of C code that I was asked to analyze in an interview. ``` int main() { char *ptr = "hello"; return 0; } ``` Which part of the memory does the string "hello" get stored?
This is implementation-specific and not specified by the standard. You'd have to consult the documentation for your particular compiler to determine where it's placed. Generally, compilers place string literals in a read-only data segment such as the code segment. This allows multiple different string literals to b...
I constructed a database manipulating GUI using glade, for my add button hierarchy is add->confirmation dialog->(if yes)add data. how could each widget values in the main form be accessed? i am new to gtk and glade, i managed to get rid of most of the errors.
Ordinarily you would use GtkBuilder like Ethan said. As far as I know, dynamically-created widgets can't be so easily looked-up. I'd just pass a small array of pointers to the modules that need them.
I have these two structures... ``` typedef struct{ MY_SECOND_STRUCT s1; }MY_FIRST_STRUCT; typedef struct{ int s1; }MY_SECOND_STRUCT; ``` I prefer this order, I dont want to switch them. But compiler dont know MY_SECOND_STRUCT at the moment and I get error error: expected specifier-qualifier-list before '...
I prefer this order, I dont want to switch them. You have to switch them. IfMY_FIRST_STRUCThas a member variable of typeMY_SECOND_STRUCTthenMY_SECOND_STRUCTmust be defined and complete (not just declared and incomplete) before the definition ofMY_FIRST_STRUCT.
I am trying to get total and if possible free memory of the system by C. It should be system-independent. To initiate the discussion I can suggest getpagesize() method to get page-size. Anyone can help about number of memory pages would be good.
There isn't a system independent way of doing this because it is obviously system dependent!
Is there a good GUI designer (read: drag 'n drop/WYSIWYG) for the plain old Windows API? I'm not looking for something that uses Qt, GTK, .NET, etc, just plain old Windows API. Must be usable with either C or C++.
You are looking for a resource editor. Visual Studio Professional, Premium and Ultimate have one built into the IDE. You can access it by creating a new .rc file and then adding a resource to it. If you're not using Visual Studio you can use an external resource editor such as ResEdit. Not having it built into the ID...
I wrote a C program in Linux to set the values of environment variables usingsetenv, but after execution, when I runsetorexport, the environment variable itself seems to be unset. Why? Here is the code snippet: ``` int main() { char *mallocPtr, *callocPtr, *reallocPtr, *memalignPtr, *vallocPtr; struct sigaction ...
The environment variables are set within the context of your program. When your program exits, you're back in the context from where your program was started.
in c fseek,fopen this all function works for long int means only handle file of 2 gb. now how can i open file whose size is more than 2 GB?
As the commenters have already explained, whether you can open a file of more than 2GB depends on the OS and C library, not on the compiler onsizeof(long). If your OS supports such files, you should be able tofopenthem, although you may have to set a flag (#define _FILE_OFFSET_BITS 64for Linux). Then,fseekindeed cann...
I have the following function implementation that checks for NULL pointer. This is a part of Linux driver, C code: ``` bool is_null_ponter(volatile void* ptr) { return (NULL == ptr)? true : false; } ``` What is the advantage of volatile in that case? Why not to put it in a register? Thank you.
Thevolatilehelps that any pointer can be passed to the function without error or warning even if it isvolatilequalified. But this is bogus, the driver you see seems not to be written very professionally. First, to be complete such a pointer should also beconstqualified, only then it would capture really all pointers...
I need to make one 2D array in which one column store the pointer of some structure & another column store one 32 bit magic number. how can i do it in 2D array.? or any other method to keep track of this two columns info?
You can use: ``` // The struct that will hold the pointer and the magic number struct data { void *other_struct_ptr; unsigned int magic_number; }; // Declare my array struct data array[N]; ``` Where N is the size of your array. Now just fill your data into the array. For example: ``` array[0].other_struct_...
This question is probably stupid or paranoidal, but anyway :-). Given following code: ``` DWORD hiRes; // will overflow about once in an hour hiRes = GetTickCount() * 1193L; ``` If it known thathiResoverflows periodically and such situations are handled properly, is there anything wrong with this code? UPDATE:Resu...
Overflowing anunsigned intis safe. Overflowing a signed one isn't (undefined behavior). MSDNsays: A DWORD is a 32-bitunsignedinteger (range: 0 through 4294967295 decimal). This type is declared as follows:typedef unsigned long DWORD So it should be safe.
see i m using multiple time malloc & free. so at the end of application i want to make sure there is no memory leakage. all malloc are freed. Is there any method or function to see that? another question : all all os mostly reclaim memory only when that application gets exit but if application is suppose to be run...
At the end of a process the OS reclaims used memory (so it cannot "leak"). so at the end of application i want to make sure there is no memory leakage EDIT James raised an interesting point in the comments: "Any decent programmer should not rely on the OS to do his job". I must underline I was thinking of the follo...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
IRIT modelling environmentsupports trivatiate spline volumes. It is free, but only for non commercial uses. You can contact the developer and ask about the commercial licencing terms.
As we all know that Associativity of assignment operator is from right to left but in the given code output should be zero if we go from right to left but output is 1 . ``` main() { int a=3,b=2; a=a==b==0; printf("%d",a); } ``` How output is coming out to be 1 if we go by right to letf?? If we go by right to ...
Assignment is done RTL, but equality (==) isn't. The statement is actually: ``` a = ((a == b) == 0) ``` The right hand side of the assignment is evaluated from left to right. In steps, this is what's happening: a == bis00 == 0is11is assigned toa
I'm looking for a Virtual Machine runtime environment that is embeddable in any ANSI C code. I have designed a syntax for a functional language that looks a lot like a stripped version of CoffeeScript. Now I want to write a compiler for this language, but I don't have know what VM I should go for. The key function ...
There's also theNeko VM.
Whether following structure declaration is right. ``` typedef struct { int roll; int age ; } class[10]; ``` When I do like this , compiler does not say any error. But, when I assignclass[0].age=10,am getting error. So here class[0] struct variable or structure name.. Thanks
You are defining atypeclasswhich is an array of ten structs. To use this type you have to instatiate a variable of that type: ``` class x; x[0].age = 10; ``` Maybe a slightly cleaner way would be to have two separate typedefs: ``` typedef struct { int roll; int age; } foo_unit; typedef foo_unit foo_array[10]; foo...
I am trying to parse through an array for a char and delete everything after that. I did write the code to find the location of the char search in the array. How to delete the remaining part of the array after the identified location. Thank you
You can usememset: ``` memset(&arr[current_location], 0, sizeof(arr) - current_location); ``` To set all bytes inarraftercurrent_locationcontain0
I'm looking at someone's code and they did: if ( myNum > (num1 && num2 && num3) ) ... with the intent of executing code when myNum is greater than num1, num2, and num3. Will this work? edit: Thanks guys. I didn't think it would work, but I'm no expert, so I thought I'd ask people who are.
Assuming the values are of a type likeint, in C or C++ this would first evaluate ``` (num1 && num2 && num3) ``` as ``` (num1 !=0) && (num2 != 0) && (num3 != 0) ``` The result would be eithertrueorfalsein C++, and either 1 or 0 in C. You would then comparemyNumto that result.
I have a struct of values for a date. ``` struct date { int day; int month; int year; }; ``` Are there any libraries for C for quick and easy date validation.
The standard C library functionmktime()will convert year/month/day (really a fullstruct tm) to atime_t, and tell you if something went wrong.
How to call a varargs function via dbus, like printf? The server is written in C, the client is written in Python. My questions are how to write the XML spec file? And how to write my GObject? Thanks in advance. [I use DBus-GLib.]
There is no way to call a variadic function programmatically with varying number and type of arguments. You could use the corresponding "v" functions (vprintfetc.) but there's no way to make theva_listto pass to them from foreign code and pass it over DBus. In any case you really need to rethink your design. It's uns...
``` int a=0; int b=1; int c=a,b; int d=(a,b); ```
Outside of an initialization, the comma ina,bis thecomma operator, and evaluates tob. The parentheses in the line involvingdmakes this such a case. So that line is really just equivalent to: ``` int d = b; ``` However, in the line involvingc, this is not a use of the comma operator. Instead, it's just a list of v...
``` #include<stdio.h> main() { int i; char c; for (i=0;i<5;i++){ scanf("%d",&c); printf("%d",i); } printf("\n"); } ``` I thought it will print 0 1 2 3 4 but it didn't. What's the reason of the strange output?
Undefined Behaviour. You're attempting to read anint(the"%d"in the scanf call) into an object of typechar(thec). Don't do that!
I'm trying to do this: ``` typedef struct { float x; float y; } coords; struct coords texCoordinates[] = { {420, 120}, {420, 180}}; ``` But the compiler won't let me. : ( What's wrong with this declaration? Thanks for your help!
Either do: ``` typedef struct { float x; float y; } coords; coords texCoordinates[] = { {420, 120}, {420, 180}}; ``` OR ``` struct coords { float x; float y; }; struct coords texCoordinates[] = { {420, 120}, {420, 180}}; ``` In C,structnames reside in a different name space thantypedefs. Of course...
I'm getting an error on the second while loop "invalid pointer operation" i thinking its because of the len but i need it to be a pointer so i can address this back. Any suggestions on how to fix this error? ``` char* getWord(char* string, short* len) { size_t walker = 0; /*POINT TO THE FIRST CHAR*/ while (stri...
Deference it: ``` while ( string[walker + *len] != ' ' || string[walker + *len] != '\0' ) ++(*len); ``` but first make sure it is initialized... Also, you need to return the pointer to the word, not the char at this address, so write: ``` return (&string[walker]); ``` instead of ``` return (string[walker])...
see i m using multiple time malloc & free. so at the end of application i want to make sure there is no memory leakage. all malloc are freed. Is there any method or function to see that? another question : all all os mostly reclaim memory only when that application gets exit but if application is suppose to be run...
At the end of a process the OS reclaims used memory (so it cannot "leak"). so at the end of application i want to make sure there is no memory leakage EDIT James raised an interesting point in the comments: "Any decent programmer should not rely on the OS to do his job". I must underline I was thinking of the follo...
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
IRIT modelling environmentsupports trivatiate spline volumes. It is free, but only for non commercial uses. You can contact the developer and ask about the commercial licencing terms.
As we all know that Associativity of assignment operator is from right to left but in the given code output should be zero if we go from right to left but output is 1 . ``` main() { int a=3,b=2; a=a==b==0; printf("%d",a); } ``` How output is coming out to be 1 if we go by right to letf?? If we go by right to ...
Assignment is done RTL, but equality (==) isn't. The statement is actually: ``` a = ((a == b) == 0) ``` The right hand side of the assignment is evaluated from left to right. In steps, this is what's happening: a == bis00 == 0is11is assigned toa
I'm looking for a Virtual Machine runtime environment that is embeddable in any ANSI C code. I have designed a syntax for a functional language that looks a lot like a stripped version of CoffeeScript. Now I want to write a compiler for this language, but I don't have know what VM I should go for. The key function ...
There's also theNeko VM.
Whether following structure declaration is right. ``` typedef struct { int roll; int age ; } class[10]; ``` When I do like this , compiler does not say any error. But, when I assignclass[0].age=10,am getting error. So here class[0] struct variable or structure name.. Thanks
You are defining atypeclasswhich is an array of ten structs. To use this type you have to instatiate a variable of that type: ``` class x; x[0].age = 10; ``` Maybe a slightly cleaner way would be to have two separate typedefs: ``` typedef struct { int roll; int age; } foo_unit; typedef foo_unit foo_array[10]; foo...
I am trying to parse through an array for a char and delete everything after that. I did write the code to find the location of the char search in the array. How to delete the remaining part of the array after the identified location. Thank you
You can usememset: ``` memset(&arr[current_location], 0, sizeof(arr) - current_location); ``` To set all bytes inarraftercurrent_locationcontain0