question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to pass a string (or char*) from Rundll32 to a DLL built (with MinGW) using this source: ``` #include <windows.h> __declspec( dllexport ) int hello(LPSTR content) { MessageBox( NULL, content, "Message", MB_OK ); return 0; } ``` When running this I get random crashes. This is how I run it. ``` C:\workspace>c:\MinGW\bin\gdb.exe rundll32 -ex "run program1.dll,hello test" ``` I tried setting a breakpoint at hello() and it seems that "content" is pretty random. Am I passing the argument from rundll32 in the wrong way? It works fine if I don't have arguments.
rundll32 entry points need to be declared in a very specific way. Check outthis articlewhich explains what to do. One thing I've noticed is that, for a symbol called "EntryPoint", the function name passed to rundll32 should be "_EntryPoint@16" for 32-bit DLLs, and just "EntryPoint" for 64-bit DLLs.
Consider: ``` ssize_t write(int fd, const void *buf, size_t count); ``` The result has to be signed to account for -1 on error, etc., and is thus ssize_t. But why then allow for the request to be an unsigned amount (twice as large) when the result of asking for more than ssize_t is undefined? Is there a significant optimization in the kernel by virtue of not checking for signedness of the count parameter? Or something else?
According tothe documentationforssize_t write(int fildes, const void *buf, size_t nbyte) If the value of nbyte is greater than {SSIZE_MAX}, the result is implementation-defined. So each particular implementation may handle this situation differently. I would not be surprised if some implementations simply setEFBIG. As for the rationale, perhapssize_tis simply the best type to represent the size of the buffer, semantically? It states that this argument is a nonnegative size, and nothing else.
What is the programmatic way of enabling or disabling an interface in kernel space? What should be done?
...by using IOCTL's... ``` ioctl(skfd, SIOCSIFFLAGS, &ifr); ``` ... with the IFF_UP bit set or unset depending on whether you want bring the interface up or down accordingly, i.e.: ``` static int set_if_up(char *ifname, short flags) { return set_if_flags(ifname, flags | IFF_UP); } static int set_if_down(char *ifname, short flags) { return set_if_flags(ifname, flags & ~IFF_UP); } ``` Code copy-pasted fromLinux networking documentation.
This question already has answers here:Closed12 years ago. Possible Duplicate:How to create a linux user using C/C++? Is there any way to create new user from c program in Linux?
It's a fairly complicated process to do everything right. The easiest way for you would be to simply run theuseraddprogram, either usingsystem()orfork/exec. Otherwise, if you really, really need to do it in your own code, get the source foruseraddand study it. Seethis questionfor info about finding theuseraddsource.
I want to know how can I work with Bluetooth in android usingC/C++notJAVA APIif somebody have useful links or can give advice ? I foundthispost but I want to know if i gives complete information ?
During my research I found this, and now I want somebody tell me what ishciattach,hcidand where to know how can I work inUserspace bluez: it provides 'hcid' daemon and it's responsible for all related bluetooth services dbus-daemon: the bridge between hcid and system serverD-Bus is a simple inter-process communication (IPC) system for software applications to communicate with one another.debug utility: d-feet (a dbus UI debugger ), dbus-monitor (debug probe to print message bus messages), dbus-send (Send a message to a message bus)bluez dbus API document: /mydroid/external/bluez/utils/hcid/dbus-api.txtone example as below Here isarticlethat gives all answers !
I know that calloc request memory to be used, writes 0 on all the bits and then returns a pointer to it. My question is: if I use calloc with a structure that contains pointers, will those pointers have the NULL value or do I have to set them to point to NULL? ``` struct a{ char * name; void * p; }* A; ``` So basically, will name and p point to NULL after I've used calloc with struct a? Thanks!
Somehow you've gotten a lot of incorrect answers. C does not require the representation of null pointers to be all-zero-bits. Many people mistakenly think it does, since an integer constant expression with value 0, converted to a pointer, becomes a null pointer. With that said, on all real-world systems, null pointers are all-zero-bits, andcallocis a perfectly reasonable way to get a null-pointer-initialized pointer array in the real world.
Does anyone know, how can we verify whether an allocated space is successfully freed? In the manual page, it says that "free() returns no value".
There are three possible cases: ``` free( NULL ); // does nothing, so always works free( malloc(42) ); // does something, always works free( 666 ); // undefined behaviour - returned value would be meaningless ``` So there is no case where testingfree()has a point.
I am using NSight to debug my CUDA code and I have question: how can I place a breakpoint for a specific thread and block? When I place a breakpoint on the kernel the debugger always stops at thread 0 of block 0.
As discussed in the online help in Nsight, you can set a breakpoint and make it conditional on block and thread id like this: To set a block or thread condition on a CUDA C breakpoint: Set a breakpoint on a line of source code.Right-click on the breakpoint.From the drop-down menu, select Condition...Type:@blockIdx(0,2,0) && @threadIdx(5,0,0)Click OK. The breakpoint glyph shows a plus sign.
Hi i would like to convert 0x49 and 0x83 from C++ to C#. May i know what does this 0x49 represent in c# character? Also, what does 83 represent in character? I have searching through google but found no answer for this. I would appreciate it there is a chart outthere list out all the ASCII code representing the characters meaning.
Have a lookhere. But ascii is ascii.. there are no differences between C++ and C#
Is there a way to run linux'sprofin a way equivalent to what a program with-gprofwould do? I know wouldn't be exact, but only statistically correct. I'm basically looking for a way to do agprof-like analysis on a C/C++ program that includes debug symbols, but without recompiling it.
I'm very satisfied lately by CPU profiler of theGoogle performance tools. Programs basically run at undistorted normal speed under it. No recompilation is required, linking against a special libraries is recommended but using LD_PRELOAD is also possible in most cases.
I am using APR library to create portable multi-threading program in C++. Problem is I need to sleep a thread when it is not needed but there is no function mentioned inmanualto do so. Do you now a way how to sleep an APR thread without need to use native system functions? I would like to avoid any OS specific code. Thank you.
If you simply want to hand over CPU to other thread, you can use: ``` void apr_thread_yield(void); ``` Otherwise, you can use: ``` apr_status_t apr_thread_cond_timedwait( apr_thread_cond_t * cond, apr_thread_mutex_t * mutex, apr_interval_time_t timeout ); ``` or ``` apr_status_t apr_thread_cond_wait( apr_thread_cond_t * cond, apr_thread_mutex_t * mutex ); ``` Refer tohere.
This question already has answers here:What's the reasoning behind putting constants in 'if' statements first?(8 answers)Closed9 months ago. While exploring msdn sites ,most of the condition checking places they are using (NULL == bCondition). what is the purpose of using these notations? Provide some sample to explain these please. Thanks.
The use ofNULL == conditionprovides more useful behaviour in the case of a typo, when an assignment operator=is accidentally used rather then the comparison operator==: ``` if (bCondition = NULL) // typo here { // code never executes } if (NULL = bCondition) // error -> compiler complains { // ... } ``` C-compiler gives a warning in the former case, there are no such warnings in many languages.
I am trying to make a calculator in C or Objective-C that accepts a string along the lines of ``` 8/2+4(3*9)^2 ``` and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?
Dave DeLong'sDDMathParserclass may save you a lot of time and trouble.
I want a cross between the two declarations below: ``` char string[6]; char * string; ``` I need a pointer with a fixed size and Idon'twant to usemallocfor something this simple. All this char array needs to do is be assigned a value and have it retrieved by a function as seen below. (But in a loop hence the separate declaration) What is the best way to do this? ``` string = "words"; printf("%s",string); ```
Define a constant array of which the size gets counted by the initializer: ``` const char string[] = "words"; ``` If you just want a pointer to a fixed size amount of memory that is small, just use it like this: ``` const int STR_LEN = 10; char str[STR_LEN]; ... loop, etc strncpy(string, "1234567890", STR_LEN); ... etc ```
Is there any tutorial about FTP transactions(like download, upload and files/directory listings) using Microsoft Visual C++ 6 using C language instead of C++?
You basically want a WinInet FTP client, which is the Win32 API for this kind of thing. You can do all this in straight C. There's a decent writeup here: http://www.teksoftco.com/articles/ftp%20client.htm but the gist is: you use InternetOpen/InternetConnect to get a connection, then use FtpOpenFile/FtpGetFile/FtpPutFile etc. There are FtpFindFirstFile/NextFile to enumerate directories, and other methods for interrogating your current directory, deleting files, etc.
If I have a an array ofints, how could I directly edit eachint? ``` int i = arr + 1; // Getting the integer in pos 1 ``` iis just a copy, correct? If I seti = 4, thenarr + 1would still be1. Would this work? ``` int *i = &(arr + 1); *i = 4; ```
You should use the array operators: ``` int i = arr[1]; arr[1] = 4; ```
Hi i would like to convert 0x49 and 0x83 from C++ to C#. May i know what does this 0x49 represent in c# character? Also, what does 83 represent in character? I have searching through google but found no answer for this. I would appreciate it there is a chart outthere list out all the ASCII code representing the characters meaning.
Have a lookhere. But ascii is ascii.. there are no differences between C++ and C#
Is there a way to run linux'sprofin a way equivalent to what a program with-gprofwould do? I know wouldn't be exact, but only statistically correct. I'm basically looking for a way to do agprof-like analysis on a C/C++ program that includes debug symbols, but without recompiling it.
I'm very satisfied lately by CPU profiler of theGoogle performance tools. Programs basically run at undistorted normal speed under it. No recompilation is required, linking against a special libraries is recommended but using LD_PRELOAD is also possible in most cases.
I am using APR library to create portable multi-threading program in C++. Problem is I need to sleep a thread when it is not needed but there is no function mentioned inmanualto do so. Do you now a way how to sleep an APR thread without need to use native system functions? I would like to avoid any OS specific code. Thank you.
If you simply want to hand over CPU to other thread, you can use: ``` void apr_thread_yield(void); ``` Otherwise, you can use: ``` apr_status_t apr_thread_cond_timedwait( apr_thread_cond_t * cond, apr_thread_mutex_t * mutex, apr_interval_time_t timeout ); ``` or ``` apr_status_t apr_thread_cond_wait( apr_thread_cond_t * cond, apr_thread_mutex_t * mutex ); ``` Refer tohere.
This question already has answers here:What's the reasoning behind putting constants in 'if' statements first?(8 answers)Closed9 months ago. While exploring msdn sites ,most of the condition checking places they are using (NULL == bCondition). what is the purpose of using these notations? Provide some sample to explain these please. Thanks.
The use ofNULL == conditionprovides more useful behaviour in the case of a typo, when an assignment operator=is accidentally used rather then the comparison operator==: ``` if (bCondition = NULL) // typo here { // code never executes } if (NULL = bCondition) // error -> compiler complains { // ... } ``` C-compiler gives a warning in the former case, there are no such warnings in many languages.
I am trying to make a calculator in C or Objective-C that accepts a string along the lines of ``` 8/2+4(3*9)^2 ``` and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?
Dave DeLong'sDDMathParserclass may save you a lot of time and trouble.
I want a cross between the two declarations below: ``` char string[6]; char * string; ``` I need a pointer with a fixed size and Idon'twant to usemallocfor something this simple. All this char array needs to do is be assigned a value and have it retrieved by a function as seen below. (But in a loop hence the separate declaration) What is the best way to do this? ``` string = "words"; printf("%s",string); ```
Define a constant array of which the size gets counted by the initializer: ``` const char string[] = "words"; ``` If you just want a pointer to a fixed size amount of memory that is small, just use it like this: ``` const int STR_LEN = 10; char str[STR_LEN]; ... loop, etc strncpy(string, "1234567890", STR_LEN); ... etc ```
Is there any tutorial about FTP transactions(like download, upload and files/directory listings) using Microsoft Visual C++ 6 using C language instead of C++?
You basically want a WinInet FTP client, which is the Win32 API for this kind of thing. You can do all this in straight C. There's a decent writeup here: http://www.teksoftco.com/articles/ftp%20client.htm but the gist is: you use InternetOpen/InternetConnect to get a connection, then use FtpOpenFile/FtpGetFile/FtpPutFile etc. There are FtpFindFirstFile/NextFile to enumerate directories, and other methods for interrogating your current directory, deleting files, etc.
If I have a an array ofints, how could I directly edit eachint? ``` int i = arr + 1; // Getting the integer in pos 1 ``` iis just a copy, correct? If I seti = 4, thenarr + 1would still be1. Would this work? ``` int *i = &(arr + 1); *i = 4; ```
You should use the array operators: ``` int i = arr[1]; arr[1] = 4; ```
I am trying to pass whatever arguments are passed into the MAIN thread to a "sub thread" I create with "pthread_create". ``` void *threadMainLoop(void *arg){ char *arguments = (char*)arg; printf("arg 1 - %s\n", arguments[1]); } int main(int argc, char *argv[]){ printf("Start of program execution\n"); rc = pthread_create(&outboundThread, NULL, threadMainLoop, (void *) argv); printf("Thread create rc: %i, %d\n", rc, outboundThread); if(rc != 0){ printf("Thread creation failed\n"); exit(1); } pthread_join(outboundThread, NULL); return 0; } ``` The above code does not work, can you please show me how I can access the ARGV array like "argv[0]" etc in the thread?
Theargvinmainis achar**, not achar*, and so that's what you should cast it back to inthreadMainLoop.
Say i have an array in C ``` int array[6] = {1,2,3,4,5,6} ``` how could I split this into ``` {1,2,3} ``` and ``` {4,5,6} ``` Would this be possible using memcpy? Thank You, nonono
Sure. The straightforward solution is to allocate two new arrays usingmallocand then usingmemcpyto copy the data into the two arrays. ``` int array[6] = {1,2,3,4,5,6} int *firstHalf = malloc(3 * sizeof(int)); if (!firstHalf) { /* handle error */ } int *secondHalf = malloc(3 * sizeof(int)); if (!secondHalf) { /* handle error */ } memcpy(firstHalf, array, 3 * sizeof(int)); memcpy(secondHalf, array + 3, 3 * sizeof(int)); ``` However, in case the original array exists long enough, you might not even need to do that. You could just 'split' the array into two new arrays by using pointers into the original array: ``` int array[6] = {1,2,3,4,5,6} int *firstHalf = array; int *secondHalf = array + 3; ```
Can anyone give me an example code for a tool window (with pixel dimensions) for the Win32 API? Thanks
Tool windows are just windows with the WS_EX_TOOLWINDOW extended style: ``` hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, 100, 100, 500, 400, NULL, NULL, hInstance, NULL); ``` Note you need to use CreateWindow*Ex* to use extended styles. The above is a 500x400 window at 100,100 on the screen.
I need to parse a document in C language. I was about to use the strtok function but I don't know if it's the best method or if just a token system is enough (searching for \n, space etc). The structure of each line of the document is : element \n element "x". thanks :-)
Token system if fine,strtokis just an implementation of that. However, you're better off with usingstrtok_rwhich does not keep any internal state outside control of your program.
Here's the log from the build. This is a brand new project in Xcode 4, so the only non-regular things in it are as follows: A .c fileA .a libraryA bunch of header files I've been playing with the build settings and searching for answers for a couple of hours now to see if it would go away, but it didn't. Any help you have would be appreciated.! The output (click for a larger image):
You have a duplicate symbol error - your program can't have two functions calledmain(). Remove one of them, and you should be able to move forward.
a very simple question I am afraid but I have been stuck for days with this, Google gives me nothing, I even tried bing... ;o) I am working in pure C under windows in VS2010. I have a static char array as such... ``` static char word[5]; ``` I can set each array position just fine i.e... ``` word[0] = 'f'; word[1] = 'o'; word[2] = 'o'; ``` But what I cannot seem to do (at any point after declaration) is... ``` word = "foo"; ``` Any help or pointers as to where I am going wrong would be very much appreciated. Thanks all in advance.
``` strncpy(word, "foo", _countof(foo)); ``` If_countofis not defined, usesizeof(foo) / sizeof(*foo)instead.
Can a function be defined like this: ``` int foo(int temp1, int temp2 temp3) { ... } ``` Specifically withtemp2andtemp3, will that cause errors? If not, what's the overall effect?
You're allwrong.. This isperfectlyvalid with: ``` #define temp2 blah) { return 1; } int foo_ (int int foo(int temp1, int temp2 temp3) { return 0; } ``` (This is the outcome of me feeling a little humorous first thing in the morning - feel free to downvote if you'd like to ;))
How can I add a new libc function and also call it from C programs? The new function is a not a wrapper to any kernel level system calls. Its function will be done in user space.
Put it in its own library file and link it with-llibrary_name_here. The only things that belong in libc are already there (along with plenty of things that don't belong there).
During a interview, I was asked what kind of overflow tool in C language you used? I do not know any tool like that. And in C++, what kind of tool used to track the versions of c++ files? Do anyone know about that?
I assume that "overflow" in this context is referring to "buffer overflow". There are a range of memory debuggers available, that can detect this kind of error. One popular example isValgrind. Tracking file versions is generally done with arevision control system(RCS), but this isn't specific to C++. There are zillions of RCSs available, such as Sourcesafe, Perforce, ClearCase, CVS, SVN, Git, Mercurial.
Lets say I have float x from main ``` import progC def main(): x = 3 y=progC(x) print y if __name__ == __main__ main() ``` ``` #include <Python.h> static PyObject* py_bracket(PyObject* self, float x){ x = x+5; return Py_BuildValue("d",x); } ``` ok problem is my float x in my C program receiving 0 not the number 3 from python
Try this: ``` static PyObject* py_bracket(PyObject* self, PyObject* args){ float x; if (!PyArg_ParseTuple(args, "f", &x)) return NULL; x = x+5; return Py_BuildValue("f",x); } ```
i'm trying to compute "2^0 + 2^1 + 2^2 + ... + 2^14", using the following program(i'm a newbie and can only compute a exponent by multiply itself a certain times). The result should be 32767, but i ran it and got 270566475, i thought for long but can't figure out why... ``` #include <stdio.h> int main(void) { int i, e, exponent, sum; e = 1; exponent = 1; sum = 1; for (i = 1; i <=14; i++) { for (e = 1; e <= i; e++) { exponent *= 2; } sum += exponent; } printf("%d\n", sum); return 0; } ``` So what's wrong with this??? Thanks!!!
You don't need the inner loop. Just executeexponent *= 2once, directly inside the outer loop. BTW, I think you have to do itafterthesum += .... Also, you could start withsum = 0andi = 0, which is closer to the math you described.
For the following piece of code: ``` #include<stdlib.h> #include<stdio.h> int main() { int x; x = rand()%100; printf("The Random Number is: %i", x); return 0; } ``` It always seems to print the random number as 83. Why is this?
Mostrandom number generatorsare repeatable. You need to seed the generator before using it which you typically do using the system time. ``` #include <time.h> srand(time(NULL)); ```
I'm declaring an array of strings very simply, hard-coded, but it keeps giving me thearray type has incomplete element typeerror. I guess this has something to do with the length of each array but I don't know how to fix it without setting a fixed length for the strings. ``` char allocate[][2][] = { // Error with or without the 2 {"value1","value2"}, {"value3","value4"} }; ```
That syntax isn't valid. If you want a true multi-dimensional array, all the dimensions must be specified, except the first one. (The compiler must know how big the "inner" arrays are in order to perform address calculation for the outer dimensions.) Try this instead: ``` const char *allocate[][2] = { {"value1","value2"}, {"value3","value4"} }; ``` It declares a 2D array ofconst char *. Note that if you want strings that you canwriteto, then the above approach will not work.
I found the construct= {0};in this C-code sample, found ontidy.sourceforge.netWhat is the rvalue of the statement and is it ANSI C? ``` #include <tidy.h> #include <buffio.h> #include <stdio.h> #include <errno.h> int main(int argc, char **argv ) { const char* input = "<title>Foo</title><p>Foo!"; TidyBuffer output = {0}; TidyBuffer errbuf = {0}; ```
This initializes all fields in a struct, in your caseTidyBuffer, to zeroes. The rule in C is that you can omit members in an initialization clause, and the rest will be initialized to zero. In C++, this is legal as well: ``` TidyBuffer output = {}; ```
I have a header file (sample.h) for my c file (sample.c). When I prototyped a function in my header file as below. ``` return_type sample_fun (FILE *filePtr); ``` I get a compilation error saying,Syntax error: possible missing ')' or ','?When I include the stdio.h error is resolved. Is the stdio.h include mandatory? Some of my files work well without the include. I use gcc on AIX.
Yes, the typeFILEis defined instdio.h; if you mention it, then you must include that file.
my question is not a duplicate ofthisthe solution provided in the above does not work when using Nsight as a debugger.how can i view all the elements of an array inside a kernel when using Nsight as a debugger?QuickWhatch only shows the first 4 elements of the array!
The number of elements NSight will copy to the host for debugging is set in: Nsight->Nsight Options->Debugger->Max Array elements The default is 4, which is why you only see 4 elements. Increase this (and restart your debugging session), and you will be fine.
I write a C program with Xcode 4. I include some OpenSSL header files: ``` #include <openssl/sha.h> #include <openssl/hmac.h> #include <openssl/evp.h> ``` This does not seem to work, as I getApple Mach-O Linker (ld) Error: "..." referenced from:errors. I have tried to include the OpenSSL framework, but I cannot find it in the list (I only findlibsslwhich doesn't do the trick). What am I doing wrong?
#includeis relevant at the preprocessing/compiling phase. Since you’re getting linker errors, the problem is that you haven’t linked the appropriate libraries. OpenSSL is not a framework in the Apple sense, which is why you haven’t found it. In your case, since libssl wasn't enough, you’re missing libcrypto (which is also part of OpenSSL).
I have a function that passes in a struct that and instead of doing bit manipulations on the arr itself I want to create copy. How can I make a copy of an element of an array of unsigned ints to do bit manipulations on? ``` unsigned int * arr = cs->arr; // cs->arr is set as unsigned int * arr; unsigned int copy; memcpy(copy,arr[0], sizeof(unsigned int)); // Copy into copy the first element, for now int i = 0; while(copy != 0) { i += copy & 1; copy >>= 1; } return i; ``` Thank you!
You dont needmemcopy. A simple array access is enough: ``` unsigned int copy = cs->arr[0]; int i = 0; while(copy != 0) { i += copy & 1; copy >>= 1; } return i; ```
My structure variabletemp_var[0].trade_datehas the value of20100614. I need to format this date like6/14/2010. Could anybody please help me put the date in this format?
You could use sprintf, like this: ``` //date int numeric_date = 20110430; //convert integer to string char numeric_date_string[9]; sprintf(numeric_date_string,"%d",numeric_date); //format the string char date[11]; sprintf(date,"%.4s/%.2s/%.2s",&numeric_date_string[0], &numeric_date_string[4], &numeric_date_string[6]); ```
Is it true that the first element always at a lower address than the last element,no matter whether it's in stack or heap?
Um, yes. The elements of astructare located in memory in the same order they're defined in thestructdefinition. They may have padding between them (but there's guaranteed to be no padding before the first one, and a pointer to astructcan be safely cast to a pointer to the first element of thatstruct), but they always get laid out in memory in the same order. Can we ask why you're asking?
I've been gooling for a while, but I found nothing too helpful. What is an opaque byte string and what would be a c/c++ example of it ? UpdateA little more context, from rfc5001 2.3. The NSID Option The OPTION-CODE for the NSID option is 3. The OPTION-DATA for the NSID option is anopaque byte string, the semantics of which are deliberately left outside the protocol. See Section 3.1 for discussion.
They probably mean a byte array of unspecified format. By "opaque" they mean that the inner structure exists, but is unknown. So the program is expected to treat the string as a whole - store it, transmit it, but not try to interpret. The C++ example would be an instance ofstd::vector<unsigned char>. A C example would be an array of unsigned char (either dynamic AKAmalloc'ated or static).
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. Is there any way with which I can generate bit mask of a number without changing the number itself? I am new to programming and I have seen hard-coded bit-masks only. Can we do any operations on the number to generate the bitmask, from the number itself (i.e.: a dynamically generated mask, depending the value of the number) Thanks.
Why not? Use the number itself as a mask: ``` //returns true if bit n is 1 and false otherwise bool get(int index, int mask) { return (mask >> index) & 1; } ```
How can I tell where g++ was able to find an include file? Basically if I ``` #include <foo.h> ``` g++ will scan the search path, using any include options to add or alter the path. But, at the end of days, is there a way I can tell the absolute path of foo.h that g++ chose to compile? Especially relevant if there is more than one foo.h in the myriad of search paths. Short of a way of accomplishing that... is there a way to get g++ to tell me what its final search path is after including defaults and all include options?
``` g++ -H ... ``` will also print the full path of include files in a format which shows which header includes which
AFAIK, C supports just a few data types: ``` int, float, double, char, void enum. ``` I need to store a number that could reach into the high 10 digits. Since I'm getting a low 10 digit # from INT_MAX , I suppose I need a double. <limits.h>doesn't have aDOUBLE_MAX. I found aDBL_MAXon the internet that said this is LEGACY and also appears to be C++. Is double what I need? Why is there noDOUBLE_MAX?
DBL_MAXis defined in<float.h>. Its availability in<limits.h>on unix is what is marked as "(LEGACY)". (linking to the unix standard even though you have no unix tag since that's probably where you found the "LEGACY" notation, but much of what is shown there for float.h is also in the C standard back to C89)
How do I get a microseconds timestamp in C? I'm trying to do: ``` struct timeval tv; gettimeofday(&tv,NULL); return tv.tv_usec; ``` But this returns some nonsense value that if I get two timestamps, the second one can be smaller or bigger than the first (second one shouldalwaysbe bigger). Would it be possible to convert the magic integer returned bygettimeofdayto a normal number which can actually be worked with?
You need to add in the seconds, too: ``` unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec; ``` Note that this will only last for about 232/106=~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
I'm trying to clear all stored cookies in Libcurl (version 7.21.6) but nothing really seems to work. What command should I use? I'm using the C-binding version. Thanks.
You can't "clear" a cookie file (on disk) with libcurl. Just remove it from the file system with a normal system function such as unlink() or zero it with truncate(). You can clear all cookies libcurl knows about in memory with CURLOPT_COOKIELIST "ALL".
I'm a newbie with xml/libxml. What I'm trying to do is simple. I have a node like : ``` <tag attr="example" attr2="example2"/> ``` which is stored in a xmlNode. I want to get the following xmlChar* : ``` "<tag attr="example" attr2="example2"/>" ``` I tried xmlNodeGetContent and xmlNodeListGetString but none of them seem to do what I want. I'm using libxml2 in C. The file xml version is 1.0
xmlNodeGetContentisn't what you're looking for : checkthis pagefor info on its behavior. I think the function you're looking for isxmlNodeDump, which will of course require a valid buffer.
Gtk has casting macros that allow it to change a gtk object's type: ``` GTK_WIDGET(gtktoolbox); ``` Glib works in a similar way (As far as I can tell) but I can't find the macros for data types: ``` G_INT(); // doesn't work GINT(); // doesn't work // etc ``` What are the glib casting macros? Or should I just use(type) variableinstead? I thought the whole point of these macros was to make that less risky? Or did that only apply to gtk objects because of their complex type?
GTK+ uses some magic to do dynamic type checking and type safe casts.http://openbooks.sourceforge.net/books/wga/gtk.html#AEN194This works for the GTK objects, but not for primitive types, like int. Just use(int) varinstead.
I have following code, ``` char * segbase_char = (char*)segbase; ``` As debugged in gdb, it prints ``` segbase_char = 0x80e2da8 segbase = 0xb7ffd000 ``` Any ideas?
It is possible that optimisation has resulted in code being moved around, such that the load ofsegbase_charhas been delayed. Try compiling with a lower level of optimisation enabled.
is there a way for a forked child to examine another forked child so that, if the other forked child takes more time than usual to perform its chores, the first child may perform predefined steps? if so, sample code will be greatly appreciated.
Yes. Simply fork the process to be watched,from the process to watch it. ``` if (fork() == 0) { // we are the watcher pid_t watchee_pid = fork(); if (watchee_pid != 0) { // wait and/or handle timeout int status; waitpid(watchee_pid, &status, WNOHANG); } else { // we're being watched. do stuff } } else { // original process } ``` To emphasise: There are 3 processes. The original, the watcher process (that handles timeout etc.) and the actual watched process.
Is it possible to create a multidimensional array of gtkwidgets? Specifically something like this: ``` mywidgetlist[2]["title"]; ``` Or should I be doing this in a different way? How would I do this? Basically I have a number of "widgets" (Loaded from gtkbuilder) composed of smaller widgets and I want to be able to change certain values, so this array setup seems preferable. Is there another way of doing this (Other than actually coding a complete widget using signals etc and placing them in a simple array?)
In C, you cannot use a string to index into an array. Or, strictly speaking you can, but it's almost never what you want to do. For C solution using glib (handy if you already use GTK+), consider a single-dimensional array ofGHashTablepointers.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question If I could write a user program that would crash my OS(not my application), how would I do it? I was thinking somehow switch my usermode program to kernel mode and cause a memory corruption. Is it possible? Note: I am not creating a virus. Just curiosity.
KeBugCheckon Windows is the documented way to get a BSOD. You can also try deleting therootregistry key (\REGISTRY) in Windows XP, using thenativeNT API.
Is it possible to use a library I wrote in C (compiled with GCC on a Mac) on an Objective-C project under XCode? The project is for a Mac OS X app, not iOS. The library was compiled via GCC on the command line and it is in C (as in C language) and the header for the library (.h file) is a simple C header with function declarations. If yes, how? Furthermore, do I need to convert the .h files to an objective-c styled header? Thank you!
You might take a look atUsing static libraries with iPhone SDK.
How to Create NodeJS equivalent for the below simple C code? ``` int main(int argc, char *argv[]) { if (fork()) { printf("I'm parent %d", getpid()); printf("From parent : %d", 1+1); } else { printf("I'm child %d", getpid()); printf("From child : %d", 10+20); } return 0; } ```
Check outChild Processesin theNodeJS docs. Then check outForeveras an example of how to use them.
I wrote some simple program ``` int main(){ printf("hello word!"); return 0; } ``` I compiled it usinggcc -o hello hello.c(no errors) but when I run itin terminalusing./helloI see nothing, why? thanks in advance
Could be the missing newline, so that the output is mangled with the next prompt. Try: ``` printf("hello world\n"); ``` this version also uses a more conventional message.
In either C or C++, is there a conclusive difference between using!(variable)and(!variable)in anif-statement, such as: if (!(variable)) { .. // do something } or if (!variable && !(variable2)) { .. // do something } such that one version delivers a different result over the other?
Its all about order of operation. Using !(variable) will evaluation all conditions inside of the parenthesis then do the ! (or NOT) to determine whether to enter the if statement where-as (!variable will do the NOT specifically on the variable itself. So in the situations: ``` !(true && false) = true !(true && true) = false (!true && !false) = false (!true && true) = false !(true && !false) = false ``` ...and so on Hope this helped.
when i use read system call, the buffer that i provide in the second argument, where the data from reading are supposed to get stored, gets overwritten right!? thanks, Nikos
Yes, that is the point ofread(), to fill (=overwrite) the buffer with the content read from the file.
I am parsing an XML file using libxml2, and I need to pull out a hex number from an xml attribute. Now, lib2xml doesn't give a null terminated string for the attribute, just pointers to the beginning and end of the attribute. So, given.........FILL:BB0011AA;...............(where dots indicate arbitrary characters), andchar* beginpointing to the F inFILL, andchar* endpointing to the semi-colon, how can I efficiently pull out the hex number, WITHOUT making a copy into a null terminated string?
Like so: ``` unsigned int value; if(sscanf(begin, "FILL:%x;", &value) != 1) printf("Parse error\n"); ``` I think the above is safe even if the data atbeginisn't a string at all, i.e. if it doesn't contain aNULterminator. Since the%xwill abort if any non-hexadecimal character is found, there shouldn't be any risk of it running off into la-la land in memory. I can't come up with a case where it would run amok.
In C, what is the followingspecifiedto do? ``` if ("" == "") { printf("Empty strings are equal\n"); } ``` I have a compiler on hand that tells me that""is indeed equal to"". But is this equality guaranteed? Edit: I understand perfectly well how pointer comparison and string comparison work in C. What I'm asking is what behavior, if any, is specified in the C standard for compile-time constant empty strings. My belief is that the strings are not guaranteed to be equal, but in practice usually will be equal since all const empty strings will be interned to the same address. But I want to know if anyone can provide a definitive reference
TheC Standardsays (6.4.5/6) It is unspecified whether [string literals] are distinct
Can a CFMutableArrayRef store simple integer values? Or must I wrap them like with NSMutableArray (which is basically the same beast at runtime)?
CFMutableArrayand its toll-free bridged siblingNSMutableArraywill only allow a pointer value to be stored inside of it.
``` #include <libxml/xmlmemory.h> #include <libxml/parser.h> static xmlDocPtr importSettings(char file[]="CsSettings.xml"){} ``` That's not so complicated, why does it always throw this error? ``` test.c:3: error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token ``` Am I compiling it wrong?
C doesn't have default parameter values. You need to compile your file as C++. Edit: So you don't want to use C++. (Good, because I don't want to use C++, either.) Here's one reasonable way to do the same thing: ``` static xmlDocPtr importSettings(char file*) { if (file == NULL) { file = "CsSettings.xml"; } /* etc. */ } ``` This way, if you want to use the default, just pass NULL to the import settings. Another option is to add#define DEFAULT_XML_FILE "CsSettings.xml"somewhere in your header, and then require callers to passDEFAULT_XML_FILEif they want to use the default.
In this small program, why doesGetCurrentProcess()return -1? ``` int _tmain(int argc, _TCHAR* argv[]) { HANDLE h = GetCurrentProcess(); // ret -1 printf("0x%x\n",(DWORD)h); return 0; } ``` What's wrong? InKernel32.GetCurrentProcessI see this: ``` OR EAX,FFFFFFFF ; EAX - ? RETN ```
That is correct, seethis API reference for GetCurrentProcess. TheGetCurrentProcessfunction retrieves a pseudo-handle for the current process, which is currently defined as(HANDLE)-1. However, because you should not assume that the value will never change, theGetCurrentProcessfunction is provided as an alternative to hard-coding the constant into your code.
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. I want to use C or C++ to do hard realtime processing of market ticker data. Are there any special considerations to take into account when using either language? Such as headers or what not to do? Regards
Don't use dynamic memory allocation (malloc/free) because you can't predict the amount of time this will take. Don't use critical sections (same reason), use lock-free algorithms instead if necessary.
1. ``` void main(void) { int *ptr1; ptr1 = (int *)malloc(..); } ``` 2. ``` void main(void) { static int *ptr2; ptr2 = (int *)malloc(..); } ``` I want to ask how is memory allocation done for ptr1 & ptr2?
Theptr1pointer itself is allocated on the stack.ptr1points to memory on the heap. Theptr2pointer itself is allocated on program startup (beforemainis invoked) and is global but just happens to be visible only inmainbecause it is declared in its scope.ptr2points to memory on the heap as well. Declaringptr2outside ofmainwould only make it visible in all functions below it, but its storage will be the same.
1)can we define a void pointer?such asvoid * pointer;is it allowed in C? what is a void pointer?2) I always hear about Global Variable, but I do not know how to define Global Variable, I mean where to define a Global Variable? in the beginning of a file or what?
Yes. A void pointer is a pointer to memory where we have not specified what type is at that memory location.Define them outside of any function or class.
Is it possible to use a library I wrote in C (compiled with GCC on a Mac) on an Objective-C project under XCode? The project is for a Mac OS X app, not iOS. The library was compiled via GCC on the command line and it is in C (as in C language) and the header for the library (.h file) is a simple C header with function declarations. If yes, how? Furthermore, do I need to convert the .h files to an objective-c styled header? Thank you!
You might take a look atUsing static libraries with iPhone SDK.
How to Create NodeJS equivalent for the below simple C code? ``` int main(int argc, char *argv[]) { if (fork()) { printf("I'm parent %d", getpid()); printf("From parent : %d", 1+1); } else { printf("I'm child %d", getpid()); printf("From child : %d", 10+20); } return 0; } ```
Check outChild Processesin theNodeJS docs. Then check outForeveras an example of how to use them.
I wrote some simple program ``` int main(){ printf("hello word!"); return 0; } ``` I compiled it usinggcc -o hello hello.c(no errors) but when I run itin terminalusing./helloI see nothing, why? thanks in advance
Could be the missing newline, so that the output is mangled with the next prompt. Try: ``` printf("hello world\n"); ``` this version also uses a more conventional message.
In either C or C++, is there a conclusive difference between using!(variable)and(!variable)in anif-statement, such as: if (!(variable)) { .. // do something } or if (!variable && !(variable2)) { .. // do something } such that one version delivers a different result over the other?
Its all about order of operation. Using !(variable) will evaluation all conditions inside of the parenthesis then do the ! (or NOT) to determine whether to enter the if statement where-as (!variable will do the NOT specifically on the variable itself. So in the situations: ``` !(true && false) = true !(true && true) = false (!true && !false) = false (!true && true) = false !(true && !false) = false ``` ...and so on Hope this helped.
when i use read system call, the buffer that i provide in the second argument, where the data from reading are supposed to get stored, gets overwritten right!? thanks, Nikos
Yes, that is the point ofread(), to fill (=overwrite) the buffer with the content read from the file.
I am parsing an XML file using libxml2, and I need to pull out a hex number from an xml attribute. Now, lib2xml doesn't give a null terminated string for the attribute, just pointers to the beginning and end of the attribute. So, given.........FILL:BB0011AA;...............(where dots indicate arbitrary characters), andchar* beginpointing to the F inFILL, andchar* endpointing to the semi-colon, how can I efficiently pull out the hex number, WITHOUT making a copy into a null terminated string?
Like so: ``` unsigned int value; if(sscanf(begin, "FILL:%x;", &value) != 1) printf("Parse error\n"); ``` I think the above is safe even if the data atbeginisn't a string at all, i.e. if it doesn't contain aNULterminator. Since the%xwill abort if any non-hexadecimal character is found, there shouldn't be any risk of it running off into la-la land in memory. I can't come up with a case where it would run amok.
In C, what is the followingspecifiedto do? ``` if ("" == "") { printf("Empty strings are equal\n"); } ``` I have a compiler on hand that tells me that""is indeed equal to"". But is this equality guaranteed? Edit: I understand perfectly well how pointer comparison and string comparison work in C. What I'm asking is what behavior, if any, is specified in the C standard for compile-time constant empty strings. My belief is that the strings are not guaranteed to be equal, but in practice usually will be equal since all const empty strings will be interned to the same address. But I want to know if anyone can provide a definitive reference
TheC Standardsays (6.4.5/6) It is unspecified whether [string literals] are distinct
Can a CFMutableArrayRef store simple integer values? Or must I wrap them like with NSMutableArray (which is basically the same beast at runtime)?
CFMutableArrayand its toll-free bridged siblingNSMutableArraywill only allow a pointer value to be stored inside of it.
``` #include <libxml/xmlmemory.h> #include <libxml/parser.h> static xmlDocPtr importSettings(char file[]="CsSettings.xml"){} ``` That's not so complicated, why does it always throw this error? ``` test.c:3: error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token ``` Am I compiling it wrong?
C doesn't have default parameter values. You need to compile your file as C++. Edit: So you don't want to use C++. (Good, because I don't want to use C++, either.) Here's one reasonable way to do the same thing: ``` static xmlDocPtr importSettings(char file*) { if (file == NULL) { file = "CsSettings.xml"; } /* etc. */ } ``` This way, if you want to use the default, just pass NULL to the import settings. Another option is to add#define DEFAULT_XML_FILE "CsSettings.xml"somewhere in your header, and then require callers to passDEFAULT_XML_FILEif they want to use the default.
In this small program, why doesGetCurrentProcess()return -1? ``` int _tmain(int argc, _TCHAR* argv[]) { HANDLE h = GetCurrentProcess(); // ret -1 printf("0x%x\n",(DWORD)h); return 0; } ``` What's wrong? InKernel32.GetCurrentProcessI see this: ``` OR EAX,FFFFFFFF ; EAX - ? RETN ```
That is correct, seethis API reference for GetCurrentProcess. TheGetCurrentProcessfunction retrieves a pseudo-handle for the current process, which is currently defined as(HANDLE)-1. However, because you should not assume that the value will never change, theGetCurrentProcessfunction is provided as an alternative to hard-coding the constant into your code.
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. I want to use C or C++ to do hard realtime processing of market ticker data. Are there any special considerations to take into account when using either language? Such as headers or what not to do? Regards
Don't use dynamic memory allocation (malloc/free) because you can't predict the amount of time this will take. Don't use critical sections (same reason), use lock-free algorithms instead if necessary.
1. ``` void main(void) { int *ptr1; ptr1 = (int *)malloc(..); } ``` 2. ``` void main(void) { static int *ptr2; ptr2 = (int *)malloc(..); } ``` I want to ask how is memory allocation done for ptr1 & ptr2?
Theptr1pointer itself is allocated on the stack.ptr1points to memory on the heap. Theptr2pointer itself is allocated on program startup (beforemainis invoked) and is global but just happens to be visible only inmainbecause it is declared in its scope.ptr2points to memory on the heap as well. Declaringptr2outside ofmainwould only make it visible in all functions below it, but its storage will be the same.
Can a CFMutableArrayRef store simple integer values? Or must I wrap them like with NSMutableArray (which is basically the same beast at runtime)?
CFMutableArrayand its toll-free bridged siblingNSMutableArraywill only allow a pointer value to be stored inside of it.
``` #include <libxml/xmlmemory.h> #include <libxml/parser.h> static xmlDocPtr importSettings(char file[]="CsSettings.xml"){} ``` That's not so complicated, why does it always throw this error? ``` test.c:3: error: expected ‘;’, ‘,’ or ‘)’ before ‘=’ token ``` Am I compiling it wrong?
C doesn't have default parameter values. You need to compile your file as C++. Edit: So you don't want to use C++. (Good, because I don't want to use C++, either.) Here's one reasonable way to do the same thing: ``` static xmlDocPtr importSettings(char file*) { if (file == NULL) { file = "CsSettings.xml"; } /* etc. */ } ``` This way, if you want to use the default, just pass NULL to the import settings. Another option is to add#define DEFAULT_XML_FILE "CsSettings.xml"somewhere in your header, and then require callers to passDEFAULT_XML_FILEif they want to use the default.
In this small program, why doesGetCurrentProcess()return -1? ``` int _tmain(int argc, _TCHAR* argv[]) { HANDLE h = GetCurrentProcess(); // ret -1 printf("0x%x\n",(DWORD)h); return 0; } ``` What's wrong? InKernel32.GetCurrentProcessI see this: ``` OR EAX,FFFFFFFF ; EAX - ? RETN ```
That is correct, seethis API reference for GetCurrentProcess. TheGetCurrentProcessfunction retrieves a pseudo-handle for the current process, which is currently defined as(HANDLE)-1. However, because you should not assume that the value will never change, theGetCurrentProcessfunction is provided as an alternative to hard-coding the constant into your code.
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. I want to use C or C++ to do hard realtime processing of market ticker data. Are there any special considerations to take into account when using either language? Such as headers or what not to do? Regards
Don't use dynamic memory allocation (malloc/free) because you can't predict the amount of time this will take. Don't use critical sections (same reason), use lock-free algorithms instead if necessary.
1. ``` void main(void) { int *ptr1; ptr1 = (int *)malloc(..); } ``` 2. ``` void main(void) { static int *ptr2; ptr2 = (int *)malloc(..); } ``` I want to ask how is memory allocation done for ptr1 & ptr2?
Theptr1pointer itself is allocated on the stack.ptr1points to memory on the heap. Theptr2pointer itself is allocated on program startup (beforemainis invoked) and is global but just happens to be visible only inmainbecause it is declared in its scope.ptr2points to memory on the heap as well. Declaringptr2outside ofmainwould only make it visible in all functions below it, but its storage will be the same.
On Windows this ``` #include <stdio.h> int main() { putc('A',stdout); putc('\r',stdout); putc('\n',stdout); } ``` outputs ``` A<CR><CR><LF> ``` How to write just LF char to stdout without automatic conversion to CR LF? I need it to make simple socket stream reader to stdout. I've tried bcc32 from CodeGear, mingw, tinycc all yield same result, changing putc to putchar, fputc, fwrite doesn't help either.
The MSVC solution is: ``` #include <io.h> #include <fcntl.h> ... _setmode(1,_O_BINARY) ``` Other runtimes may provide the C99 solution or an alternate way. EDIT: I believesetmode([file number],O_BINARY)originated on Borland Turbo C, and other compilers for MS-DOS and Windows imitated it. The _ prefix is done to keep the namespace clean, and may not be present on some compilers.
``` KdPrint(("Enter HelloWDMAddDevice\n")); ``` What's the reason for doing that?
That is so you can pass an entire argument list to the macro and have it pass it on to a function that takes a variable number of arguments. I would bet anything that the definition of that macro is: ``` #if DEBUG /* or something like it */ #define KdPrint(args) (printf args) #else #define KdPrint(args) /* empty */ #endif ``` Or similar to some other function that works just like printf. If it were defined as printf(args), then you could only pass the single string argument, because an argument to a macro can't contain a comma that isn't inside a nested parenthesis.
I'm writing an application in C to parse Windows Icon files (ICO). When I read in theBITMAPINFOHEADERstruct for an existing icon entry, all of the variables within the struct contain values that are expected, except thatbiHeight, which should contain the height in pixels of the image, is always twice what it should be. So for example if I have a 64x64 icon,biWidthis 64, butbiHeightis 128. Is this expected behavior? This is my first time dealing withBITMAPINFOHEADER. I'm mainly operating from theMSDN article on BITMAPINFOHEADER.
Yes, this is normal. It is the added height of the "AND" bitmap mask and the "XOR" bitmap mask, so for any normal icon it is simply 2X the icon height. (Those masks aren't used for 32-bit icons anymore; they are a holdover.) Just divide by two.
I'm trying to run the following code, but I cannot compile it as my IDE complained for the following reason. H:\C\sandBox.c|11|warning: implicit declaration of function 'RECIPROCAL'| I don't know why my code doesn't work. Can you please help? ``` #include <stdio.h> # RECIPROCAL(number) (1.0 / (number)) int main() { float counter; /* Counter for our table */ for (counter = 0.0; counter < 10.0; counter += 1.0) { printf("1/%f = %f\n", counter, RECIPROCAL(counter)); } return (0); } ```
That’s because you need to use#defineto define a preprocessor macro. Change: ``` # RECIPROCAL(number) (1.0 / (number)) ``` to ``` #define RECIPROCAL(number) (1.0 / (number)) ```
I tried to the identifier function try_to_change_it() with two styles as below, it produced the same result. Which style is recommend? ``` #include "stdafx.h" #include <stdio.h> // style1 declare try_to_change_it() here void try_to_change_it(int); int _tmain(int argc, _TCHAR* argv[]) { int a = 1; // style2 declare try_to_change_it() here void try_to_change_it(int); printf("%d\n", a); try_to_change_it(a); printf("%d\n", a); return 0; } void try_to_change_it(int a) { a = 777; } ```
It makes no real difference. In a typical case, you declare functions by including a header, which you normally want to do outside any function.
``` #include <stdio.h> #include <stdlib.h> #include <limits.h> int main() { int val[100000000] ; printf("%d", CHAR_BIT); } ``` When I execute the code, It occur "segment fault" error. I suppose this error mean that there is no enough memory on the heap area.
No, it's not theheapthat's the problem, it's thestack. You've declared a local variable, and local variables live on the stack. Tryint *val = malloc(sizeof(int)*100000000);instead. You can test whether that succeeds by examining whether(val != NULL). (Of course, you'll need to remember to callfree(val)when you're done with the memory.)
I know this is stupid but I'm a quiet a noob in a programming world here is my code. This one works perfectly: ``` #include <stdio.h> int main() { float x = 3153600000 ; printf("%f", x); return 0; } ``` But this one has a problem: ``` #include <stdio.h> int main() { float x = 60 * 60 * 24 * 365 * 100 ; printf("%f", x); return 0; } ``` So 60 * 60 * 24 * 365 * 100 is 3153600000 right ??? if yes then why does it produced different results ??? I got the overflow in the second one it printed "-1141367296.000000" as a result. Could anyone tell me why ?
You're multiplying integers, then putting the result in a float. By that time, it has already overflowed. Tryfloat x = 60.0f * 60.0f * 24.0f * 365.0f * 100.0f;. You should get the result you want.
Im using C++ and im trying to create a program similar to handle.exe from sysinternals. Basically, i am getting the filename from the user, and I need to be able to display which process is locking the file. Does anyone know where I can get this information from? I've tried using some process functions in winapi, but I cant figure out how to get this information, Here is an example of what im trying to create: http://www.kartmann.org/freeware/WhoSLocking/ReadMe.htm Thanks in advance
There is an undocumented option onNtQuerySystemInformationto get the file handles for a process. There is sample codehere. Second sample (in Delphi) ishere.
I get "passing argument 2 of ‘execvp’ from incompatible pointer type" andexpected ‘char * const*’ but argument is of type ‘const char **’I'm wondering what the correct syntax is? Thanks! ``` int main(int argc, const char* argv[]) { if(argv[0]!=NULL) return -1; int pid = fork(); if(pid==0) execvp(argv[0],argv+strlen(argv[0])); else wait(); return 0; } ```
execfunctions don't acceptconst char*. In your case, simply changeargvtochar*, that's the correct prototype. Btw.argv + strlen(argv[0])doesn't make any sense, what did you mean by that?
I'm learning C, but I do not understand this: ``` #define square(x) x*x a = square(2+3) //a = 11 ``` When this is run, why doesaend up being11?
It expands to2+3*2+3, which is equivalent to2+(3*2)+3. Use parentheses to fix it: ``` #define square(x) ((x)*(x)) ``` Now try it withsquare(x++)and you'll run into more problems (undefined behavior). Avoid doing this as a macro if you can.
what_if_var[0].price(type ischar [10]) has the value of "$15555.665". Is there is anyway to remove "$" from the value (like "15555.665") and convert the value into double?
If you always know that the'$'is going to be the first character, you could just try: ``` double num = strtod (what_if_var[0].price + 1, NULL); ```
``` #include <windows.h> #include <winbase.h> #include <stdio.h> typedef void (*MYPROC)(LPTSTR); int main() { HINSTANCE LibHandle; MYPROC ProcAdd; LibHandle = LoadLibrary("msvcrt.dll"); printf ("%#p\n", LibHandle); ProcAdd = (MYPROC)GetProcAddress(LibHandle, "system"); printf ("%#p\n", ProcAdd); (ProcAdd)("cmd.exe"); return 0; } ``` The above code is supposed to invoke acmd.execommand then exit,but it turns out will cause infinite loop,why? It's outputing this for me: ``` 0X77BE0000 0X77BF93C7 0X77BE0000 0X77BF93C7 0X77BE0000 0X77BF93C7 0X77BE0000 0X77BF93C7 0X77BE0000 0X77BF93C7 0X77BE0000 0X77BF93C7 0X77BE0000 0X77BF93C7 0X77BE0000 ... ```
The only thing I can think of, and trying this out confirms this, is that you are calling your executable 'cmd.exe', which means the system call is invoking a new version of your program.
Sincefseek()does not work on pipes what methods exist for simulating seeking forward? The naive approach is to usefread()and throw away the contents read into the memory buffer. For huge seeks to avoid huge buffers you would use the same buffer over and over with the final read using just a part of the buffer. But is this the only approach? Is there another way which avoids the buffer and the potential multiple read?
Seeking doesn't make sense on pipes because the input is produced dynamically (not stored on disk). Thelseekkernel system call is not implemented for pipes. Also have in mind that a pipe is essentially a producer-consumer buffer of a limited, fixed size. When it gets full, the producer is suspended until the consumer reads the oldest data.
Quick question: strlen[char*]works perfectly regardless whether I#include <string.h>or not All I get from compiler is a warning about implicit declaration, but functionally it works as intended. Why is that?
When you invokeundefined behavior, one possible behavior is that the program behaves as you expected it to,one your system, andwith the current versionof libraries and system software you have installed. This does not mean it's okay to do this. Actually a correct C99 compiler should not allow implicit function declarations; it should give you an error.