question
stringlengths
25
894
answer
stringlengths
4
863
I get an addres of string from assembler into C, and I need to get content of this address. How to do it? Google gives C++ examples with reinterpret_cast, but it not working in C (I suppose). I will appreciate if you will note needed libs too, tenx ``` #include <stdio.h> #include <stdlib.h> unsigned long const1(void); int main() { printf("Const: %d\n", const1()); return 0; } ```
If you've already got the address and you know it's a null terminated string, then all you need to do is treat it like a string. ``` printf("%s", (char*)alleged_string_address); ```
What's the most efficient/safest way to check if a string in C is made up only of spaces? Do I need to write a function myself to check or is there one in string.h that I can use?
Well, writing your own is trivial: ``` int IsSpaces( char * s ) { while ( * s ) { if ( ! isspace( * s ) ) { return 0; } s++; } return 1; } ``` Anything you use from the standard library is not likely to be much more efficient.
hi there i can compare people birthday in format YYYY-MM-DD with string (strcmp) functions. but i need compare todays date with person's birthday to display if his/her birthday is in 7 days or not_?. i searched "time.h" library but couldn't managed it. i appreciated if you can help.
I would usedifftimeon thetime_tvalues and compare against the number of seconds in a week...
Does anyone know of a free (non-GPL), decently performing compression library that supports packet oriented compression in C/C++? With packet oriented, I mean the kind of featureQuickLZ(GPL) has, where multiple packets of a stream can be compressed and decompressed individually while a history is being maintained across packets to achieve sensible compression. I'd favor compression ratio over CPU usage as long as the CPU usage isn't ridiculous, but I've had a hard time finding this feature at all, so anything is of interest.
zlib's maindeflate()function takes aflushparameter, which allows various different flushing modes. If you pass Z_SYNC_FLUSH at the end of each packet, that should produce the desired effect. The details are explained in thezLib manual. bzip2 has flushing functionality as well, which might let you do this kind of thing. Seehttp://www.bzip.org/1.0.5/bzip2-manual-1.0.5.html#bzCompress
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 adapt my old C codebases, that were written for IPv4, to work with IPv6. What do I need to change so that my C code works with both IPv4 and IPv6?
Find all code that usesinet_aton,inet_ntoa,gethostbyname,gethostbyaddr,htonl,htons,ntohl,ntohs, and any directsockaddr_inmanipulation and replace it with simple calls togetaddrinfoorgetnameinfo. This will make your code much simpler and more maintainable and IPv6 will automatically work with no additional effort.
I am looking a set of#ifdef's to check availability of__restrictkeyword for GCC and Visual Studio. I assume that it needs to check compiler version, but I don't know for which versions it was introduced. Anyone that can help me out? UPDATE: This must (and only needs to) work when compiling as C89! So I cannot rely on__STDC_VERSION__indicating C99, or C99 support.
How I fixed it: ``` #if defined(__GNUC__) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) # define SKP_restrict __restrict #elif defined(_MSC_VER) && _MSC_VER >= 1400 # define SKP_restrict __restrict #else # define SKP_restrict #endif ```
``` #include < iostream > #define MY_CHK_DEF(flag) \ #ifdef (flag) \ std::cout<<#flag<<std::endl; \ #else \ std::cout<<#flag<<" ,flag not define"<<std::endl; \ #endif int main() { MY_CHK_DEF(FLAG_1); MY_CHK_DEF(FLAG_2); MY_CHK_DEF(FLAG_3); ... } ``` complier report: main.cpp:3:24: error: '#' is not followed by a macro parameter any ideas? Thanks
You can't do it. #if, #else, and #endif must be the first tokens on the logical line. Your definition is just one logical line, so it doesn't work,
I'm curious about few things about text algorithms. For example we have binary word : 1011101110001101 And how to search for specific fixed subsequences in this word ? For example how to find longest fixed subsequence(lets call it LFS) in word which has same amount of 1's and 0's ? And another, how to find LFS with more 1's than 0's in it ? Example : word :1001010 we are searching for LFS with same amount of 1's and 0's. So this LFS would be 100101 But with more 1's than 0's we'll have : 101 How to solve this faster than O(n^2)? Chris.
You can make aTrieout of the input. That will help you find LFS strings. You can change the creation algorithm to count 1s and 0s, and then you'll easily find those numbers on the substring nodes. Look atSuffix Treeas well.. Creation = O(n)For the search, you'll probably do something like BFS which also be like O(N)
When I use__attribute__ ((weak))like inthis postI get warnings from gcc about redeclaring the symbol, while all I do is adding an attribute. Can the attribute be attached differently? The warnings I get look like this: ``` threads.c:53: warning: redundant redeclaration of ‘pthread_once’ /usr/include/pthread.h:478: note: previous declaration of ‘pthread_once’ was here ```
Yes - GCC allows you to use#pragma weakto declare symbols as weak, so you can do this instead: ``` #include <pthread.h> #pragma weak pthread_create #pragma weak pthread_mutex_init #pragma weak pthread_mutex_lock #pragma weak pthread_mutex_unlock #pragma weak pthread_mutex_destroy /* ... code ... */ ``` (Documentedhere.)
I am compiling a program for source, and it is not finding some dynamic libraries that are compiled with it. Here is the output when I run the executable. (It compiles fine) ``` dyld: Library not loaded: libipeqtcanvas.so.7.0.14 Referenced from: /Users/zrbecker/testipe/bin/./ipe Reason: image not found Trace/BPT trap ``` My question is, I know -L finds libraries while compiling, but how do I make sure the program can find the libraries when running. The libraries are located at the relative path ../lib from the executable which is in a bin directory.
You can setLD_LIBRARY_PATH(or actually,DYLD_LIBRARY_PATH, since you're on OS X) at runtime to include the library directory. export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:/path/to/lib"
Isint puts(const char*);re-entrant? Can I safely put it into a signal handler?
Hereis a table with all functions considered safe for signal handling: "The following table defines a set of functions that shall be either reentrant or non-interruptible by signals and shall be async-signal-safe." putsdoes not seem to be in that list, however perthis, it is deemed reentrant, but not async-safe, perhaps why it is not in the above mentioned list.
I'm trying to call into a C function that takes the following struct as a parameter: ``` typedef struct CSTRUCT { unsigned long* p1; unsigned long* p2; unsigned long* p3; unsigned long* p4; } CSTRUCT; ``` I need to call the function from C# and need to know the pinvoke C# equivalent for this C struct. Can anybody help?
unsigned long* p1in C is simply a pointer which you would typically declare asIntPtrin C#. That's the easy part of the process. The hard part is how to assign to the pointer. Is the pointer to memory owned by the C code? Or is it memory owned by the C# code? And who writes to that memory, the C code or the C# code? You need to know the answers to those questions before you can make forward progress.
I am using a while loop to detect the presence of a ">" symbol in an array. The loop conditional never evaluates to true. When I show the contents of the array, the ">" symbol is there by itself though. In my code, this isn't the first call to strtok. This is also only a snippet of the total code. The string to be broken up by strtok is "ls > testfile.txt". Any help would be appreciated. ``` while (userArgs[k] != ">") { k++; userArgs[k] = strtok(NULL, " "); if(userArgs[k] == ">") { break; } if (userArgs[k] == NULL){ break; } } ```
strtokreturns achar *so I guess you're trying to compare strings. You can't compare strings like that in C, usestrcmp. What you are doing now is comparing addresses, definitely not what you want.
Unsure how to tell if an overflow is possible. I am given this sample code: ``` char x; float f, g; // some values get assigned to x and f here... g = f + x; ``` Can someone please explain?
Afloat, at its highest limits (binary exponent of 127), does not have sufficient precision (23 bits) to show a difference of the largest possiblechar(127, 7 bits), and so overflow is not possible since addition will have no effect (a precision of 127-7=120 would be required).
Im just trying to share an integer between two processes, but the memory segment is initialized in program 1 and is used in program 4. Here is the initialization in program 1: ``` shmid = shmget(key, sizeof(int*), 0666 | IPC_CREAT); int *data = (int *)shmat(shmid, (void*)0,0); ``` Here I get a warning of "cast to pointer from integer of different size". Argh. Simple, I'm assuming, but I'm a big time noob with IPC. And many other things in c.... Then I pass it to another program: ``` snprintf(shmarg, sizeof(shmarg), "%n", data); pid_t pid3 = run_cmd4("/home/tropix/hw11-4", shmarg, semarg, pipe_from_p2_2, pipe_to_p5_2); ``` Not sure how to access it on the other side though. How can I get the int back in Program 4?
Pretty sure you're missing the header that definesshmat()and thus the compiler is guessing thatshmatreturns an int (not a pointer).
In each of the following statements, what are the tokens? a. x = y +++ 3;x, =, y, ++, +, 3, ; 7 tokensb. a+=c*=(d+-2)>>5&3;a, +=, c, *=, (, d, +, -, 2, ), >>, 5, &, 3, ; 15 tokens For each, state whether it is a syntactically correct expression.a. x+++yx, ++, +, y. Yes.b. x+++++yx, ++, ++, +, y. No. Just wondering if I'm counting tokens the right way. I wasn't sure if parenthesis are counted as separate tokens or not.
Yes, your proposed answers are correct. Parentheses are tokens - in the C grammer, they're one of a class of tokens calledpunctuators.
What exactly does the below statement do? ``` const char *string *string - '0' ``` Thanks!
It subtracts the value of the character'0'from the character pointed to bystring, turning it into a numerical value. So for example the character'9'will be turned into the integer9.
I would like to do some benchmarking on a few simple functions in C. ``` // Record start time // Do a bunch of work for (int i = 0; i < SOME_BIG_NUMBER; i++) mySimpleFunction(); // Record stop time ``` In my release build configuration the compiler is smart enough to optimize this away. Is there a canonical method of working with release configurations where you want optimizations enabled but still would like to force specific code to be executed? Thanks!
Use the result: ``` int accum = 0; // Record start time // Do a bunch of work for (int i = 0; i < SOME_BIG_NUMBER; i++) accum += mySimpleFunction(); // Record stop time printf("%d", accum); ```
I have a sample problem withw=1,y=7,z=0,x = ~(w && y) | y;and the solution isx = -1, but I can't figure out why? Here is my thought process:(w && y) = (1 && 7) = 1~11 in bits is0000 0001~1 in bits is1111 1110 Not sure what to do from here.
The last step is a bitwise OR so you get: ``` 1111 1110 | 0000 0111 = 1111 1111 ``` which is -1.
Is there a way to find the parameters passes to the kernel (/proc/cmdline) at boot time without reading any files in proc? I might have a process that needs to read the boot parameters before /proc is mounted.
It seems the kernel passes anything on the boot line as a arg to init- unless there is a ' = ' or a ' . ' Passing Linux boot opts to Init
I'm trying to compare two character and see which one is lexicographic longer and sorting by it problem is I'm not sure how to compare single character I tried doing it with strcmp like ``` struct example { char code; } if (strcmp(i->code, j->code) < 0) return 1; ``` warning: passing argument 1 of âstrcmpâ makes pointer from integer without a cast warning: passing argument 2 of âstrcmpâ makes pointer from integer without a cast I know that strcmp is for strings, should I just malloc and make the char code into a string instead, or is there another way to compare single characters?
charis an integer type. You comparecharobjects using the relational and equality operators (<,==, etc.).
I've been having trouble with fputs lately: when printing some strings in a text file with fputs, it happens I get other characters than A-Z, a-z, 0-9 in (chars that aren't part of the string). I made absolutely sure the strings all end with the null character. Unfortunately I can't give you more information, since I did not personally test the program, that was the feedback I received. But after I replaced fputs with fprintf it worked properly. So my question is: is fputs sort of dangerous? Have you ever had trouble with it?
fputsis not inherently dangerous. Of course without example code its hard to say what was causing the problem you were seeing.
What is an efficient way to calculate the maximum of 2 floats inside a for loop in C without using a logic statement which might stall the pipeline such asa > b ? a : b? I am working with huge 3D arrays and have tons of loop iterations.
Check what your compiler outputs, it's probably "optimal" already. For instance, ``` float foo(float a, float b) { return (a>b?a:b); } ``` Compiled with GCC 4.5,-O3, generates this assembly on x86_64: ``` Disassembly of section .text: 0000000000000000 <foo>: 0: f3 0f 5f c1 maxss %xmm1,%xmm0 4: c3 retq ``` i.e. the compiler knows a lot about the instruction set you're targeting, and the semantics of your code. Let it do its job.
``` main() { char *x="girl"; int n,i; n=strlen(x); *x=x[n]; for(i=0;i<n;i++) { printf("%s \n",x); x++; } } ``` What is the output?Please explain the output.......................o/p is : ``` irl rl l ```
The output is undefined behaviour. You modified a string literal.
I am trying to create a method that finds and replaces a string within a string but I seem to have some error at compile time with it. Could I get some help into figuring out what is going on? ``` void replaceString(char *find, char *replace) { int len_string,i; char temp[30]; len_string=strlen(find); while(1) { for(i=0;i<len_string;i++) temp[i]=fgetc(edit); temp[i+1]=NULL; /* the stricmp() is used for comparing both string. */ if(stricmp(find,temp)==0) { fprintf(edit,"%s ",replace); fclose(edit); exit(1); } fseek(edit,-(len_string-1),1); } } ``` the error I get at compile time is undefined reference to stricmp. I know it isn't proper coding convention, but edit (object of type FILE) is currently a global variable.
stricmpis Windows-specific. If you're not on Windows,strcasecmp.
Is there a way to use preprocessor keywords inside of a macro? If there is some sort of escape character or something, I am not aware of it. For example, I want to make a macro that expands to this: ``` #ifdef DEBUG printf("FOO%s","BAR"); #else log("FOO%s","BAR"); #endif ``` from this: ``` PRINT("FOO%s","BAR"); ``` Is this possible, or am I just crazy (and I will have to type out the preprocessor conditional every time I want to show a debug message)?
You can't do that directly, no, but you can define thePRINTmacro differently depending on whetherDEBUGis defined: ``` #ifdef DEBUG #define PRINT(...) printf(__VA_ARGS__) #else #define PRINT(...) log(__VA_ARGS__) #endif ```
How do you connect a GtkTreeVew and a GtkListStore? My TreeView shows the ListStore's data fine, but won't update the ListStore when the user changes a value in one of the cellrenderer widgets. The widgets behave normally but when they lose focus the value returns to normal. Would I have to write signal handlers for every cell I make or is there some setting I should be setting? I'm using glade to create these models.
Apparently the only way to do this is to catch the edited signal and handle it manually. What a shame.
I'm looking to make a custom filesystem for a project I'm working on. Currently I am looking at writing it in Python combined with fusepy, but it got me wondering how a compiled non-userspace filesystem is made in Linux. Are there specific libraries that you need to work with or functions you need to implement for the mount command to work properly. Overall I'm not sure how the entire process works.
Yup you'd be programming to the kernel interfaces, specificallythe VFS layerat a minimum.EditBetter link[1] 'Full' documentation is in the kernel tree:http://www.mjmwired.net/kernel/Documentation/filesystems/vfs.txt. Of course, the fuse kernel module is programmed to exactly the same interface This, however, is not what you'd call a library. It is a kernel component and intrinsically there, so the kernel doesn't have to know how a filesystem is implemented to work with one. [1]google was wrong: the first hit wasn't the best :)
I'm writing a fairly simple program with LEX, that after parsing a few files, parses input from a user. Now, with the files, everything works like a charm. However, when it comes to user input from stdin, LEX rules won't run until an EOF (via ctrl+D) character is sent. When I do that, LEX parses all I wrote and then waits for more input. A second consecutive EOF terminates the scanner. Thing is, I want the program to react on\n, outputting some data. Is there a way to force a scan from inside a rule, or to configure LEX buffering somehow to match this behaviour?
Solved! This did the trick: ``` %option always-interactive ``` I'm leaving this here for future reference, in case... well, who knows.
I trying to use a library (http://code.google.com/p/qxmpp/) but I can't find the name of the library to link it to. I want to understand how can you find out the name of the library to use in the linking parameters.
Looks like that is a source archive only -- no binaries included. Have you built the library from it? Where did the build process put it?/usr/libor/usr/local/libwould be usual suspects, but read the build and install documentation in the package.
Where i can find documentation about registers which assembly must preserve when a C function is called?
What you want is your system's C Application Binary Interface. Google for "C ABI" and your architecture, and you'll find it. For example,hereis one for sparc andhereis the relevant bit for AVRs.
I was going through The C programming Language by K&R. Here in a statement to print a double variable it is written ``` printf("\t%g\n", sum += atof(line)); ``` where sum is declared as double. Can anybody please help me out when to use %g in case of double or in case of float and whats the difference between %g and %f.
They are both examples of floating point input/output. %g and %G are simplifiers of the scientific notation floats %e and %E. %g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two. The output of your print statement will depend on the value of sum.
I've recently encountered a very rarely reproducible bug. If I cast a pointer that isn't nil to BOOL for some reason I get NO!!!11 I know that BOOL is typedef of signed char. Can that be a problem?
If the pointer is of the form0xNNNNNN00or (on 64-bit)0xNNNNNNNNNNNNNN00, whereNis any hex digit, then a cast toBOOL(anunsigned char) will leave you with0since it will truncate all the non-zero bits. To properly convert a pointer toBOOL, use the inequality operator: BOOL isNotNull = (myPointer != NULL);
I am doing a project in C and in that I need to process a lot of data . Is there a way to stop the program automatically after 30 minutes and then resume whenever I run the program again?
There is noautomaticway to do this. If you're on a Unix system though, you can pressCtrl+Zwhile your program is running to send it a STOP signal. It will wait until you continue again by sending it a CONT signal (the easiest way is with thefgshell command). A stopped process is still resident in memory, but is not running. There are more sophisticated ways to take a "snapshot" of a running program and save it to disk. Later, you can load the snapshot and continue execution of the program. For example, seeCryoPID.
I have to do some int -> byte conversion and switch to big endian for some MIDI data I'm writing. Right now, I'm doing it like: ``` int tempo = 500000; char* a = (char*)&tempo; //reverse it inverse(a, 3); [myMutableData appendBytes:a length:3]; ``` and the inverse function: ``` void inverse(char inver_a[],int j) { int i,temp; j--; for(i=0;i<(j/2);i++) { temp=inver_a[i]; inver_a[i]=inver_a[j]; inver_a[j]=temp; j--; } } ``` It works, but it's not real clean, and I don't like that I'm having to specify3both times (since I have the luxury of knowing how many bytes it will end up). Is there a more convenient way I should be approaching this?
Use theCore Foundation byte swapping functions. ``` int32_t unswapped = 0x12345678; int32_t swapped = CFSwapInt32HostToBig(unswapped); char* a = (char*) &swapped; [myMutableData appendBytes:a length:sizeof(int32_t)]; ```
Are there existing algorithm visualization tool for C programs? like visualizing an execution of a C program through animated execution stack.
I recommenddddfor fancy GUI debugging visualizations. It visualizes all the data structures and makes pretty graphs and gives you access to your regular debugger.
I open a file in program A. Its file descriptor is 3. Using fork followed by an execve I execute another program B, where I immediately open another file. This files descriptor is 4. If A and B was not sharing the file descriptor table then the file descriptor of file opened in B should have been 3. I need to create child processes not sharing the parents address space including open files. Thanks a lot
The childdoesn'tshare the same FD table, you simply forgot to close them in the child or mark them close-on-exec.
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. To reach thestate of the artofdimension reductionI'd like to know if there is an implementation no matter if it is pseudocode, c, java, matlab... of several algorithms or if there is some project that has some of them implemented for example I know that for PCA we can use matlab's svd() function... but a full script or something...
FastICAis a very good package for doing this sort of thing, and it's available in C++, R, Python, and MATLAB. I have used the matlab version of this package; it's simple to use and produces good output.
As in: How do you recover the memory, and delete the array to such an extent you can initialize it again later in the program? Like so: ``` char * array[][2] = { {"bla","bla","bla"}, {"blabity","blabity","bla"} } // Delete array sizeof(array) == NULL; char * array[][2] = { {"bla","bla","bla"}, {"blabity","blabity","bla"} } ```
You can't. An array defined using brackets (outside the scope of a function1) is compiled directly into your program, and therefore cannot be deallocated. You can, however, reinitialize it simply by writing the initial contents to it again. If you want to be able to create and destroy an array at will, you need to store it as a pointer and usemallocandfree. 1: Within a function, the array will be created on the stack each time the function is run, and destroyed when it exits, unless it is defined as a static variable. You still cannot deallocate it without returning.
I am trying to create a method that finds and replaces a string within a string but I seem to have some error at compile time with it. Could I get some help into figuring out what is going on? ``` void replaceString(char *find, char *replace) { int len_string,i; char temp[30]; len_string=strlen(find); while(1) { for(i=0;i<len_string;i++) temp[i]=fgetc(edit); temp[i+1]=NULL; /* the stricmp() is used for comparing both string. */ if(stricmp(find,temp)==0) { fprintf(edit,"%s ",replace); fclose(edit); exit(1); } fseek(edit,-(len_string-1),1); } } ``` the error I get at compile time is undefined reference to stricmp. I know it isn't proper coding convention, but edit (object of type FILE) is currently a global variable.
stricmpis Windows-specific. If you're not on Windows,strcasecmp.
Is there a way to use preprocessor keywords inside of a macro? If there is some sort of escape character or something, I am not aware of it. For example, I want to make a macro that expands to this: ``` #ifdef DEBUG printf("FOO%s","BAR"); #else log("FOO%s","BAR"); #endif ``` from this: ``` PRINT("FOO%s","BAR"); ``` Is this possible, or am I just crazy (and I will have to type out the preprocessor conditional every time I want to show a debug message)?
You can't do that directly, no, but you can define thePRINTmacro differently depending on whetherDEBUGis defined: ``` #ifdef DEBUG #define PRINT(...) printf(__VA_ARGS__) #else #define PRINT(...) log(__VA_ARGS__) #endif ```
How do you connect a GtkTreeVew and a GtkListStore? My TreeView shows the ListStore's data fine, but won't update the ListStore when the user changes a value in one of the cellrenderer widgets. The widgets behave normally but when they lose focus the value returns to normal. Would I have to write signal handlers for every cell I make or is there some setting I should be setting? I'm using glade to create these models.
Apparently the only way to do this is to catch the edited signal and handle it manually. What a shame.
I'm looking to make a custom filesystem for a project I'm working on. Currently I am looking at writing it in Python combined with fusepy, but it got me wondering how a compiled non-userspace filesystem is made in Linux. Are there specific libraries that you need to work with or functions you need to implement for the mount command to work properly. Overall I'm not sure how the entire process works.
Yup you'd be programming to the kernel interfaces, specificallythe VFS layerat a minimum.EditBetter link[1] 'Full' documentation is in the kernel tree:http://www.mjmwired.net/kernel/Documentation/filesystems/vfs.txt. Of course, the fuse kernel module is programmed to exactly the same interface This, however, is not what you'd call a library. It is a kernel component and intrinsically there, so the kernel doesn't have to know how a filesystem is implemented to work with one. [1]google was wrong: the first hit wasn't the best :)
I'm writing a fairly simple program with LEX, that after parsing a few files, parses input from a user. Now, with the files, everything works like a charm. However, when it comes to user input from stdin, LEX rules won't run until an EOF (via ctrl+D) character is sent. When I do that, LEX parses all I wrote and then waits for more input. A second consecutive EOF terminates the scanner. Thing is, I want the program to react on\n, outputting some data. Is there a way to force a scan from inside a rule, or to configure LEX buffering somehow to match this behaviour?
Solved! This did the trick: ``` %option always-interactive ``` I'm leaving this here for future reference, in case... well, who knows.
I trying to use a library (http://code.google.com/p/qxmpp/) but I can't find the name of the library to link it to. I want to understand how can you find out the name of the library to use in the linking parameters.
Looks like that is a source archive only -- no binaries included. Have you built the library from it? Where did the build process put it?/usr/libor/usr/local/libwould be usual suspects, but read the build and install documentation in the package.
Where i can find documentation about registers which assembly must preserve when a C function is called?
What you want is your system's C Application Binary Interface. Google for "C ABI" and your architecture, and you'll find it. For example,hereis one for sparc andhereis the relevant bit for AVRs.
I was going through The C programming Language by K&R. Here in a statement to print a double variable it is written ``` printf("\t%g\n", sum += atof(line)); ``` where sum is declared as double. Can anybody please help me out when to use %g in case of double or in case of float and whats the difference between %g and %f.
They are both examples of floating point input/output. %g and %G are simplifiers of the scientific notation floats %e and %E. %g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two. The output of your print statement will depend on the value of sum.
I've recently encountered a very rarely reproducible bug. If I cast a pointer that isn't nil to BOOL for some reason I get NO!!!11 I know that BOOL is typedef of signed char. Can that be a problem?
If the pointer is of the form0xNNNNNN00or (on 64-bit)0xNNNNNNNNNNNNNN00, whereNis any hex digit, then a cast toBOOL(anunsigned char) will leave you with0since it will truncate all the non-zero bits. To properly convert a pointer toBOOL, use the inequality operator: BOOL isNotNull = (myPointer != NULL);
I am doing a project in C and in that I need to process a lot of data . Is there a way to stop the program automatically after 30 minutes and then resume whenever I run the program again?
There is noautomaticway to do this. If you're on a Unix system though, you can pressCtrl+Zwhile your program is running to send it a STOP signal. It will wait until you continue again by sending it a CONT signal (the easiest way is with thefgshell command). A stopped process is still resident in memory, but is not running. There are more sophisticated ways to take a "snapshot" of a running program and save it to disk. Later, you can load the snapshot and continue execution of the program. For example, seeCryoPID.
I have to do some int -> byte conversion and switch to big endian for some MIDI data I'm writing. Right now, I'm doing it like: ``` int tempo = 500000; char* a = (char*)&tempo; //reverse it inverse(a, 3); [myMutableData appendBytes:a length:3]; ``` and the inverse function: ``` void inverse(char inver_a[],int j) { int i,temp; j--; for(i=0;i<(j/2);i++) { temp=inver_a[i]; inver_a[i]=inver_a[j]; inver_a[j]=temp; j--; } } ``` It works, but it's not real clean, and I don't like that I'm having to specify3both times (since I have the luxury of knowing how many bytes it will end up). Is there a more convenient way I should be approaching this?
Use theCore Foundation byte swapping functions. ``` int32_t unswapped = 0x12345678; int32_t swapped = CFSwapInt32HostToBig(unswapped); char* a = (char*) &swapped; [myMutableData appendBytes:a length:sizeof(int32_t)]; ```
Are there existing algorithm visualization tool for C programs? like visualizing an execution of a C program through animated execution stack.
I recommenddddfor fancy GUI debugging visualizations. It visualizes all the data structures and makes pretty graphs and gives you access to your regular debugger.
I open a file in program A. Its file descriptor is 3. Using fork followed by an execve I execute another program B, where I immediately open another file. This files descriptor is 4. If A and B was not sharing the file descriptor table then the file descriptor of file opened in B should have been 3. I need to create child processes not sharing the parents address space including open files. Thanks a lot
The childdoesn'tshare the same FD table, you simply forgot to close them in the child or mark them close-on-exec.
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. To reach thestate of the artofdimension reductionI'd like to know if there is an implementation no matter if it is pseudocode, c, java, matlab... of several algorithms or if there is some project that has some of them implemented for example I know that for PCA we can use matlab's svd() function... but a full script or something...
FastICAis a very good package for doing this sort of thing, and it's available in C++, R, Python, and MATLAB. I have used the matlab version of this package; it's simple to use and produces good output.
As in: How do you recover the memory, and delete the array to such an extent you can initialize it again later in the program? Like so: ``` char * array[][2] = { {"bla","bla","bla"}, {"blabity","blabity","bla"} } // Delete array sizeof(array) == NULL; char * array[][2] = { {"bla","bla","bla"}, {"blabity","blabity","bla"} } ```
You can't. An array defined using brackets (outside the scope of a function1) is compiled directly into your program, and therefore cannot be deallocated. You can, however, reinitialize it simply by writing the initial contents to it again. If you want to be able to create and destroy an array at will, you need to store it as a pointer and usemallocandfree. 1: Within a function, the array will be created on the stack each time the function is run, and destroyed when it exits, unless it is defined as a static variable. You still cannot deallocate it without returning.
A client requested that the MTU limit should be 1492. Is there a way to do it in the source code (program in C)? Is there any other way to do it in general? (ifconfig?) Why does somebody needs to modify MTU to a certain limit? What is the benefit? And the most important: By changing the MTU is there any risk to break the code?
Programmaticaly way using C: ``` int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); struct ifreq ifr; strcpy(ifr.ifr_name, "eth0"); if(!ioctl(sock, SIOCGIFMTU, &ifr)) { ifr.ifr_mtu // Contains current mtu value } ifr.ifr_mtu = ... // Change value if it needed if(!ioctl(sock, SIOCSIFMTU, &ifr)) { // Mtu changed successfully } ``` It works at least on Ubuntu, seeman netdevice.
I'm trying to implement in C some graph algorithms, using an adjacency matrix as support data structure. I need to implement a weighted graph, with weigths represented by a real number. Given that 0 and negative numbers would be a correct weight for an edge, how can I represent the absence of an edge between two nodes?
You could use instead of a number (double) a structure like this: ``` struct weight { double weight; bool edge_exists; }; ``` and create an adjacency matrix ofweight's. So ifedge_exists is false there is no reason to check theweight, otherwiseweightwill be meaningful. I would use the above if every(?)doublecould be a possible weight value.
Hi can't read the french accent (like 'é') in a text file, this is the piece of code I use to open and read the file... ``` FILE* file = fopen( [MyFileName UTF8String], "r, ccs=UTF-8"); if (file != 0) { while(fgets(buffer, 1024, file) != NULL) { NSString* string = [[NSString alloc] initWithCString: buffer]; //Do many things..... } fclose(file); } ``` I can't see where is the problem, my file is correctly encoded in UTF8... Thanks!
The fgets function in c is ASCII only, you need to use the fgetws. This is the wide version of fgets for use with multibyte encodings.
In a C program, I have a file path in a string (specifically, this is theexename stored inargv[0]). I would like to extract the file name and discard the directory path using MS Visual Studio 2005. Any built in function for that?
For reference, here's the code I implemented, supposedly Win/Unix compatible: ``` char *pfile; pfile = argv[0] + strlen(argv[0]); for (; pfile > argv[0]; pfile--) { if ((*pfile == '\\') || (*pfile == '/')) { pfile++; break; } } ```
I want to append two strings. I used the following command: ``` new_str = strcat(str1, str2); ``` This command changes the value ofstr1. I wantnew_strto be the concatanation ofstr1andstr2and at the same timestr1is not to be changed.
You need to allocate new space as well. Consider this code fragment: ``` char * new_str ; if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){ new_str[0] = '\0'; // ensures the memory is an empty string strcat(new_str,str1); strcat(new_str,str2); } else { fprintf(STDERR,"malloc failed!\n"); // exit? } ``` You might want to considerstrnlen(3)which is slightly safer. Updated, see above. In some versions of the C runtime, the memory returned bymallocisn't initialized to 0. Setting the first byte ofnew_strto zero ensures that it looks like an empty string to strcat.
I have 2 applications, one written in C and the other in Java, that suppose to run on the same machine. What is the best way to implement an IPC between them? best meaning portability, minimal user awareness (firewall popups...), etc.
I would use Sockets over loop back to start with. This allows you to send text or binary data and cleanly handle when one process starts or dies. The latency is about 20-50 micro-seconds depending on what you are doing with the data and how much you send. Sockets are platform independent and can be use in pure Java. There are millions of examples and tutorials available for Java.
As I understand correctly, besides the fact that Objective-C language is a strict superset of a "clean" C, added OOP paradigm is simulated by a set of functions partially described inObjective-C Runtime Reference. Therefore, I'm expecting a possibility to somehow compile Objective-C code in an intermediate C/C++ file (maybe with some asm inserts). Is it generally possible ?
You could use the clang rewriter to convert to C++. Not aware of a way to go to C though. The rewriter is available via the "-rewrite-objc" command line option.
Why is garbage collection rarely spoken about in languages such as Pascal and C, whereas it is very important in SML and Java?
Pascal and C don't traditionally use garbage collections. They used manual memory management instead (malloc/freefor C andnew/disposein Pascal). Garbage collection can beaddedin most languages that don't have them, but often with considerable expenses. An example of a garbage collector for C/C++ is theBoehm GC. Java, on the other hand, has been designed with garbage collection from the ground up.
I have to send a short string from ANSI C application to Java application through a socket - already done. Because its important data I have to encrypt it using password like "abc123". How should I do it in the simpliest way?
By "socket" I assume you mean a TCP/IP connection. In that case you should consider using Secure Sockets Layer (SSL). SSL pretty much solves most of the security problems associated with sending data across the wire. The only thing you need to work out is how to distribute keys to each end of the pipe. I strongly recommend that you don't roll your own system. Crypto is hard to get right so use an existing, well tested implementation. If you're talking about a Unix domain socket then you probably don't need to bother with encryption since domain sockets are just inter-process pipes.
I'm new in c. I want to create array, and after it delete it, and then put another array into it. How can I do it?
If you are looking for a dynamic array in C they are fairly simple. 1) Declare a pointer to track the memory,2) Allocate the memory,3) Use the memory,4) Free the memory. ``` int *ary; //declare the array pointer int size = 20; //lets make it a size of 20 (20 slots) //allocate the memory for the array ary = (int*)calloc(size, sizeof(int)); //use the array ary[0] = 5; ary[1] = 10; //...etc.. ary[19] = 500; //free the memory associated with the dynamic array free(ary); //and you can re allocate some more memory and do it again //maybe this time double the size? ary = (int*)calloc(size * 2, sizeof(int)); ``` Information oncalloc()can be foundhere, the same thing can be accomplished withmalloc()by instead usingmalloc(size * sizeof(int));
I need to use the function _nextafterf on Visual C++ 32 bit to compute the distance in ULP of some results compare to reference functions. C99 provides nextafterf and nextafter for float and double but these functions are not supported by Visual C++. However, Visual C++ 2010 supports _nextafterf and nextafter from but only in 64 bits... With the 32 bits model only _nextafter is support and from ... Is there a way to get _nextafterf working on Visual Studio maybe up to Visual C++ 2005? Thanks, Christophe
There is a templatized equivalentnextafterin Boost.Math, seeFinding the Next Representable Value in a Specific Direction (nextafter). The C99 functions must use suffixes f and l to distinguish float and long double versions. C++ uses the template mechanism instead.
I am new to C and I have this code: ``` f = fopen( argv[1], "rb" ); fseek( f, 64, SEEK_SET ); fpos_t pos; fgetpos (f, &pos); printf("%x", pos); ``` However, this returns 40, even though it's supposed to be returning 64. What am i doing wrong?
You are outputting 64 in hex format,"%x". Since 64=0x40, the mystery is solved!
What exactly is the purpose of using malloc hooks? And I've read it's used in memory-profiling, etc. but never really understood how.
Well, if you can hook into the behaviour of allocation functions, then you can track memory allocations for profiling and debugging. The GCC documentation on malloc hooks hasa nice little exampledemonstrating adding debug output every time the allocation functions are invoked. I'm not really sure what else to tell you... is that not reason enough?
Is there any way to check if an object file(.o file) is PIC-enabled?
Not sure how portable this is, but for x86 and x86_64, ELF format, you can usereadelf -rand look at the relocation types. For 32bit PIC code, you should have a R_386_GOTPC relocation section: ``` Relocation section '.rel.text' at offset 0x38c contains 3 entries: Offset Info Type Sym.Value Sym. Name 00000004 00000902 R_386_PC32 00000000 __i686.get_pc_thunk.cx 0000000a 00000a0a R_386_GOTPC 00000000 _GLOBAL_OFFSET_TABLE_ 00000010 00000803 R_386_GOT32 00000000 f ``` No such section section should exists for non-PIC.os. (You'll also see a global offset table in thereadelf -soutput.) For 64bit, same thing but with aR_X86_64_GOTPCRELrelocation type. I'm pretty sure all the relocation type names are directly indicative of whether the code is PIC or not, but I can't find a reference right now.
My ipad application has a custom look. It uses text labels extensively for displaying partly colored/shadowed/bold texts. Larger pieces of text may contain numbered lists and embedded Images. There could be couple rich text regions on a single page. I am not sure that UIWebView is the right tool for displaying strings like: MyApptitle Hellorichtextworld List itemList item Writing my own text rendering engine looks more sufficient to me than using UIWebView. Any ideas for lightweight rich text renderer ? c library or custom control ?
I would recommend usingTTStyledLabelfrom theThree20library. It provides the desired functionally and would save you the time of writing your own.
The below fails to compile: ``` typedef int arr[10]; int main(void) { return sizeof arr; } sizeof.c:3: error: expected expression before ‘arr’ ``` but if I change it to ``` sizeof(arr); ``` everything is fine. Why?
According to 6.5.3, there are two forms forsizeofas the following: ``` sizeof unary-expression sizeof ( type-name ) ``` Sincearrin your code is atype-name, it has to be parenthesized.
This question already has answers here:Closed12 years ago. Possible Duplicate:what's the mechanism of sizeof() in C/C++? Hi, I'm a TA for a university, and recently, I showed my undergraduate students the following C code from a C puzzle I found: ``` int i = 5; int j = sizeof(i++); printf("%d\n%d\n", i, j); ``` I just have one question: why is the output for i equal to 5, not 6? Is the ++ simply disregarded? What's going on here? Thanks!
The expression in a sizeof is not evaluated - only its type is used. In this case, the type is int, the result of what i++ would produce if it were evaluated. This behavior is necessary, as sizeof is actually a compile-time operation (so its result can be used for things like sizing arrays), not a run-time one.
I want to design a timer in Linux, but due to some system constraints and design requirements i cannot use the POSIX timer APIs. Can somebody kindly let me know, what are the other timer design mechanisms available in Linux apart from the POSIX timers? (timer_create, timer_settime etc to avoid) Thanks in advance. EDIT: P.S: Any mechanism you provide, requesting you to kindly give me some useful links or example links NOTE: We can't use any third party library (Like ACE library) as our code is a proprietory code.
Check out myanswer. One of the timers I find useful istimerfd_create()API provided in Linux system call. This blends well when your application is structured on an event loop.
Suppose, i know the process of my parent id and would like to ``` kill(my_parent_id, SIGTERM) ``` As a parent process, how can i catch this signal?
Register to catch the signal: ``` void termination_handler(int sig) { /* do something */ } struct sigaction handler; handler.sa_handler = termination_handler; sigemptyset (&handler.sa_mask); handler.sa_flags = SA_RESTART; sigaction(SIGTERM, &handler, NULL); ``` Here is a goodexample page. You could use the old style, but it is not suggested: ``` void termination_handler() { /* do something */ } signal(SIGTERM, termination_handler); ```
We're running a Linux server with Microsoft SQL Server for the database. Are there any good (preferably open source) c libraries that we could use other than FreeTDS? Thank you
Not really. Sybase has some client libraries, but they only work for older versions of MS SQL Server (since it is a derivative of Sybase SQL Server).
What is the purpose of this block in stdint.h (from newlib)? ``` #if defined(__GNUC__) && \ ( (__GNUC__ >= 4) || \ ( (__GNUC__ >= 3) && defined(__GNUC_MINOR__) && (__GNUC_MINOR__ > 2) ) ) /* gcc > 3.2 implicitly defines the values we are interested */ #define __STDINT_EXP(x) __##x##__ ``` This macro is used later in the header for integer comparison but I'm not sure how it is supposed to evaluate. For example: ``` #if __STDINT_EXP(LONG_MAX) > 0x7fffffff ```
##is the cpp (C Preprocessor) operator to concatenate tokens, ie. ``` #if __STDIN_EXP(LONG_MAX) > 0x7fffffff ``` evaluates to ``` #if __LONG_MAX__ > 0x7fffffff ``` in the first step.
Suppose I define the following: ``` unsigned char temp[2][13]; ``` What is the default values will be assign to thischar[]? Is it like{'', '', '', ... , ''}? In my program (The calculator), I haveoperand[2][13](where first operand isoperand[0]and second operand isoperand[1]) and I have Operation andResult[15]and they are allunsigned char. Fisrt, the user will enter Operand1 and Operand2 (A char at a time) and it will be stores inoperand[2][13]then the program will store the result as chars inResult[15]. Now what I want is, at next iteration, I want to clearoperand[2][13], operation andResult[15]so that the user can enter next operands and the program executes next operation and saves the result inResult[15]. How can I clear these arrays?
memset(operand, 0, 2 * 13);memset(Result, 0, 15);
I am writing a multithreaded application and would like to pass around pointers to a struct. Do the structs in the struct need to be malloced or if the outer struct is malloced will it prevent the internal structs from being deleted or lost when passing around the pointer? Struct I am asking about is ``` struct thread_data { position starttile; position destinationtile; char *message; }; ``` where position is a struct itself that contains no pointers
If the struct contains child structs, then it is generally all one block of memory. And so there would be no separate allocation. If the struct instead contains pointers to structs, then my previous comment would not apply. In this case, it kind of depends on what you are doing. Had you considered posting a tiny bit of code so people would have a clue what you had in mind.
Can anyone recommend a good library I could use on Linux to watermark videos? I want to overlay a watermark at several different positions in my videos, fade them in randomly and with different colors and opacity.
Have you triedffmpeg? That's a very good tool for video related stuff. Also for watermarking you can try thislink.
For some odd reason I was copying an example in another language of which does not use types, and forgot to add one in to a function definition parameter, and it worked. ``` #include <stdio.h> char toChar(n) { //sizeof n is 4 on my 32 bit system const char *alpha = "0123456789ABCDEF"; return alpha[n]; } int main() { putchar(toChar(15)); //i.e. return 0; } ``` I am sure that main defaults to int by most compilers of some standard (but only return), is this also a behaviour true for other functions as well or is this implementation defined? It seems just out of the ordinary, my compiler is just a slightly outdated GCC port (MinGW).
K&R-style function declaration: ``` void foo(n) int n; { } ``` If type isn't specified, it defaults to int. This is valid in C89, not C99
I am wondering if there is an equivalent to C's fputc in PHP? I am trying to do the following C code in PHP: ``` fputc(0x10, fp); ``` more information on fputc:http://en.wikipedia.org/wiki/C_file_input/output#Writing_to_a_stream_using_fputc Thanks
You can write the character code directly to the file: ``` fputs($fp, "\x10"); // or fputs($fp, chr(16)); // or fputs($fp, chr(hexdec(10)); ```
in my code I work with Ethernet MAC addresses and need to compare for a 00:00:00:00:00:00 address; the easiest solution I came up with is this: ``` #define ETH_ADDR_LEN 6 unsigned char mac[ETH_ADDR_LEN] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 }; /* example */ const unsigned char empty[ETH_ADDR_LEN] = { 0, }; if (memcmp(mac, empty, ETH_ADDR_LEN) == 0) { .... } ``` Is there a more concise way to achieve my goal? Simply memcmp(mac, "", 6) won't work -- may I know why? Thanks in advance!
There is nothing wrong with your code. Keep it as it is. The "empty" array contains 6 zeroes so it will work just fine.
Let's say I've got that: ``` char *p = NULL; ``` I'm sure this one would be a problem as I'd be dereferencing aNULLpointer: ``` *p = 16; ``` On the other hand, I think this one would be OK for I'd be getting the address of *p which is notNULLitself: ``` char **pp = &p; ``` Am I right in both cases?
Yes you are. Although the value of p is NULL, it still has a valid address, so you may pass its reference.
The pthread functions take a void * argument. How can a plain struct, not a pointer be sent in? I want to send in a non pointer struct to one pthread function. Also I want to send a pointer to the void * function, how is this done? can any pointer be sent in to the void * function?
Not possible; you have to send a pointer. However, avoid *can point to anything. If your struct variable is calledfoo, you can simply pass it as(void *) &foo, and inside the function, you can cast it back into e.g. astruct Foowithstruct Foo * fooPtr = (struct Foo *) param;orstruct Foo foo = *((struct Foo *) param);. Edit: As @forsvarir mentioned in the comment,foomust notbe a local variable (unless the invoking function waits for the thread to complete). See @Gavin Lock's post.
I am trying to make a prog which can record voice and store it in digital audio format on LINUX using ALSA. (currently using Ubuntu). While looking for some help on net, I found this code fromhere ``` #include "formats.h" ... ... WaveChunkHeader wch, ch = {WAV_FMT,16}; WaveHeader h; WaveFmtBody f; wch.type = WAV_DATA; ... ... ``` However, I don't have "formats.h" header file on my system. Any one know from where(which dev pkg) I can get this header file (containing audio file format related info)? Thanks, Vikram
it should be in the alsa-utils package, subdirectory aplay: http://alsa-utils.sourcearchive.com/documentation/1.0.17/formats_8h-source.html
I'm having a problem with using the automatic formatting in Eclipse CDT. For the most part it works great but it seems to insist on putting the semicolons after macro calls on a separate line. Is this a bug or did I mischeck a combination of formatting settings which lead to this?
The problem has been fixed in later versions of Eclipse CDT. Just try to download later version of Eclipse.
I have created an 'External Build Project' in Xcode 4 using a makefile. The project builds perfectly, except the only way I know how to get it to run is in Terminal. Is there a way I can run the program in Xcode 4 or is Terminal it ?
Yes, you can! Product -> Edit scheme Select "Run" from the left panel, select "Info" from top and specify "Executable" drop list Select next pane "Arguments" and add "Arguments Passed On Launch" (to "Executable" you select before)
Suppose I have: ``` Operand[2][4] = {{"1", "2", "3", "4"},{"5", "6", "7", "8"}}; ``` and I have some bit variables called Operand1_sign and Operand2_sign (0: positive and 1: negative) suppose they are: ``` Operand1_sign = 0; Operand2_sign = 1; ``` How can I convert this into 2 integers and apply some operation on them (such as summation) i.e. ``` signed int Operand1, Operand2, Result; ``` so finally I can get the following: ``` Operand1 = + 1234; Operand2 = - 5678; Result = Operand1 + Operand2; ```
Instead of answering, I'll give you a clue: the number1234can also be expressed as1 * 1000 + 2*100 + 3*10 + 4*1- this is the key to parsing numbers :)
I hope that this makes sense.... is there a way to get xCode to use the makefile system for building C programs??
Yes - set up an "external build system" project.
WCHAR wszName; In the debugger displays multiple "squares" and each addressed 0xcdcd ``` printf("Description: %ws\n", pIfRow->wszName); //prints nothing ``` Is there a reason it can not get the name from XP?(All other info inMIB_IFTABLEis correct) Thanks
0xcdcdcdcd indicates that wszName was never initialized. It is the default value of heap-allocated memory in the Debug build. Review the code that copies a string into wszName, it is not working. Presumably the call to GetIfTable() failed or you're iterating the table wrong.
I need to control C-State configuration. Specifically, I'd probably like to execute the following asm code: ``` __asm { rdmsr and eax, 0x00 or eax, 0x01 wrmsr } ``` Currently, I got this exception onrdmsrline: ``` Unhandled exception at 0x00e3139e in MessWithCStates.exe: 0xC0000096: Privileged instruction. ``` How can I (permanently) elevate priviliges of my app so it could execute the code above? I use VS 2010. NOTE: It is possible without writing a kernel-mode driver. SeeR/W Everything.
Chances are, you are running this code on an x86 processor within Ring 3. You do not have the privileges to execute this command. Period. This is a hardware limitation. The only way to execute that instruction is to go into Ring 0 and chances are, your OS won't let you do that. You will need to write a kernel-mode driver to accomplish this. Edit:http://faydoc.tripod.com/cpu/rdmsr.htmhas more info.
In C, how to do you call a function from just having its name as a string? I have this: ``` int main(int argc, const char *argv[]) { char* events[] = { "test", "test2" }; int i = 0; for (; i < 2; ++i){ char* event = events[i]; // call function with name of "event" } return 0; } ```
You can do it, but there's not much built-in to help out. ``` typedef struct { char *event_name; void (*handler)(); } event_handler; ``` then search through an array (or whatever) ofevent_handlers, and when you find the right name, call the associated function.
Does it even matter?Const before or const after?I'm guessing that whether I putconstbefore or afterCGFloatit makes the value ofCGFloatconstant, but what about the pointer? Is this right for Objective-C: ``` // Example.h extern CGFloat const kPasscodeInputBoxWidth; // Example.m CGFloat const kPasscodeInputBoxWidth = 61.0f; ```
It can go either before or after. In the case of a pointer, what matters is whether theconstends up before or after the asterisk: ``` const int *a; // pointer to const int -- can't change what a points at int const *a; // same int *const a; // const pointer to int -- can't change the pointer itself. // Note: must be initialized, since it can't be assigned. ```
I saw somewhere assert used with a message in the following way: ``` assert(("message", condition)); ``` This seems to work great, except that gcc throws the following warning: ``` warning: left-hand operand of comma expression has no effect ``` How can I stop the warning?
Use-Wno-unused-valueto stop the warning; (the option-Wallincludes-Wunused-value). I think even better is to use another method, like ``` assert(condition && "message"); ```
In C or C++ if I want to modify the filesystem permissions of a file I can us a standard library function (chmod), which is very similar to the utility that one can execute from the UNIX prompt. Is there an equivalently simple way to set the selinux context for a file? If so, what libraries do I need to link to and what header files need to be included? Something which is similarly simple to use as the command line utility chcon would be ideal.
``` #include <selinux/selinux.h> typedef char *security_context_t; int setfilecon(const char *path, security_context_t con); ``` is probably the function you are looking for. You have to link against libselinux.
This question already has answers here:Closed12 years ago. Possible Duplicate:Computational complexity of Fibonacci Sequence Hi, I found out a inductive proof yesterday for the time complexity of a recursive Fibonacci program.The proof first claimed that the complexity is exponential(and later goes on to prove it by induction) by saying that: There exists a "r" such that f(n) >= r^n for all r>=1 and n>=1.Then it chooses r to be equal to 1+sqrt(5)/2 such that it satisfies the equation r^2 = r + 1.(It later justifies it's choice for r).And then it says that now the statement becomes f(n) >= r^(n-2). I didn't understand this part how does it become r^(n-2) from r^n.Can someone please help me with that.
As Daniel says,ris greater than 1 sor^nis greater thanr^(n-1)which is greater thanr^(n-2)etc... So you have indeed:f(n) >= r^n >= r^(n-1) >= r^(n-2)
is it possible in java to have a C like syntax for this: ``` int counter = 10; while(counter){ System.out.println(counter--); } ``` In C it is working very well to count until the counter is 0... do i really have to write ``` int counter = 10; while(counter!=0){ System.out.println(counter--); } ``` ?
No, java requires abooleanin awhilecondition.
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. % operator isn;t working in objective. I am doing simple seconds to minute:second conversion. the modulus operator isn't working it is giving me error "Invalid operands to binary %" what does that mean and what can I do to fix this. thanks TC
Modulas operator only works for integers..Check whether your operands are floats..If they are floats or doubles, you can usefmodfinstead..
In C, I can use the following form inside a method. ``` void foo() { struct { int val; int color; string desc; } ItemMap[] = { { 1, 2, "test"}, { 2, 3, "test"}, } // process tasks according to ItemMap. } ``` If I want to do the same thing under C#, how to achieve it ?
You could use anonymous types for that in C#: ``` var ItemMap = new[] { new { val = 1, color = 2, desc = "test" }, new { val = 2, color = 3 , desc = "test" } }; string description = ItemMap[0].desc; ``` This would however create a one-dimensional array of ananonymous classfor you not a struct - also it is read only. If you specifically need a struct / value type that is mutable, you will have to declare the struct outside of your method.
Here is what I have to find the kth smallest value in a binary search tree: ``` struct treeNode { int data; struct treeNode *left, *right: }; int rank(stuct treeNode* ptr, int k) { if(node == NULL) return root; while(ptr->left != NULL) { ptr = ptr->left; return rank(ptr->left) } } ``` This is obviously not correct. Without providing the solution, could someone guide me in the right direction as to how I could solve this? I am having trouble figuring out how I could find the kth smallest element in a BST.
A BST is a sorted binary tree, an in-order traversal (left subtree, current node, right subtree) will give sorted node values. To find the kth smallest node, just do an in-order traversal with a counter. The counter starts from 0, whenever a node is traversed, increase it by one, when it reaches k, the node is the kth smallest one.
I have several equations that will return the binary value for each of the three bits in my number. I am programing this in C which is a new language for me. So let's say my equations returnY0 = 1,Y1 = 0andY2 = 1(101); I want to store that value as5. Is this possible in C if these values are returned by different equations? I know how to do it by multiplying, but I am looking for a function or something which I imagine is already built into C.
No such luck. You have to multiply (or shift, which is the same) ``` unsigned Y0 = 1, Y1 = 0, Y2 = 1, val; val = (Y0 * 4) + (Y1 * 2) + (Y2 * 1); /* parens */ val = (Y0 << 2) + (Y1 << 1) + (Y2 << 0); /* redundant */ ```