question
stringlengths
25
894
answer
stringlengths
4
863
I have a static method in a cpp file (not in class) . I want to use it globally without redeclaring it as extern . In that case is it possible to use a global function pointer to this static method and use this function pointer globally ??
It is possible to do what you want, but why would you avoid using extern when it does exactly what you are trying to emulate through a much more convoluted (and unreadable) mechanism?
Is it possible to still use inet_ntoa() and not worry about Windows User Permissions? Do I need to put a try/catch block around inet_ntoa() to catch any possible problems if User Permissions prevent me from getting the IP address of an interface?
inet_ntoadoesn't raise exceptions. It returnsNULLin case of an error. It's hard to see how user permissions could come into this function since it is just an integer to string conversion.
I have a 16 bit fixed point processor and I want to do fixed point processing with it. I'm looking for the correct datatype to use for unsigned 16 bit ints.. My question is: what is the difference between auint16_tanduint_fast16_t? (These are included in thestdint.h.) Isuint_fast16_tbetter since it is faster?? Thanks!!
uint16_tis an unsigned 16-bit integer.uint_fast16_tis the fastest available unsigned integer with at least 16 bits.
The following C program: ``` int doStuff(int afm[]); int main(){ int afm1[9] = {1,2,3,4,5,6,7,8,9}; //size=9 int afmLength = sizeof(afm1)/sizeof(int); printf("main: Length Of Array=%d\n", afmLength); //9 OK int k = doStuff(afm1); system("PAUSE"); return 0; } int doStuff(int afm[]){ int afmLength = sizeof(afm)/sizeof(int); printf("doStuff: Length Of Array=%d\n", afmLength); //1 WRONG return 1; } ``` produces the following output: ``` main: Length Of Array=9 doStuff: Length Of Array=1 ``` Why is the array size calculated correctly in main, but is wrong inside the function?
Because inmainyou have an array and in the function you have a pointer to that array. ``` int doStuff(int afm[]) ``` is equivalent to ``` int doStuff(int *afm) ```
the program is to decide big endian or little endian. This is the answer given in the book: ``` int Test(){ short int word = 0x0001; char *byte = (char *) &word; return (byte[0] ? BIG:LITTLE); } ``` I don't understand this line:char *byte = (char *) &word;Does it mean "pass the address of word into byte"? So, now byte point to word's original address? As I known, short int is 2 bytes. So, does "byte" point to higher address or lower address? Why? How does this work?
It's just taking the address ofword, casting it to a char pointer, and putting it inbyte. At that point,bytewill point to the first byte of 2-byteword, and the value of that byte (1 or 0) will tell you if you're on a big or little endian machine.
In my C code, I'mfprintfing a"%lu"and giving auint32_tfor the corresponding field. But, when I compile with-Wallin GCC (ver. 4.2.4), I get the following warning: ``` writeresults.c:16: warning: format '%4lu' expects type 'long unsigned int', but argument 2 has type `uint32_t' ``` Aren't auint32_tandlong unsigned intthe same thing on 32-bit architectures? Can this warning be avoided without eliminating the-Wallcompiler switch or using a typecast (and if so, how)? Yes, I'm still using a 32-bit computer/arch/OS/compiler (too poor at the moment to afford new 64-bit HW). Thanks!
uint32_ton x86 Linux with GCC is justunsigned int. So usefprintf(stream, "%4u", ...)(unsigned int) or better yet,fprintf(stream, "%4" PRIu32, ...)(theinttypes.hprintf-string specifier foruint32_t). The latter will definitely eliminate the compiler warning / error, and, additionally, is cross-platform.
The follow program declares a pointer then again a new pointer to hold address of previous pointer variable.. How much can I use nested pointer variable to hold memory address is there any limit? ``` #include <stdio.h> #include <conio.h> void main() { int x=2,y=5; int *ptr; int **sptr; int ***ssptr; ptr = &x; // address of x *ptr = 0; sptr = &ptr; ssptr = & sptr; printf(" address is ip = %u %u %u",ptr,sptr,ssptr); _getch(); } ```
There is no limit. A pointer is a chunk of memory (typically one word) whose contents are an address. A pointer to a pointer is also a word whose contents are an address, but it just so happens that the contents atthataddress is another address. There is nothing particularly special about a pointer to a pointer (to a pointer to a pointer... etc.,ad nauseum).
Hello lovely computer people: I would like to convert the following CFStringRef into a CString. Any idea how? ``` recordFilePath = (CFStringRef)[NSTemporaryDirectory() stringByAppendingPathComponent: @"recordedFile.wav"]; ``` Thanks! EDIT 1 DarkDust answer seems to come close, but I'm still getting an error (see comment). Any help?
A straightforward solution: ``` CFStringGetCString(myCFStringRef, myCStringPointer, mySize, myEncoding); ``` Checkout this function: ``` Boolean CFStringGetCString ( CFStringRef theString, char *buffer, CFIndex bufferSize, CFStringEncoding encoding ); ```
I wish to make an SMS analysis tool that downloads the SMS.db file from an iPhone device, connected via USB. I am coding in C++ and would like to know how applications such as DiskAid and iPhone Explorer access the entire filesystem via USB? Thanks in advance!
iPhone Explorer requires iTunes; probably it works by employing the iTunes COM API (I know there is one). Anyway, it does not show the full filesystem; just the parts that iTunes exposes. And AFAIK, the SMB.db is not exposed. Or maybe it taps into some lower-level API that iTunes itself consumes. Not sure about DiskAid.
I guess I have two questions really. 1) I was wondering if anyone knows a way to convert mpfr_t types into __float128 types in GCC. I've looked around and found a thread on the mpfr bugfixes site where someone discusses their attempt to write a converter from __float128 to mpfr_t, but it seems to have dropped off sometime last year. 2) If no one knows a way to convert mpfr_t's to __float128's, does anyone know of another arbitrary precision C/C++ library thatcan? Thanks
You might want to look atgfortran's implementationfor translating to intrinsics (the code is C). It makes a couple steps through an intermediary tree structure but the end result is the same.
In some header file which I can not modify I have the following set of defines: ``` #define FLAG1 (0x0000_0001) #define FLAG2 (0x0000_0002) ... ``` Then, in my code I use them in switch: ``` switch (aaa) { case FLAG1: .... case FLAG2: .... } ``` As a result, Coverity reports on 2 defects per each case label: ``` RW.EXP_RPAREN: Event exp_rparen: expected a ")" RW.CASE_LABEL_CONFLICT: Event case_label_conflict: case label value has already appeared in this switch at line XX ``` What is wrong with these case labels? Does it violate C standards?
Yes, you are allowed to have parentheses. What youaren'tallowed to have is a number like0x0000_0001. That's not a valid hex number, you'll probably have to remove the_character.
I'm trying to pass data from C to python. I've hit a brick wall doing it with beanstalk. My last option is sockets. Are they any fast queue daemons around which have client libraries for both C and python? Edit:Operating System: UbuntuSolved: Check comment by Yossarian Edit2:libbeanstalkclient, the C client for beanstalk is spewing errors like these ->linkSolved: Check comment by Yossarian
You aren't linking against libsbeanstalkclient. try something like gcc -lbeanstalkclient when compiling (add the -l... parameter) (this isn't answer on the question, but solution of questioner's problem)
I have a piece of code that uses stdin. When I run the program from command-line I pass it the location of a wav file i.e. /Users/username/Desktop/music.wav. The code is written only in C. The stdin variable runs throughout 2 functions. How would I replace the stdin within the code with the input of the file directory and location? In other words, how do I hard code '/Users/username/Desktop/music.wav' into two different C functions.
I think you are looking forfreopen. If I understand correctly, you read the filename fromargv[1]and call freopen(): ``` freopen(argv[1], "r", stdin); ```
function wait() is declared in another function. Is it legal? ``` void panic(const int reason, const char *strg) { int ErrNo; struct machine_attributes mach; int ret, docstat, cnt; pid_t pid, wait(int *), setsid(void); ...... } ``` Thank you!
Yes, so long as this declaration matches the actual definition of the function. ``` pid_t pid, wait(int *), setsid(void); ``` This declares three entities: apid_tnamedpid, a function (takingint*and returningpid_t) namedwaitand a function (taking no parameters and returningpid_t) namedsetsid. The declaration ofpidis also a definition.
``` static FAST_FUNC int fileAction(const char *pathname, struct stat *sb UNUSED_PARAM, void *modname_to_match, int depth UNUSED_PARAM){...} ``` what does "int depth UNUSED_PARAM" mean ?
Frominclude/platform.hin Busybox-1.18.3: ``` #define UNUSED_PARAM __attribute__ ((__unused__)) ``` And from theGCC documentation: unusedThis attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable. So, it is just a way to tell both the human programmers and the compiler that the variable is not necessarily used. Otherwise, the compiler may warn you about an unused variable. Presumably,fileActionrequires thedepthparameter to be compatible with a function pointer type or other API constraints butfileActiondoesn't actually use the parameter.
folks, from the following code ``` int a = mysql_query(conn,"INSERT into data VALUES (NULL,'tes','aja')); ``` how come i could make sure mysql_query is do the supposed thing, because i've tried wrong sql query and it becomes same return value from mysql_query function which from file mysql.h: ``` int STDCALL mysql_query(MYSQL *mysql, const char *q); ``` is there a way to check that string of query is valid and queried properly ?
According to theMySQL reference documentation for mysql_querythis should return zero on success and non-zero on failure. Are you sure that it is returning 0 value for an invalid query?
I've got a quick and I am assuming question but I have not been able to find anything online. How to calculates the average of elements in an unsigned char array? Or more like it, perform operations on an unsigned char?
C++03 and C++0x: ``` #include <numeric> int count = sizeof(arr)/sizeof(arr[0]); int sum = std::accumulate<unsigned char*, int>(arr,arr + count,0); double average = (double)sum/count; ``` Online Demo :http://www.ideone.com/2YXaT C++0x Only (using lambda) ``` #include <algorithm> int sum = 0; std::for_each(arr,arr+count,[&](int n){ sum += n; }); double average = (double)sum/count; ``` Online Demo :http://www.ideone.com/IGfht
I'm calling a function from a DLL, like this: ``` __declspec ( dllimport ) bool dll_function(...); int main() { [...] if (dll_function(...)) { [...] } } ``` In some cases, the data I pass to the DLL function will lead to a crash of the DLL. Is it possible to catch this so my application doesn't crash as well (without modifying the DLL which is not created by me)?
You can catch AVs with the __try and __except keywords in the MSVC compiler. Not all that useful, you have no idea what kind of damage was done. The state of your program might well be corrupted. The heap might be blown for example, causing subsequent random failure. Hosting the DLL in its own process and using IPC to talk to it is the only decent approach.
As above, say I have a 3 dimensional array, a[][][], and I want to pass this to a function; how should I declare the function parameter?
``` void function1(int array[][3][4]) { ...use array here... } void function2(void) { int array[20][3][4]; ...load array... function1(array); } ```
I have previously,here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading them one way or another because Callgrind, part of Valgrind, show them demangled while in assembly they are shown mangled. So I would like to either mangle the Valgrind function output or demangle the assembly names of functions. Anyone ever tried something like that? I was looking at awebsiteand found out the following: Code to implement demangling is part of the GNU Binutils package; see libiberty/cplus-dem.c and include/demangle.h. Has anyone ever tried something like that? I want to demangle/mangle in C. My compiler is gcc 4.x.
Use thec++filtcommand line tool to demangle the name.
I've been looking through questions on here and the internet for a while now and I cannot seem to find out whether or not it is possible to do inline assembly with GCC using something other than GAS. I am trying to find if I can avoid using not only GAS's AT&T syntax (though, I know how to use Intel syntax with GAS) but the extended asm format. While this is not for a project or anything other than my own curiosity, I would really appreciate any help I can get (this is actually my first question here because I could not find an answer about it)! Also, if this makes any difference, I'm currently using DevC++ (for C code, not C++) on Windows. Thanks, Tom
You can link the output from an assembler (a ".o" or ".obj" file) with your C or C++ program. Put your assembler code in a text file. Your IDE or makefile will assemble it just as it would any c source file. The only tricky bit is learning how to interface between the two different systems.
``` SOCKET server = socket(PF_INET,SOCK_STREAM, 0); bind(server, 7.7.7.7, sizeof(7.7.7.7) ); listen(server, 0); server.Poll(1, SelectMode.SelectRead); ``` error C2228: left of '.Poll' must have class/struct/union type The IP is not the same but the 3 functions work correctly creating a socket that the server can listen to and send data, to the client. I would like to poll the client,using this example but in C++. Which object or structure can I use here with Poll()?
Please read thisTutorial. What you are doing doesn't look close to correct.
Is it possible to pass a large Structure through JNI from C to Java? Can somebody please give me the possible solutions?
Declare a pointer to the struct in your java class like so: protected long ptrToX; Next, to set it: Get the field ID using(*env)->GetFieldID(...)Get the pointer using(*env)->GetLongField(...)Set the pointer using(*env)->SetLongField(...) To get it, just follow the first two steps mentioned above. Always remember to include a finaliser that will take care of deallocating the pointer when the object is garbage-collected. Alternatively, if you do not want to incur the performance hit incurred by using finalisers, just provide a terminate() method that deallocates the pointer.
Is there any way I can synchronize the data(data sharing) between C and Java code with JNI using mutex or any other methods. Please let me know if you have any documentation about the methods for data sharing.
You can use any lock you prefer in C and make it available to Java via JNI. You can do the reverse as well, calling a method in Java from C to use the lock. I would do it natively in the framework which created the thread.
Consider printf: ``` int printf ( const char * format, ... ); ``` What are the terms used to describe the...and the functions that use it? I've been calling it an ellipsis, but that's like calling&the "ampersand operator."
Variable length parameter list Edit: Or, if describing the function itself:Variadic function
I'm concerned about endianness when it comes to this problem. Maybe I am overthinking what I have to worry about. The input to my code is a packet that looks like: I've received a network packet that contains some bytes. If I know the index in the byte array (and have valid data) of where thein_addris, is it safe to do something like: ``` uint8_t* addrPtr = packet[IP_IDX]; struct in_addr addr; memcpy((void*) addr, addrPtr, sizeof(in_addr)); ``` Is this safe regardless of Endianness? What about for in6_addr which is actually 16 bytes? Thanks.
struct in_addris supposed to be in network byte order, IIRC. Assuming your packet is also delivered in network byte order, you're good to go.
Hello nice computer persons, Per to aquestion I had earlier concerning accessing the samples in an audio file, I now realize that the Core Audio Format may not be the way to go. Especially sinceon page 15 of the specit mentions something about the use of C being a 'notational convenience' i.e. you can't just crack it open with some c functions and do what you want with it. That said, if I want to open an audio file and then run some C, C++ or Objective-C code on it to play around with the sample values, which format would be best to do this on: WAV? AIFF? other? Please keep in mind I would like this to be able to run on iOS. Thanks!
Uncompressed WAV files. They consist of a header followed by the raw samples.
Could anyone give me a suggestion or an example of how I would loop through the samples of CAF (Core Audio Format) file? Like taking the first 1000 samples and changing them to 0? Something like: ``` for(int i=0; i < numberOfSamples; i++) { cafFile.sample[i] = methodThatUsesSampleValue(cafFile.sample[i]); } ``` Keep in mind: I don't need to do this live. No buffers, etc. needed.I would like to do this in C, C++ or Objective-C.Would like to be able to use the code on the iOS platform. Any help appreciated!
ThelibsndfileC++ library is well-known and provides -among lot of other functions - a function to read AIFF-files:http://www.mega-nerd.com/libsndfile/, the lib is distributed under the "Gnu Lesser General Public License". I don't know if that is an issue.
How could I simple initialize a multidimensional C-array with 0 elements like this: ``` int a[2][2] = { { 0, 0 }, {0, 0} } ```
This should work: ``` int a[2][2] = {0}; ``` EDITThis trick may work for silencing the warning: ``` int a[2][2] = {{0}}; ```
How is an array of structures created in C without knowing the eventual amount of structures to be stored in the array? I would like to loop in a for loop, create a tempStruct set its variables, add this to an array and then loop again, creating a new tempStruct and adding it to the array. Im having some issues wrapping my head around how this is done in C while trying to relate from objective C.
Dynamically allocated arrays (usingmalloc) can be reallocated (usingrealloc). Therefore the solution will look something like this: mallocinitial array (arbitrary size)while still space in array, add structureswhen array full,reallocto bigger sizegoto 2
When I run the following code: ``` #include <stdio.h> int main(int argc, char *argv[]) { int p = 0; p = strcmp(NULL,"foo"); return 0; } ``` I get segmentation fault. echo $? says 139. But when I run ``` #include <stdio.h> int main(int argc, char *argv[]) { int p = 0; strcmp(NULL,"foo"); // Note removed assignment return 0; } ``` I don't get any segmentation fault. Could someone please throw some light? Here is my gcc info: ``` > gcc --version gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-8) ```
You are probably using optimization options when compiling. Since the result ofstrcmp()in the second snippet is ignored the compiler eliminates this function call and this is why your program does not crash. This call can be eliminated only becausestrcmp()is an intrinsic function, the compiler is aware that this function does not have any side effects.
I've just starting playing with Apache, and I wanted know. If I base myself on the tutorial/examples I've found, e.g. mod_example.c or mod_hello.c the http seems always to be sent line by line: ``` ap_rputs("<HTML><HEAD><TITLE>Greetings</TITLE></HEAD></BODY>\n",r); ap_rputs("<H1>Greetings, Earthling</H1>\n",r); ``` Is it a readability issue, or there are real reasons for this ?
It's readability in many cases. You could send the entire response (HTML, etc.) withap_rputs()if you wanted to.
I don't know if it is legal on SOF to access such a specific question, but here I go: I've found this wonderfulpiece of codewhich takes all the samples from a WAV file and passes it into an array. The code compiles, but I can't seem to figure out where to pass the argument of where the file is and what its name is. Any help? PS If this code does what it says it does, I think it could be useful to a lot of people. Thanks!
If you look at the code it's reading fromstdin(and it even says in the description above the code:"It reads from stdin"). Evidently it's designed to be used as a command line tool (or "filter") which can be piped with other tools, or standalone using I/O redirection.
As all we know in windows EOL is CRLF and in linux LF and CR in Mac. (more_info) I want to write a program which reads as linux and Mac as well Win files line by line in Windows. To open file I would use fopen in "rt" mode, but I don't know how read lines. fgets reads until CRLF and LF under Windows but I want it to work for EOL=CR files also. So what is the solution? Thanks in advance.
To open in "t" mode, the file must conform to the platform you are running on. Otherwise you just have to open in binary mode, and sort the difference out yourself. The C library helps you write a program that works roughly the same on different platforms, but does not support "cross reading" the files.
What exactly happens here? a << -5 Obviously it doesn't right shift. But the book I'm reading states: On one machine, this expression actually does a left shift of 27 bits My question is; why? What causes a left shift of 27 bits? And what exactly happens when shifting with a negative shift count? Thank you.
Negative integers on right-hand side is undefined behavior in the C language. ISO 9899:2011 6.5.7 Bit-wise shift operators: The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.If the value of the right operand is negativeor is greater than or equal to the width of the promoted left operand,the behavior is undefined.
Please consider the following code snippet: From php-5.3.1/ext/session/session.c: ``` PHPAPI char *php_session_create_id(PS_CREATE_SID_ARGS) … gettimeofday(&tv, NULL); … /* maximum 15+19+19+10 bytes */ spprintf(&buf, 0, "%.15s%ld%ld%0.8F", remote_addr ? remote_addr : "", tv.tv_sec, (long int)tv.tv_usec, php_combined_lcg(TSRMLS_C) * 10); … return buf; } ``` I have found it on the internet. But I can't understand what code is this. I guess this is the implementation of a php function in C++. If yes, then please explain me how php calles c++ function in it?
The shocking truth is that PHP is written in C. You are looking at the source of PHP itself, or need to explain the question further.
I have to add a class object as member within a c struct. Is there any prohibition doing this. Regards, iSight
I'll assume you're talking about C++, since there is no concept of a "class" in C - although you certainly can have astructas a member of anotherstruct. Apart from one unimportant detail,classandstructare identical, and both are often referred to as "class types". Anything you can do with aclass(such as having a member of class type), you can also do with astruct. If you're interested, the only difference is the default accessibility of members and base classes;publicforstruct, andprivateforclass.
How do I do a deep copy of a python object using the C API? I know I can use copy.deepcopy, but I'd prefer to use the C API if I can.
The functionality ofcopy.deepcopy()iscompletely written in Python. I don't think they would have done this if there was a single C call to achieve the same thing, so my guess is you will have to callcopy.deepcopy().
I am doing C development in Emacs. If I have a source file open with multiple functions and "the marker" is at a function call e.g.int n = get_number(arg);is there any way I can "jump to" the implementation of that function? e.g. toint get_number(int *arg) { ... } I have done some Java development in Eclipse and is missing this functionallity, because I'm not that used to Emacs but I would like to learn.
You have to create atagfile.Under Unix, you have theetagsprogram that understands the syntax ofC,C++,Java... and that create atagfile that can be used by Emacs. This ratherold page(2004) provides more information. To jump to a function use M-. (that’s Meta-Period) and type the name of the function. If you simply press enter Emacs will jump to the function declaration that matches the word under the cursor.
This question already has answers here:Closed12 years ago. Possible Duplicate:How do I call unmanaged C/C++ code from a C# ASP.NET webpage I have a dll file that is written in "C" language, i want to use it in C#. How can i do that?
You can usePInvoke Platform Invocation Services (PInvoke) allows managed code to call unmanaged functions that are implemented in a DLL. Hereis a great tutorial by the NAG (Numerical Algorithms Group) group
Can we invoke functions of a DLL compiled for 64 bit using an application compiled for 32 bit? I am using Windows 2008 64 bit system. But, the application is still compiled using 32 bit. The code involves MFC & Windows SDK functions.
No.A 32-bit application cannot load a 64-bit module into its process space (nor vice versa). Remember that 32-bit processes are only supported on 64-bit versions of Windows in the dedicated Windows-on-Windows (WOW64) subsystem. That makes interoperability tricky at best. Raymond Chen'sblog entry on the subjectis quite instructive, if you care about the technical details. You will either need to recompile one or the other, or load it into a separate process and useinterprocess communicationto coordinate between the two.
``` #include "usefunc.h" //don't worry about this -> lib I wrote int main() { int i; string given[4000], longest = "a"; //declared new typdef. equivalent to 2D char array given[0] = "a"; printf("Please enter words separated by RETs...\n"); for (i = 1; i < 4000 && !StringEqual(given[i-1], "end"); i++) { given[i] = GetLine(); /* if (sizeof(given[i]) > sizeof(longest)) { longest = given[i]; } */ printf("%lu\n", sizeof(given[i])); //this ALWAYS RETURNS EIGHT!!! } printf("%s", longest); } ``` Why does it always return 8???
There is nostringdata type in C. Is this C++? Or isstringa typedef? Assumingstringis a typedef forchar *, what you probably want isstrlen, notsizeof. The 8 that you are getting withsizeofis actually the size of the pointer (to the first character in the string).
I'm calling a function from a DLL, like this: ``` __declspec ( dllimport ) bool dll_function(...); int main() { [...] if (dll_function(...)) { [...] } } ``` In some cases, the data I pass to the DLL function will lead to a crash of the DLL. Is it possible to catch this so my application doesn't crash as well (without modifying the DLL which is not created by me)?
You can catch AVs with the __try and __except keywords in the MSVC compiler. Not all that useful, you have no idea what kind of damage was done. The state of your program might well be corrupted. The heap might be blown for example, causing subsequent random failure. Hosting the DLL in its own process and using IPC to talk to it is the only decent approach.
As above, say I have a 3 dimensional array, a[][][], and I want to pass this to a function; how should I declare the function parameter?
``` void function1(int array[][3][4]) { ...use array here... } void function2(void) { int array[20][3][4]; ...load array... function1(array); } ```
I have previously,here, been shown that C++ functions aren't easily represented in assembly. Now I am interested in reading them one way or another because Callgrind, part of Valgrind, show them demangled while in assembly they are shown mangled. So I would like to either mangle the Valgrind function output or demangle the assembly names of functions. Anyone ever tried something like that? I was looking at awebsiteand found out the following: Code to implement demangling is part of the GNU Binutils package; see libiberty/cplus-dem.c and include/demangle.h. Has anyone ever tried something like that? I want to demangle/mangle in C. My compiler is gcc 4.x.
Use thec++filtcommand line tool to demangle the name.
I've been looking through questions on here and the internet for a while now and I cannot seem to find out whether or not it is possible to do inline assembly with GCC using something other than GAS. I am trying to find if I can avoid using not only GAS's AT&T syntax (though, I know how to use Intel syntax with GAS) but the extended asm format. While this is not for a project or anything other than my own curiosity, I would really appreciate any help I can get (this is actually my first question here because I could not find an answer about it)! Also, if this makes any difference, I'm currently using DevC++ (for C code, not C++) on Windows. Thanks, Tom
You can link the output from an assembler (a ".o" or ".obj" file) with your C or C++ program. Put your assembler code in a text file. Your IDE or makefile will assemble it just as it would any c source file. The only tricky bit is learning how to interface between the two different systems.
``` SOCKET server = socket(PF_INET,SOCK_STREAM, 0); bind(server, 7.7.7.7, sizeof(7.7.7.7) ); listen(server, 0); server.Poll(1, SelectMode.SelectRead); ``` error C2228: left of '.Poll' must have class/struct/union type The IP is not the same but the 3 functions work correctly creating a socket that the server can listen to and send data, to the client. I would like to poll the client,using this example but in C++. Which object or structure can I use here with Poll()?
Please read thisTutorial. What you are doing doesn't look close to correct.
Is it possible to pass a large Structure through JNI from C to Java? Can somebody please give me the possible solutions?
Declare a pointer to the struct in your java class like so: protected long ptrToX; Next, to set it: Get the field ID using(*env)->GetFieldID(...)Get the pointer using(*env)->GetLongField(...)Set the pointer using(*env)->SetLongField(...) To get it, just follow the first two steps mentioned above. Always remember to include a finaliser that will take care of deallocating the pointer when the object is garbage-collected. Alternatively, if you do not want to incur the performance hit incurred by using finalisers, just provide a terminate() method that deallocates the pointer.
Is there any way I can synchronize the data(data sharing) between C and Java code with JNI using mutex or any other methods. Please let me know if you have any documentation about the methods for data sharing.
You can use any lock you prefer in C and make it available to Java via JNI. You can do the reverse as well, calling a method in Java from C to use the lock. I would do it natively in the framework which created the thread.
My professor cited this example in class. Its basically a version of the Unixmorecommand, and I'm unsure about a couple things in it ``` int main( int ac , char *av[] ) { FILE *fp; if ( ac == 1 ) do_more( stdin ); else while ( --ac ) if ( (fp = fopen( *++av , "r" )) != NULL ) { do_more( fp ) ; fclose( fp ); } else exit(1); return 0; } ``` I understand that*fpdefines a file pointer, and that *av[] is the array of command line arguments. But what does*++avmean in terms of operation?
read *++av like this: ``` ++av // increment the pointer *av // get the value at the pointer, which will be a char* ``` in this example, it will open every files passed on the command line. also: ``` av[0] // program name av[1] // parameter 1 av[2] // parameter 2 av[3] // parameter 3 av[ac - 1] // last parameter ```
I want to use c/cpp functions/library in an Android application using jni. any suggestion / links / tutorials /example ? my problem with pointer/structure return in c/cpp. how to use pointer/structure in android? actually, I am trying to develop a remote desktop application through which I should be able to access my pc in android.
The Android NDK is a toolset that lets you embed components that make use of native code in your Android applications.What is the NDK Following are some link which help you to work in Android NDK Using NDK to Call C code from Android AppsAndroid Beginners: NDK Setup Step by StepWriting applications using the Android NDK
Do you know a good example of nonlinear programming?, I have search over google, but any text just formulate and do not solve the problem, They mention lingo and even excel for solving it. Could you please post an example and explain a little of if? Thanks in advance P.d You know the idea is to see some results, and numbers, using C, java. Thanks
try these (java): Example1 Example2 Example3
If I create a new NSData object of a specific size using dataWithBytes:length:, what is the most efficient way to create the input bytes (20 Mb worth) of random characters, preferably without reading the data in from a file? I need a unique buffer of a specific size each time. Thanks
You can create a 20*2^20bNSDataobject, then append a random 4 byte integer to it 20*2^20/4 times witharc4random(). I believe you need to includestdlib.h(viaGenerating random numbers in Objective-C). ``` #include <stdlib.h> -(NSData*)create20mbRandomNSData { int twentyMb = 20971520; NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb]; for( unsigned int i = 0 ; i < twentyMb/4 ; ++i ) { u_int32_t randomBits = arc4random(); [theData appendBytes:(void*)&randomBits length:4]; } return theData; } ```
Is it possible in GCC to use a struct or class as a vector type for SSE instructions? something like: ``` typedef struct vfloat __attribute__((vector_size(16))) { float x,y,z,w; } vfloat; ``` Rather than the canonical: ``` typedef float v4sf __attribute__ ((vector_size(16))); union vfloat { v4sf v; float f[4]; }; ``` Would be very handy, but I can't seem to make it work.
Could you make aunionlike the one you posted but with yourstructinstead offloat f[4];as the second member? That would give you the behavior you want.
I have a school project to develop a static analyzer in C for C. Where should I start? What are some resources which could assist me? I am assuming I will need to parse C, so what are some good parsers for C or tools for building C parsers?
I would first take yourself over toantlr, look at itsgetting started guide, it has a wealth of information about parsing etc.., I personally use antlr as it gives a choice ofcode generation targets. To use antlr you need ac or c++ grammar file, pick of these up and start playing. Anyway have fun with it..
I have written a program which calculates the amount of battery level available in my laptop. I have also defined a threshold value in the program. Whenever the battery level falls below threshold i would like to call another process. I have used system("./invoke.o") where invoke.o is the program that i have to run. I am running a script which runs the battery level checker program for every 5 seconds. Everything is working fine but when i close the bash shell the automatic invocation of invoke.o is not happening. How should i make the invoke.o to be invoked irrespective of whether bash is closed or not??. I am using UBUNTU LINUX
Try running it as:nohup ./myscript.sh, where thenohupcommand allows you to close the shell without terminating the process.
``` int *(*(*P)[2][2])(int,int); ``` P is a pointer to 2x2 array of pointers to a function with 2 type int parameters, that returns a int type pointer. Is this correct?
cdeclis a great tool for figuring these kinds of problems out: ``` $ cdecl Type `help' or `?' for help cdecl> explain int *(*(*P)[2][2])(int,int); declare P as pointer to array 2 of array 2 of pointer to function (int, int) returning pointer to int ``` So yes, you're correct.
One can design plugins in C using 2 techniques (AFAIK): Use dlopen() all the way: The core code expects all functions in library to have a known name and prototype. It dlopen()s the library and gets all the function pointers via dlsym()Keep one exposed known function which takes in a structure that is filled with implemented functions by plugin. This one function is got via dlsym() and called once in beginning. Which technique do you think is better and why? Please mention any other ways of doing this if any.
I prefer the second way, since it will be a lot easier: to load your plugin: it needs just a single call todlsym, instead of tensto handle your plugin: you can pass around the structure with the function pointers. Instead that passing tens of functions or building such a structure in the framework in order to pass it around. Remember that easier means less error-prone.
This is the problem I'm working on:http://www.codechef.com/problems/HS08TEST/ And this is my solution: ``` #include <stdio.h> int main (void) { int withdraw_i; float balance_i; scanf("%d %f", &withdraw_i, &balance_i); if(withdraw_i % 5 == 0) { if(withdraw_i <= balance_i) { float result = balance_i - withdraw_i - 0.5; printf("%.2f", result); } else { printf("%.2f", balance_i); } } else { printf("%.2f", balance_i); } return 0; } ``` (In C) It works perfectly for the tests shown on the page, but, when I submit it, I still keep getting the error "wrong answer", what's going on?
It's because you didn't implement the conditions on this test correctly. Try the case "300 300".
I'm using this code to move pointer by 1 byte now, but I'm feeling something unclear.. ``` int* a = (int*)malloc(sizeof(int)); void* b = ((char*)a)+1; ``` charis 1 byte, but not defined for byte operation purpose. I believe there's another way to do thisbyteoperation. What's thecorrectway tobyteoperation? PS. I modified sample code to be valid. It's now compiled as C++ with Clang.
I think you are confused: charis 1 byte, but not defined for byte operation purpose. I believe there's another way to do thisbyteoperation. What's thecorrectway tobyteoperation? What exactly are you expectingbyteto mean, if not the exact same thing thatcharmeans? In C and in C++, charsarebytes.By definition. What isnotthe case is thatbytesare necessarilyoctets. A byte contains at least 8 bits. There isnoguarantee that a given platform even makes itpossibleto reference a chunk of memory that isexactly8 bits.
Given atime_tas1291121400, how do I get the date of that day formatted as20101130?
Usegmtime(3)orlocaltime(3)to convert it into astruct tm(Or, better, the reentrant versionsgmtime_rorlocaltime_r), and then usestrftime(3)to turn it into a string. For example, if you want the output in UTC: ``` struct tm tm; char buf[9]; gmtime_r(&my_time_t, &tm); strftime(buf, sizeof(buf), "%Y%m%d", tm); printf("The date is: %s\n", buf); ```
I have a function which needs the quotient and remainder for an unsigned 64-bit division. It looks like lldiv and lldiv_t, whilelong long ints rather thanints, are signed. Is there an unsigned version? If not, what's the best way to handle this? Speed is important (as usual, billions or trillions of operations), but the compilermightbe smart enough to handle this properly -- I'm using gcc 4.3.3.
Just use the division and remainder operators. Any sane compiler will do a much better job optimizing them than a call todiv,ldiv, orlldiv.
I saw some C while loop with predicate as while(*ptr), and ptr is usually of char * type, how does this work? Does this mean "while()" will also accept values other than 1 or 0 as predicates?
In C, any non-zero value is considered "true", sowhile (*ptr)will loop as long as*ptris non-zero.
I'm looking to embed the Erlang VM into C code... Im familiar with ports, linkedin drivers, etc. I want the C program to start the Erlang VM, and then pass messages to Erlang processes, and have those pass messages back to C code. I dont want the erlang VM to be the one that starts first and then invokes C code occasionally. I have my reasons.I know that this negatively affects stability guarantees given by Erlang, meaning that when the master C code crashes it will taken down the Erlang VM also, since they're running in the same process. Im willing to live with those occurrences... is this even possible?
The easiest way would be to just launch it as a separate process, and then use stdin and stdout to communicate. Just reading the docs of whatever platform you're targeting will let you know how to do that.
Is this code: ``` y = x = x + 1; ``` undefined behavior in C?
Answer to your questionNo. What will happenThis will happen: ``` int x = 1; /* ASSUME THIS IS SO */ y = x = x + 1; /* Results: */ y == 2; x == 2; ``` How it compilesThe same as: ``` x += 1; y = x; ``` Why this is not undefinedBecause you are not writingxin the same expression you read it. You just set it to itself+ 1, then assignyto the value ofx. Your futureIf you find the code confusing you can use parentheses for readability: ``` y = x = (x + 1); ```
When you typecast from an int to a char, you are cutting down the number of bytes used from 4 to 1. How does it pick which byte it is going to use make the char? Does it take the most significant byte? Or does it take the least significant? Or is there some sort of rule I should know about?
C will take the least-significant byte when doing a narrowing conversion, so if you have the integer value 0xCAFEBABE and you convert it to a char, you'll get the value 0xBE. Of course, there's no actual guarantee that anintis four bytes or that acharis one, but I'm pretty sure that the logic for doing the truncation will always be the same and will just drop the higher-order bits that don't fit into thechar.
Can I use Visual Studio 2005 to compile simple C programs? There appears to be only options to create projects for VB, C# or C++. If this is possible, what do I need to do?
To give you a more concrete answer, Visual Studio will definitely compile C code under a C++ project. It will even compile it as C code, not C++ - Visual Studio treats anything with a .c extension as C code and will compile as such by default. This is confirmed in the documentation onMSDN(albeit only specified for VS2008 and VS2010). There is even a compiler command line switch (/Tc) and an option in the properties page of any .c file to compile it as C++ code, rather than the C default.
After a whole week of trying to get GTK working on Cygwin and MinGW using makefile, I've hit a stone cold wall. Does anyone please, anyone know how I can program using C and GTK libraries in widows operating system that WORKS? If there is can anyone give me step by step instructions please! The environment has to run the hello world program as an example:http://en.wikipedia.org/wiki/GTK%2B Thanks in advance!
It's a bit tricky to configure GTK+ toolchain on Windows. The easiest way is to usethis GTK+ bundle. It provide easy to use and install GTK+ runtime environment. You will find there note how to extend this runtime for developing purposes. According to GTK+'s mailing list version 2.16 is known to be the most stable, however maybe it's good idea to try newer one. Moreover go to GTK+'s home page and read threads about GTK+ & Windows 7 on the gtk-app-devel mailing list.
``` char filePath[200]; printf("Enter filepath: \n"); fgets(filePath, 200, stdin); f = fopen(filePath, "r"); while(!feof(f)) // crashed on this line { } ``` I cannot for some reason get this to work. Please could some one point out what I am doing wrong on this. Could you advice the correct way to write code for opening a filepath specified by user through command prompt? Thanks, Freddy
fopen(3)returnsNULLif it cannot open the file. You should always check for that.fgets(3)does that too, but your problem is probably the new-line character that it keeps in the returned string.
Using Linux and glibc, when originating a TCP/IP connection (calling connect() on a socket), how can I choose explicitly from which of my IP local adresses I want to originate that connection, providing I have more than one interface (with different IPs) from where I can reach the remote host? Is it possible to do so, or it is always up to the operating system IP stack to chose the route automatically?
Bind to a specific address instead of0.0.0.0or::.
are there any library similar to apache httpcomponents for c/c++ language? Thanks in advance, Dario.
I'm not sure how similar they are to those particular Apache components, but you might want to look atPOCOandACE. Both provide quite a bit in the way of networking in C++. ACE tends to be the more all-encompassing of the two (both in terms of supporting lots of protocols and such, and in terms of tending to control/dominate all of how an application is written/works). Depending on exactly what you're after, you could also look atBoost.asioand/orLibCurl.
So I have a black and white image in OpenCV, currently I output each of its per pixel color values into file so I get a file of values from 1 to 255. I have lots of really small images so in one image I usually get values that have small difference. like from 25 to 100.. So I need a way to print into file not color values but values from 0 to 1 where lowest color would be 0 and highest 1... ``` for(x=0;x<w;x++){ for(y=0;y<h;y++){ double RealColor = cvGetReal2D(source, y, x); file << RealColor << " "; } file << endl; }file << endl; ``` How to do such a thing?
Just do a first pass, and find minimum and maximum values. Then do a second pass, and modify each value as(v - min) / (max - min)before writing to file.
i need to get the terminal cursor position then set it, i already know how to set it using "move", that's in ncurses, any ideas?
Have you triedgetyx()? Or, if you prefer legacy curses functions,getcurx() and getcury()?
I'm working on a multi-platform application in C where I need to load fonts from disk and render messages with FreeType. However, I currently use full paths for locating fonts, and it's somewhat awkward to ask users for the full path of fonts since they are generally buried deep into system folders. Is there a simple, platform-idependent way of just locating fonts? E.g. I can expect users to be able to provide something like "Sans" and have a library or something locate the full path of this font for me. I'm aware of the existence of fontconfig, but I found it quite hard to go through the documentation for it. Clarification: This is a CLI driven application, which is configured through a config file.
As far as I am aware,fontconfigis the way. Keep at the docs, and find some tutorials.This pdf, while a little old, gives a very nice overview of how fontconfig does its amazingly useful job.
One can design plugins in C using 2 techniques (AFAIK): Use dlopen() all the way: The core code expects all functions in library to have a known name and prototype. It dlopen()s the library and gets all the function pointers via dlsym()Keep one exposed known function which takes in a structure that is filled with implemented functions by plugin. This one function is got via dlsym() and called once in beginning. Which technique do you think is better and why? Please mention any other ways of doing this if any.
I prefer the second way, since it will be a lot easier: to load your plugin: it needs just a single call todlsym, instead of tensto handle your plugin: you can pass around the structure with the function pointers. Instead that passing tens of functions or building such a structure in the framework in order to pass it around. Remember that easier means less error-prone.
This is the problem I'm working on:http://www.codechef.com/problems/HS08TEST/ And this is my solution: ``` #include <stdio.h> int main (void) { int withdraw_i; float balance_i; scanf("%d %f", &withdraw_i, &balance_i); if(withdraw_i % 5 == 0) { if(withdraw_i <= balance_i) { float result = balance_i - withdraw_i - 0.5; printf("%.2f", result); } else { printf("%.2f", balance_i); } } else { printf("%.2f", balance_i); } return 0; } ``` (In C) It works perfectly for the tests shown on the page, but, when I submit it, I still keep getting the error "wrong answer", what's going on?
It's because you didn't implement the conditions on this test correctly. Try the case "300 300".
I'm using this code to move pointer by 1 byte now, but I'm feeling something unclear.. ``` int* a = (int*)malloc(sizeof(int)); void* b = ((char*)a)+1; ``` charis 1 byte, but not defined for byte operation purpose. I believe there's another way to do thisbyteoperation. What's thecorrectway tobyteoperation? PS. I modified sample code to be valid. It's now compiled as C++ with Clang.
I think you are confused: charis 1 byte, but not defined for byte operation purpose. I believe there's another way to do thisbyteoperation. What's thecorrectway tobyteoperation? What exactly are you expectingbyteto mean, if not the exact same thing thatcharmeans? In C and in C++, charsarebytes.By definition. What isnotthe case is thatbytesare necessarilyoctets. A byte contains at least 8 bits. There isnoguarantee that a given platform even makes itpossibleto reference a chunk of memory that isexactly8 bits.
Given atime_tas1291121400, how do I get the date of that day formatted as20101130?
Usegmtime(3)orlocaltime(3)to convert it into astruct tm(Or, better, the reentrant versionsgmtime_rorlocaltime_r), and then usestrftime(3)to turn it into a string. For example, if you want the output in UTC: ``` struct tm tm; char buf[9]; gmtime_r(&my_time_t, &tm); strftime(buf, sizeof(buf), "%Y%m%d", tm); printf("The date is: %s\n", buf); ```
I have a function which needs the quotient and remainder for an unsigned 64-bit division. It looks like lldiv and lldiv_t, whilelong long ints rather thanints, are signed. Is there an unsigned version? If not, what's the best way to handle this? Speed is important (as usual, billions or trillions of operations), but the compilermightbe smart enough to handle this properly -- I'm using gcc 4.3.3.
Just use the division and remainder operators. Any sane compiler will do a much better job optimizing them than a call todiv,ldiv, orlldiv.
I saw some C while loop with predicate as while(*ptr), and ptr is usually of char * type, how does this work? Does this mean "while()" will also accept values other than 1 or 0 as predicates?
In C, any non-zero value is considered "true", sowhile (*ptr)will loop as long as*ptris non-zero.
I'm looking to embed the Erlang VM into C code... Im familiar with ports, linkedin drivers, etc. I want the C program to start the Erlang VM, and then pass messages to Erlang processes, and have those pass messages back to C code. I dont want the erlang VM to be the one that starts first and then invokes C code occasionally. I have my reasons.I know that this negatively affects stability guarantees given by Erlang, meaning that when the master C code crashes it will taken down the Erlang VM also, since they're running in the same process. Im willing to live with those occurrences... is this even possible?
The easiest way would be to just launch it as a separate process, and then use stdin and stdout to communicate. Just reading the docs of whatever platform you're targeting will let you know how to do that.
Is this code: ``` y = x = x + 1; ``` undefined behavior in C?
Answer to your questionNo. What will happenThis will happen: ``` int x = 1; /* ASSUME THIS IS SO */ y = x = x + 1; /* Results: */ y == 2; x == 2; ``` How it compilesThe same as: ``` x += 1; y = x; ``` Why this is not undefinedBecause you are not writingxin the same expression you read it. You just set it to itself+ 1, then assignyto the value ofx. Your futureIf you find the code confusing you can use parentheses for readability: ``` y = x = (x + 1); ```
When you typecast from an int to a char, you are cutting down the number of bytes used from 4 to 1. How does it pick which byte it is going to use make the char? Does it take the most significant byte? Or does it take the least significant? Or is there some sort of rule I should know about?
C will take the least-significant byte when doing a narrowing conversion, so if you have the integer value 0xCAFEBABE and you convert it to a char, you'll get the value 0xBE. Of course, there's no actual guarantee that anintis four bytes or that acharis one, but I'm pretty sure that the logic for doing the truncation will always be the same and will just drop the higher-order bits that don't fit into thechar.
Can I use Visual Studio 2005 to compile simple C programs? There appears to be only options to create projects for VB, C# or C++. If this is possible, what do I need to do?
To give you a more concrete answer, Visual Studio will definitely compile C code under a C++ project. It will even compile it as C code, not C++ - Visual Studio treats anything with a .c extension as C code and will compile as such by default. This is confirmed in the documentation onMSDN(albeit only specified for VS2008 and VS2010). There is even a compiler command line switch (/Tc) and an option in the properties page of any .c file to compile it as C++ code, rather than the C default.
After a whole week of trying to get GTK working on Cygwin and MinGW using makefile, I've hit a stone cold wall. Does anyone please, anyone know how I can program using C and GTK libraries in widows operating system that WORKS? If there is can anyone give me step by step instructions please! The environment has to run the hello world program as an example:http://en.wikipedia.org/wiki/GTK%2B Thanks in advance!
It's a bit tricky to configure GTK+ toolchain on Windows. The easiest way is to usethis GTK+ bundle. It provide easy to use and install GTK+ runtime environment. You will find there note how to extend this runtime for developing purposes. According to GTK+'s mailing list version 2.16 is known to be the most stable, however maybe it's good idea to try newer one. Moreover go to GTK+'s home page and read threads about GTK+ & Windows 7 on the gtk-app-devel mailing list.
``` char filePath[200]; printf("Enter filepath: \n"); fgets(filePath, 200, stdin); f = fopen(filePath, "r"); while(!feof(f)) // crashed on this line { } ``` I cannot for some reason get this to work. Please could some one point out what I am doing wrong on this. Could you advice the correct way to write code for opening a filepath specified by user through command prompt? Thanks, Freddy
fopen(3)returnsNULLif it cannot open the file. You should always check for that.fgets(3)does that too, but your problem is probably the new-line character that it keeps in the returned string.
Using Linux and glibc, when originating a TCP/IP connection (calling connect() on a socket), how can I choose explicitly from which of my IP local adresses I want to originate that connection, providing I have more than one interface (with different IPs) from where I can reach the remote host? Is it possible to do so, or it is always up to the operating system IP stack to chose the route automatically?
Bind to a specific address instead of0.0.0.0or::.
are there any library similar to apache httpcomponents for c/c++ language? Thanks in advance, Dario.
I'm not sure how similar they are to those particular Apache components, but you might want to look atPOCOandACE. Both provide quite a bit in the way of networking in C++. ACE tends to be the more all-encompassing of the two (both in terms of supporting lots of protocols and such, and in terms of tending to control/dominate all of how an application is written/works). Depending on exactly what you're after, you could also look atBoost.asioand/orLibCurl.
So I have a black and white image in OpenCV, currently I output each of its per pixel color values into file so I get a file of values from 1 to 255. I have lots of really small images so in one image I usually get values that have small difference. like from 25 to 100.. So I need a way to print into file not color values but values from 0 to 1 where lowest color would be 0 and highest 1... ``` for(x=0;x<w;x++){ for(y=0;y<h;y++){ double RealColor = cvGetReal2D(source, y, x); file << RealColor << " "; } file << endl; }file << endl; ``` How to do such a thing?
Just do a first pass, and find minimum and maximum values. Then do a second pass, and modify each value as(v - min) / (max - min)before writing to file.
i need to get the terminal cursor position then set it, i already know how to set it using "move", that's in ncurses, any ideas?
Have you triedgetyx()? Or, if you prefer legacy curses functions,getcurx() and getcury()?
I'm working on a multi-platform application in C where I need to load fonts from disk and render messages with FreeType. However, I currently use full paths for locating fonts, and it's somewhat awkward to ask users for the full path of fonts since they are generally buried deep into system folders. Is there a simple, platform-idependent way of just locating fonts? E.g. I can expect users to be able to provide something like "Sans" and have a library or something locate the full path of this font for me. I'm aware of the existence of fontconfig, but I found it quite hard to go through the documentation for it. Clarification: This is a CLI driven application, which is configured through a config file.
As far as I am aware,fontconfigis the way. Keep at the docs, and find some tutorials.This pdf, while a little old, gives a very nice overview of how fontconfig does its amazingly useful job.
I have looked through GDB documentation, but haven't found anything that works or shows what I need: the maximum amount of memory that is used by my application. I'm using MinGW-w64 (GCC for Windows) if that's relevant. I'd like something programmatically, not "look in your task manager". Also: my application executes in one go, it doesn't stop or halt anywhere, and I'd like to keep it that way. Thanks!
You could wrap malloc/free or new/delete:How-to-profile-memory-usage-of-a-c-program Thereby you can check how much memory (heap) you are using at any time.
i've an NSString like this: ``` NSString *myStr=@"7JXAX"; ``` that is equal in ASCII decimal value to {7,74,88,65,88}. So, what i want to do is to convert this NSString to an uint8_t array value like: ``` uint8_t someInt[myStr length]={7,74,88,65,88}; ``` So the question is, in which way can i convert a string to a unit8_t array? Thanks in advance.
Will[myStr UTF8String]do the job for you? i.e: ``` uint8_t *someInt = (uint8_t *)[myStr UTF8String]; ```
What arguments should i pass to wait() so that it waits for all child processes to terminate before continuing
waitonly waits for a single child. You should callwait(NULL)in a loop until it returns-1witherrno == ECHILD: ``` while (wait(NULL) != -1 || errno != ECHILD) { } ``` From thewait(2) manual page: ECHILD (for wait())The calling process does not have any unwaited-for children.EINTRWNOHANG was not set and an unblocked signal or a SIGCHLD was caught; see signal(7). As such, you must check for ECHILD, lest you be fooled by a caught signal.
``` void foo() { char *var = kmalloc(1, GFP_KERNEL); return; } ``` This code will cause kernel level memory leaks, what is the difference between this and user land memory leaks This is a question from a interview today. I did bad about this question.Can anyone give any thoughts?
Memory leaked in userspace is reclaimed at process termination, but memory leaked in kernel space cannot be reclaimed until the machine is rebooted.
I am compiling this C program and comparing the generated assembly code: ``` int main(){ return 0; } ``` GCCgives this main function (cc hello.c -S): ``` _main: LFB2: pushq %rbp LCFI0: movq %rsp, %rbp LCFI1: movl $0, %eax leave ret ``` LLVMgives this main function (clang hello.c -S): ``` _main: Leh_func_begin0: pushq %rbp Ltmp0: movq %rsp, %rbp Ltmp1: movl $0, %eax movl $0, -4(%rbp) popq %rbp ret Leh_func_end0: ``` What aremovl $0, -4(%rbp)andpopq %rbpneeded for? Moving something on the stack and popping it directly afterwards seems useless to me.
Themovl $0, -4(%rbp)instruction is dead, because this is unoptimized code. Try passing in-Oto both compilers to see what changes.
I am making an app that needs to check if certain apps are installed with a given identifier. Is there a way to do this without private symbols and without a jailbreak? Thanks.
Bumpdeveloper gives a hint of how they do iton their blog(see comment at the bottom): Q: […] How do you check wich applications the end-user have installed? I thought that apple didn't aprove apps that do that..A: […] There's not a simple way to detect which apps are installed. We use a combination of several methods. If the other app you need to detect has a custom URL registered, you can check to see if that URL exists. Otherwise, you can look for that app's process name running in the background.
I would like char, short and int types to be 1, 2 and 4 bytes width. I have included astdint.hheader into my sources. Does this guarantee that int8_t, int16_t and int32_t integer types will be of widths specified? What is the best way to achieve this?
If these types exist, they have the correct width and are encoded in two's complement. Edit: you should be able to check if the types exist with something like ``` #ifdef INT32_MAX ... #endif ``` but on all end user architectures (PC etc) these types do usually exist.
I am doing some sse vector3 math. Generally, I set the 4th digit of my vector to 1.0f, as this makes most of my math work, but sometimes I need to set it to 0.0f. So I want to change something like: (32.4f, 21.2f, -4.0f, 1.0f) to (32.4f, 21.2f, -4.0f, 0.0f) I was wondering what the best method to doing so would be: Convert to 4 floats, set 4th float, send back to SSExor a register with itself, then do 2 shufpsDo all the SSE math with 1.0f and then set the variables to what they should be when finished.Other? Note: The vector is already in a SSE register when I need to change it.
AND with a constant mask. In assembly ... ``` myMask: .long 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000 ... andps myMask, %xmm# ``` where # = {0, 1, 2, ....} Hope this helps.
I made this code in Python ``` def hitsin(a): a = a*57.3 return math.sin(a) ``` so whenever i put hitsin(x) the x converted to radian. I confuse when I put hitsin(90) the answer is not 1 or any number near 1, but negative (it was -0.9971392129043587). Am I doing it wrong? p.s: I also try to write the same kind of code in C ``` #include <stdio.h> #include <math.h> int main(){ float degree; float result; degree = 90; degree = degree*57.3; result = cos(result); printf("%f",result); return 1; } ``` But the answer is same. sincerely yours Giri
You should divide by180/pi, not multiply. In Python, you can also usemath.radians()for the conversion from degree to radians: ``` def hitsin(a): return math.sin(math.radians(a)) hitsin(90) # 1.0 ``` Furthermore, I doubt the C code gives the same result as the Python code, because it usescos()instead ofsin().