question
stringlengths
25
894
answer
stringlengths
4
863
How can I add a speciific directory to the search path using the C API? And a related question: will the changes be local to the application, or is the search path global?
UsePySys_GetObject("path")to retrievesys.path, then manipulate it as you wouldany other sequenceorlist. Changes will be local to the Python interpreter/VM.
Here I am trying to swap two characters in a string using XOR operation. But GCC compiler throws me asegmentation fault. ``` #include <stdio.h> #include <stdlib.h> int main() { char *str = "welcome"; str[0] = str[0] ^ str[1]; // Segmenation fault here str[1] = str[0] ^ str[1]; str[0] = str[1] ^ str...
You can't change literals in C.strpoints to read-only memory. Try instead: ``` char str[] = "welcome"; ``` There is aC FAQon the subject.
i am trying to open a file in append mode using open() api call , however following code is not working ! Its not writing anything to file! here is my code :
O_APPENDis not a mode by itself; it's a flag. Since the value ofO_RDONLYis 0, it's like you're trying to open the file read-only but for append, which is nonsense. UseO_WRONLY|O_APPENDorO_RDWR|O_APPEND.
I am new to Linux development and I have to work with Mono project on Linux. I have the following function declaration: ``` static MonoString *ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name, gboolean assembly_qualified) { MonoDomain *domai...
Grep and find can do it but I think they're no the best tool for it. You'd be better off using ctags:http://ctags.sourceforge.net/. Do this from the top level directory of your project: ``` $ ctags -R * $ vi -t MonoReflectionType ``` I hope you're familiar with vi though ;)
``` int main() { unsigned int b; signed int a; char z=-1; b=z; a=z; printf("%d %d",a,b); } ``` gives -1 -1. why does no sign extension occur, ALSO, when does it occur?
Sign extension DID occur, but you are printing the results incorrectly. In your printf you specified%dforb, butbis unsigned, you should have used%uto printb. printf does not know the type of its arguments and uses the format specifies to interpret them. ``` printf("%d %u",a,b); ```
I'm having this problem. ``` char buffer[100]; buffer[0] = "\n"; ``` For some reason, the following statement is true ``` buffer[0] == 'T' ``` When it should be the "\n" ascii. Why?
"\n"is a C string, that is achar *pointing at a null terminated series ofcharelements. Your program takes the address of that string, and stores the lowest 8 bits intobuffer[0]. In your case they happen to be the ASCII code forT. Try the following: ``` char buffer[100]; buffer[0] = '\n'; ``` '\n'is acharliteral, so...
I try to use erlang nif, I made: ``` #include <erl_nif.h> ``` But get error: fatal error: erl_nif.h: No such file or directory Where can i find it? I have installed erlang R14B (erts-5.8.1) OS Arch linux. Thank you.
Compile with-I/usr/lib/erlang/erts-5.8.1/include, if that's whereerl_nif.his.
I'm creating a very basic C console application in Xcode 4 and I'm hitting a warning on compile:Implicit declaration of memcmp is invalid in c99. My use of the function is as you would expect: ``` if(memcmp(buf, block, 0x14) != 0) { fclose(fh); printf("invalid file: %s\n", argv[argc-1]); return 1; } ``` ...
You forgot to#include <string.h>, which contains the declaration ofmemcmp.
Suppose you have a .cpp file (that is, compiled using a C++ compiler like MSVC). In that file, you define astructin the following way: ``` struct Pixel { float x, y; }; ``` In the same file, you have a line of code that will call a C function, that requires a Cstructequal toPixel. If you write: ``` Pixel my_pixe...
If the header file is correct, it will work, assuming the C compiler and the C++ compiler use compatible calling conventions. Make sure the header file has an appropriateextern "C"block that contains the function definition.
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.Closed11 years ago. I was thinking to develop an image ...
This site might be helpful for yougoogle OCRsample code
i am trying to open a file in append mode using open() api call , however following code is not working ! Its not writing anything to file! here is my code :
O_APPENDis not a mode by itself; it's a flag. Since the value ofO_RDONLYis 0, it's like you're trying to open the file read-only but for append, which is nonsense. UseO_WRONLY|O_APPENDorO_RDWR|O_APPEND.
I am new to Linux development and I have to work with Mono project on Linux. I have the following function declaration: ``` static MonoString *ves_icall_System_MonoType_getFullName (MonoReflectionType *object, gboolean full_name, gboolean assembly_qualified) { MonoDomain *domai...
Grep and find can do it but I think they're no the best tool for it. You'd be better off using ctags:http://ctags.sourceforge.net/. Do this from the top level directory of your project: ``` $ ctags -R * $ vi -t MonoReflectionType ``` I hope you're familiar with vi though ;)
``` int main() { unsigned int b; signed int a; char z=-1; b=z; a=z; printf("%d %d",a,b); } ``` gives -1 -1. why does no sign extension occur, ALSO, when does it occur?
Sign extension DID occur, but you are printing the results incorrectly. In your printf you specified%dforb, butbis unsigned, you should have used%uto printb. printf does not know the type of its arguments and uses the format specifies to interpret them. ``` printf("%d %u",a,b); ```
I'm having this problem. ``` char buffer[100]; buffer[0] = "\n"; ``` For some reason, the following statement is true ``` buffer[0] == 'T' ``` When it should be the "\n" ascii. Why?
"\n"is a C string, that is achar *pointing at a null terminated series ofcharelements. Your program takes the address of that string, and stores the lowest 8 bits intobuffer[0]. In your case they happen to be the ASCII code forT. Try the following: ``` char buffer[100]; buffer[0] = '\n'; ``` '\n'is acharliteral, so...
I try to use erlang nif, I made: ``` #include <erl_nif.h> ``` But get error: fatal error: erl_nif.h: No such file or directory Where can i find it? I have installed erlang R14B (erts-5.8.1) OS Arch linux. Thank you.
Compile with-I/usr/lib/erlang/erts-5.8.1/include, if that's whereerl_nif.his.
I'm creating a very basic C console application in Xcode 4 and I'm hitting a warning on compile:Implicit declaration of memcmp is invalid in c99. My use of the function is as you would expect: ``` if(memcmp(buf, block, 0x14) != 0) { fclose(fh); printf("invalid file: %s\n", argv[argc-1]); return 1; } ``` ...
You forgot to#include <string.h>, which contains the declaration ofmemcmp.
Suppose you have a .cpp file (that is, compiled using a C++ compiler like MSVC). In that file, you define astructin the following way: ``` struct Pixel { float x, y; }; ``` In the same file, you have a line of code that will call a C function, that requires a Cstructequal toPixel. If you write: ``` Pixel my_pixe...
If the header file is correct, it will work, assuming the C compiler and the C++ compiler use compatible calling conventions. Make sure the header file has an appropriateextern "C"block that contains the function definition.
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.Closed11 years ago. I was thinking to develop an image ...
This site might be helpful for yougoogle OCRsample code
I want to write some straight C code that uses some Foundation types. For now, I want to use NSInteger, NSUInteger, and NSRange; I can imagine wanting others later. Is there a header somewhere I can import that will get me these types without causing trouble in a straight C file?
Not Foundation, but you can use Core Foundation (<CoreFoundation/CoreFoundation.h>or more specificallyCFBase.h), and the equivalent typesCFIndex,CFRange, etc.
I came across this question, while reading aboutstd::array and std::vector.
A C-Style array is just a "naked" array - that is, an array that's not wrapped in a class, like this: ``` char[] array = {'a', 'b', 'c', '\0'}; ``` Or a pointer if you use it as an array: ``` Thing* t = new Thing[size]; t[someindex].dosomething(); ``` And a "C++ style array" (the unofficial but popular term) is ju...
I'm trying to print a new line withTextOutfunction. I tried ``` TextOut(hDC, 10, 20, "Hello\nWorld", strlen(text)); ``` But the output is "HelloWorld". How can I print new line withTextOut?
Simple.TextOutdoes not have any formatting capabilities. UseDrawTextinstead. See formatting flags to center text, calculate rectangle and so forth. You do not have to useDT_EDITCONTROLflag to accomplishDrawTextformatting. For example, ``` HDC dc = ::GetDC(0); RECT rc; char *lpsz= "Hello\r\nWorld"; ::SetRect(&rc,0,0,3...
Let assume we have such URL: ``` dvb://1.3f3.255c.15 ``` my question is how to parse this address in following way: ``` val1 = 1 val2 = 3f3 val3 = 255c val4 = 15 ``` First idea is to usestrchr()from standard C library, but maybe done it before. I would like to make it as simple as possible. When I will succeed I w...
You could usestrtok ``` char dvb_url[] = "dvb://1.3f3.255c.15"; //Begin stripping the scheme (dvb:/) char *tokenized = strtok(dvb_url, "/"); //Finish stripping scheme tokenized = strtok(NULL, "/."); while(tokenized != NULL) { //Store in variable here printf("%s\n", tokenized); tokenized = st...
It might be a very naive question but i am a bit stuck. I am writing my first opengl programme and I want to pick up the R value of a pixel, of a point that i got from mouse click. I am clueless about how to use glReadPixels function. ``` void myMouseFunc( int button, int state, int x, int y ) { if ( button==GLUT...
The documentation is pretty clear: http://www.opengl.org/sdk/docs/man/xhtml/glReadPixels.xml ``` GLubyte pixel; glReadPixels(x, windowHeight - y - 1, 1, 1, GL_RED, GL_UNSIGNED_BYTE, &pixel); ```
What's the difference under the covers between using: ``` socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); ``` and ``` socket(AF_INET, SOCK_STREAM, 0); ``` I had a reason to use a stream socket within an application and was told to use the 2nd one (which I'm guessing is because TCP would be overkill since its in-box and...
There is no difference. Both will return a TCP socket, because TCP is the default STREAM protocol of INET family.
I'm working on a C application that has to walk $PATH to find full pathnames for binaries, and the only allowed dependency is glibc (i.e. no calling external programs like which). In the normal case, this just entails splitting getenv("PATH") by colons and checking each directory one by one, but I want to be sure I co...
One thing that once surprised me is that the empty string inPATHmeans the current directory. Two adjacent colons or a colon at the end or beginning ofPATHmeans the current directory is included. This is documented inman bashfor instance. It also is in thePOSIX specification. So ``` PATH=:/bin PATH=/bin: PATH=/bin::...
I am trying to write a file to open a file and read the contents of that file in C. I am using xcode but the file pointer returns a value null. ``` int main(int argc, char** argv) { FILE *fp; fp=fopen("input.txt","r"); if (fp==NULL) printf("error"); } ``` This shows error as the output. Could...
The file would need to go in the "current directory" where the program is launched. This is configurable. In the "Groups and Files" pane, expand "Executables" and pick your executable. Press Command-I to open the info window. Near the bottom of the "General" tab, you can select the current directory for when the appli...
I am trying to use aGHashTablein my code. I will be using anintas my key and a structure as my value. My questions: Will I have to allocate memory for theintI am using as a key, or can I just use a local variable in the functions for insert and lookup?What doesg_int_to_pointerdo?If I am writing aGDestroyFunction, wil...
GINT_TO_POINTER(mind the capital letters) packs a 32-bitintinto the space of a pointer, which may be 32 or 64-bit. You can use this macro to passints as theuser_dataparameter of a signal, while avoiding allocating memory for them, for example. Then in the signal handler, useGPOINTER_TO_INTto get your int back. Don't t...
I'm writing a multithreaded server using Ptrheads and I want to trace the execution of individual threads. What would be a good tracing library for this?
cTraceis an good option.
As the title says, is there a way to force GCC to warn me when I do something like this: ``` void do_something(int* ptr) { // do something } int main() { int a = 123; void* b = &a; // WARN HERE: do_something(b); } ```
Use-Wc++-compat. From theGCC manual: -Wc++-compat (C and Objective-C only)Warn about ISO C constructs that are outside of the common subset of ISO C and ISO C++, e.g. request for implicit conversion from void * to a pointer to non-void type.
I need to write a program using system calls to read a file, reverse the string and print it out to an output file. If the input file istest.txt, output should be written to filereverse_test.txt. Please let me know how I can append the stringreverse_to the name of the output file where I would be writing the results. ...
You can't append to the literal "reverse_". Try something like this: ``` char str[ENOUGH] = {0}; snprintf(str, sizeof(str), "reverse_%s", argv[1]); ```
In C I saw this code: ``` struct stud{ int b:3; }; ``` This was compiling in gcc. What do variablesband3represent? Also, please explain the use of:. Are there anymore signs like this?
It means thatbuses 3 bits of the int. The term is "bit field". Usually this is combined with other variables using other bits of the same or other ints. The idea is to either pack values harder to save space, or more common to match the data from some hardware device.
This is a question similar toProper way to close a blocking UDP socket. I have a thread in C which is reading from a UDP socket. The read is blocking. I would like to know if it is possible to be able to exit the thread, without relying on the recv() returning? For example can I close the socket from another thread an...
This really depends on what system you're running under. For example, if you're running under a POSIX-compliant system and your thread is cancelable, the recv() call will be interrupted when you cancel the thread since it's a cancel point. If you're using an older socket implementation, you could set a signal handler...
While readinghttp://en.wikipedia.org/wiki/C_preprocessor#Multiple_evaluation_of_side_effects, I came across this example: ``` \#define max(a,b) \ ({ typeof (a) _a = (a); \ typeof (b) _b = (b); \ _a > _b ? _a : _b; }) // WHY DOES THIS LINE WORK? ``` Which you can use exactly like a function, i.e.max(1,...
This is a GCC extension calledStatement Expressions. It's not standard C.
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. Which is executes faster? 1: ``` ...
Any good compiler will end up making them both the same, so I can't imagine it matters.
This question already has answers here:Closed12 years ago. Possible Duplicate:strtok giving Segmentation Fault Why do i get segfault using this code ? ``` void test(char *data) { char *pch; pch = strtok(data, " ,.-"); // segfault while (pch != NULL) { printf("%s\n", pch); pch = strto...
strtok()modifies the original string. You are passing it aconstantsource string that cannot be modified. Try this instead: ``` char *data = strdup("- This, a sample string."); test(data); ```
I'm looking for a function in Scala that has similar functionality to getch. While using the console, I'd like to have my program display information based on what characters the user inputs (for example, if I was displaying a text, hitting n would show the next page, and p the previous). Right now I'm using readLine ...
scala.Console.readChar, aliased in in current incarnations of Scala asPredef.getCharis the most direct way. ``` scala> readChar res0: Char = ! ``` UPDATE This time without the peskyEnter: ``` scala> Console.in.read.toChar res0: Char = ! ```
what shall be the output of: (and why?) ``` printf("%d",2.37); ``` Apparently, printf is a variadic function and we can never know the type of a variable argument list. so we always have to specify the format specifiers manually. so, 2.37 would be stored as double according to IEEE standards would be fetched and pr...
It is undefined behavior. You're passing adoubleargument to a function that expects to retrieve anintfrom its varargs macros, and there's no telling at all what that is going to lead to. In theory, it may even crash (with a calling convention that specifies that variadic arguments of different types are passed in diff...
see in one code i have written ``` void my_function() { INT32 i; /* Variable for iteration */ /* If system is little-endian, store bytes in array as reverse order */ #ifdef LITTLE { // i m using i for operating one loop } #endif /* If the system is big-endian, store bytes in array as forward o...
Put the declaration ofijust inside the{}where you actually use it. Even better if you have C99, declare the loop variable inside thefor(int i = 0, i < bound; ++i)
I am wondering if it is possible for a Windows program to allocate a segment descriptor within the process' local descriptor table. Is there a Windows API function that can install a new segment descriptor to the running process' LDT using a provided linear offset, segment length, and combination of flags (RWX)?
It's possible using undocumented NT API, specifically NtSetLdtEntries. Note that Windows x86-64 does not set up an LDT so this only works on x86. Here'ssome code.
i am using basename() function in my code. Where i am including ``` #include <unistd.h> ``` and when i m compiling that code with -Wall flag it shows following warning ``` warning: implicit declaration of function ‘basename’ ``` if i am writing its declaration in my code ``` char * basename (const char *fname); ...
You need to include<libgen.h>. The standardsays it's inlibgen.h,kernel.orgdoes so too.
What is the most efficient way to keep checking if a certain something happened & if that something happened you execute a set of commands? (I'm working with C & Obj-C)
Use this. NSTimer *newTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(checkBoolValue) userInfo:nil repeats:YES]; This method will run checkBoolValue after every 5 seconds. Now, when your boolean value gets set, then stop the timer by [newTimer invalidate];newTimer = nil;
I am in the directory/home/destinationI need to go back to the/homedirectory. Any ideas on how to implement this using a C-program?
A program can only changeits own environment. Thus, the program canchdirbut it will not change the current directory of the parent. That's whycdcan't be implemented as an external command.
I would like to put the number given bysystem("stat -f %g /dev/console")in a variable (working in Xcode using C). How is this best achieved?
I'd rather use thestatfunction : ``` struct stat file_details; stat("/dev/console", &file_details); printf("group id : %ld\n", (long) file_details.st_gid); ```
I have a C application running on cross platforms. In this program, I need to write a function which determines if the given date is DST or not.Actually, i try to find DST begin-DST end dates in pure C. Is there any simple and standard way to do this?
time.hprovidestmstructs with atm_isdstflag. Usetimeto get the current time,localtimeto get atmstruct with the time adjusted to the current locale and read thetm_isdstflag. From the manpage: ``` tm_isdst A flag that indicates whether daylight saving time is in effect at the time described. The value is positive if ...
Consider the following code: ``` #include <stdio.h> int main() { printf("%d", 300 * 300 / 300); return 0; } ``` This code when run on a standard GCC compiler gives the result as300but when i run it using Turbo C, the result is81. Why is it so? I understand that TC uses 2 bytes for storing integers, ...
Before it prints it divides it by 300, but the overflow already happend, since integer literals are evaluated asints, when you divide, you already with the overflowed int result. Since*and/has the same priority, the*is evaluated first (since evaluation is left to right) You can, however, do either300 * (300/300)or30...
TheMSDN documentationand theknowledge base articleof GetVolumeInformation are not very specific what the file system name string can contain. The obvious values are NTFS, CDFS and FAT32. But can it also detect other file systems and what would be the strings ? I also read somewhere that sometimes version numbers are ...
This function can detect the following file systems: FAT, FAT32, NTFS, HPFS, CDFS, UDF, NWFS As I can remember for my experiences in 3 years ago, ex2 or ex3 were not detectable at all on Windows XP SP3. Edit Since Vista SP2, there is also support for exFAT
I have a very quick question to which I havn't found an answer for. Are there any major platforms (Windows, MacOS, unix, linux, Android, iOS, etc....) out there that supports C but not C++? Thanks
C and C++ are not operating system dependant. If there is a compiler that can compile the C/C++ code to execute not he current CPU. All is good.
In order to determine the size of the column in C language we use%<number>d. For instance, I can type%3dand it will give me a column of width=3. My problem is that my number after the%is a variable that I receive, so I need something like%xd(wherexis the integer variable I received sometime before in my program). But ...
You can do this as follows: ``` printf("%*d", width, value); ``` From Lee's comment:You can also use a * for the precision: ``` printf("%*.*f", width, precision, value); ``` Note that bothwidthandprecisionmust have typeintas expected byprintffor the*arguments, typesize_tis inappropriate as it may have a different ...
``` struct st1{ int a:1; int b:3; int c:6; int d:3; }s1; struct st2{ char a:3; }s2; int main(){ printf("%d : %d",sizeof(s1),sizeof(s2)); getchar(); } ``` I am getting the output as 2 : 1 will you please tell me, how this program works and whats the use of : operator (a:1) here. Thank you
The:defines abit-field. In your example, objects of typestruct st1use 13 bits in some arrangement chosen by the compiler. The particular arrangement chosen when you compiled the code originated an object that occupies 2 bytes. The 13 bits are not necessarily the first (or last) in those bytes. The other struct type...
I got this error: ==4024== Conditional jump or move depends on uninitialised value(s) ==4024== at 0x400D69: constructBoardSpaces (in /a/fr-01/vol/home/stud/roniy02/oop/Ex3/Play) and the function is: ``` static void constructBoardSpaces(char** array,int rows,int cols) { int i=0,j=0; for (i = 0; i < rows; ...
are you sure you initialized the two dimensional array before you enter that loop? Otherwise I would say the problem is probably in the if statement where you read from the array: ``` if((array[i][j])!='X'&&(array[i][j]!='O')) ```
My question is how fast ismprotect. What will be the difference between mprotecting say 1 MB of contiguous memory as compared to 1 GB of contiguous memory? Of course I can measure the time, but I want to know what goes under the hood.
A quick check on the source seems to indicate that it iterates over the process mappings in the selected region and change their flags. If you protect less than a whole mapping it'll split it into two or three. So in short it'sO(n)wherenis the number of times you've called mmap. You can see all the current maps in/p...
I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C. What does the conditionif ((flags & 0x400) != 0)mean? How do I do that in perl? Isif ($flags == "\x400")correct?
&is a bitwise AND. SeeBitwise operators. Soflagsis being treated as a series of bits, and then you AND it with something which has exactly the bit set that you want to check. If the result is non-zero, then the bit is set, otherwise the bit you were looking at isn't set. In particular, in your example0x400 = 0100 000...
I'm trying to find the most efficient way to read in a positive number in C. I can't use just scanf("%u", &var) because scanf takes the two's complement of negative numbers thereby screwing up the number. I also don't really want to read characters in manually into a buffer, because that requires me to know before-han...
Maybe somtehing like this: ``` char sign = getchar(); if ('-' == sign) { //error } else { ungetchar(sign); scanf("%u", &var) } ```
see when ever we are going to use any library at that time we include one .h file in our application & at compiling that application we link that library. if that library is .so then link at run time. Now my question is in any system when i am including basic header file like stdio.h conio.h string.h at that time wh...
libc.sois the standard library (dynamically linked) of linux (currentlylibc.so.6)
i have a string like this.. /home/Abcd/Pradeep/Jack.sh /home/Abcd/Pradeep/Paul/Kill.sh I need to take Jack.sh and Kill.sh alone from these strings. there can be many / in the string. How to do this using strtok ?
You don't needstrtokfor this. Just usestrrchrto find the last'/'character. Your filename starts one character after that.
I am learning C Language and I have a question. If I compile and make an executable for C program in say BorlandC on one Windows PC and then transfer this file to another Windows PC which does not have the compiler, how does it run where there is no C runtime and how does the memory management work?
You can do this in a relatively painless way if you use static linking. That means the run time libraries are bound into your executable when you compile/link (on your machine), rather than being loaded up dynamically at run time (on the other machine). If you use dynamic linking, then the libraries have to be availa...
I am writing a function that just looks up values inside of a table. Is it possible to call that function inside of itself? I've seen stuff aboutthisandselfand don't really understand it.
Yes, you can. It's called recursion. ``` void foo(){ foo(); //This is legal. } ``` Of course you need to return from it to avoid infinite recursive calls. Failing to return will cause a stack overflow. Here's a better example: ``` void foo(int n){ if (n == 0) return; foo(--n); } ```
Why is the output of the following program84215045? ``` int grid[110]; int main() { memset(grid, 5, 100 * sizeof(int)); printf("%d", grid[0]); return 0; } ```
memsetsets eachbyteof the destination buffer to the specified value. On your system, anintis four bytes, each of which is 5 after the call tomemset. Thus,grid[0]has the value0x05050505(hexadecimal), which is84215045in decimal. Some platforms provide alternative APIs tomemsetthat write wider patterns to the destinat...
This question already has answers here:Closed12 years ago. Possible Duplicate:strtok giving Segmentation Fault Why do i get segfault using this code ? ``` void test(char *data) { char *pch; pch = strtok(data, " ,.-"); // segfault while (pch != NULL) { printf("%s\n", pch); pch = strto...
strtok()modifies the original string. You are passing it aconstantsource string that cannot be modified. Try this instead: ``` char *data = strdup("- This, a sample string."); test(data); ```
I'm looking for a function in Scala that has similar functionality to getch. While using the console, I'd like to have my program display information based on what characters the user inputs (for example, if I was displaying a text, hitting n would show the next page, and p the previous). Right now I'm using readLine ...
scala.Console.readChar, aliased in in current incarnations of Scala asPredef.getCharis the most direct way. ``` scala> readChar res0: Char = ! ``` UPDATE This time without the peskyEnter: ``` scala> Console.in.read.toChar res0: Char = ! ```
what shall be the output of: (and why?) ``` printf("%d",2.37); ``` Apparently, printf is a variadic function and we can never know the type of a variable argument list. so we always have to specify the format specifiers manually. so, 2.37 would be stored as double according to IEEE standards would be fetched and pr...
It is undefined behavior. You're passing adoubleargument to a function that expects to retrieve anintfrom its varargs macros, and there's no telling at all what that is going to lead to. In theory, it may even crash (with a calling convention that specifies that variadic arguments of different types are passed in diff...
I am in the directory/home/destinationI need to go back to the/homedirectory. Any ideas on how to implement this using a C-program?
A program can only changeits own environment. Thus, the program canchdirbut it will not change the current directory of the parent. That's whycdcan't be implemented as an external command.
I would like to put the number given bysystem("stat -f %g /dev/console")in a variable (working in Xcode using C). How is this best achieved?
I'd rather use thestatfunction : ``` struct stat file_details; stat("/dev/console", &file_details); printf("group id : %ld\n", (long) file_details.st_gid); ```
In Android NDK, is their a way to use _splitpath function which available in C stdlib.h? I have include ``` #include <stdio.h> #include <stdlib.h> ``` and when I call the function ``` char fname[_MAX_FNAME]; char extn[_MAX_FNAME]; _splitpath(filename.c_str(), NULL, NULL, fname, extn); ``` It give out error that i...
_splitpath()and_MAX_FNAMEare part of MSVC's runtime - they aren't standard, and are not part of GCC's library or a Linux system call. You might be able to do what you want usingdirname()andbasename().
This is a theoretical question. I wonder how certain constructions in C are performed internally without references. For example: ``` struct Foo { int a; }; int main() { struct Foo foo; foo.a = 10; return 0; } ``` What is the type offoo.a? It's definitely not a pointer, because we assign10as a value, not addr...
It is an int lvalue. Same as if you hadint bar, andbar = 10changes the data ofbar. Same applies to any element within an array. Basically anything you can take the address of is an lvalue. Lvalue status is independent of type.
I am currently looking to add encryption to a server application (programmed in C) that passes raw data, unencrypted data over TCP to clients (a large number of different applications programmed in many different languages). What is the best way to do this? Public-key cryptography? If so, how would the process go? T...
If you have to ask, you're probably not qualified to be doing cryptographic work. It is far to easy to make a subtle mistake in crypto processing that breaks your entire system's security, and unlike most other bugs, it is not at all obvious until someone else breaks your system. Just use SSL (aka TLS). The folks tha...
Why does this work: ``` //split returns (char**) char *temp2; temp2=split(array[i],'=')[1]; ``` and this doesn't: ``` char **temps; temps[0]=temp2; //crashes ``` or this: ``` temps[0]=split(array[i],'=')[1]; //crashes ```
tempsis just a pointer to achar*, but it has no initalized, sensible value!temps[0]is equivalent to*(temps + 0), but you cannot dereference a garbage value -- you first have to maketempspoints somewhere useful, e.g. by allocating memory for it. If you want to store somechar*s with automatic storage, then declare an a...
How do we interpret the following declaration: ``` char (*(*f())[])(); ``` How shall one develop a handy technique to read such complicated or even more complicated declarations in C. If you use a quick trick, please share.
There is indeed a not-so-well-known trick. Pretend thatfis a variable name, and that*,()and[]are operations you can do on it. Use the precedence rules of C operators to wit that: ``` f ``` can be applied ``` f() ``` and then dereferenced ``` *f() ``` and then subscripted ``` (*f())[] ``` and then dereferenced ...
``` /me/home/file1.c containes function definition: int mine(int i) { /* some stupidity by me */ } ``` I've declared this function in ``` /me/home/file1.h int mine(int); ``` if I want to use this functionmine()in/me/home/at/file2.c To do so, all I need to do is: ``` file2.c #include "../file1.h" ``` Is th...
You will also need to link the object file from file1. Example: ``` gcc -c file2.c gcc -c ../file1.c gcc -o program file2.o file1.o ``` Or you can also feed all files simultaneously and let GCC do the work (not suggested beyond a handful of files); ``` gcc -o program file1.c file2.c ```
``` #include <stdio.h> #include <stdlib.h> #define calc(a,b) (a*b)/(a-b) void calculate(){ int a = 20, b = 10; printf("%f\n", calc(a+4,b-2));//output 0.00000 } ``` what to do to print the actual answer, 4.83.
``` #define calc(a,b) ((a)*(b))/((a)-(b)) ``` Can you spot the extra parentheses? -->calc(a+4,b-2)resolves to((a+4)*(b-2))/((a+4)-(b-2)). Correct. Your solution without the extra parentheses: -->calc(a+4,b-2)resolves to(a+4*b-2)/(a+4-b-2). Which is very different!
Is there an algorithm that can be use to subtract 1 from a number using only increments (++in C) and left bitwise shifts (<<in C) ? EDIT: I am using type unsigned char Thanks in advance
You can do it with just the++operator. Loop forUCHAR_MAXiterations. Quite inefficient though: ``` unsigned char c = 42; unsigned char i = 0; while (++i) { ++c; } // c is now equal to 41 ``` LIVE DEMO
Ok, this was a bit too much for me. How do you read these declarations? ``` char *(*(**myCBT[][10])())[]; ``` Please note: I'm not specifically asking for this example but for a general rule of thumb if a beginner like me faces a tough puzzle like this.
Use David Anderson'sClock wise spiral rulefor reading such notations.
This question already has answers here:Closed12 years ago. Possible Duplicate:Difference between using character pointers and character arrays What's the difference between: ``` const char* myVar = "Hello World!"; const char myVar[] = "Hello World!"; ``` If there is one?
The pointer can be reassigned, the array cannot. ``` const char* ptr = "Hello World!"; const char arr[] = "Hello World!"; ptr = "Goodbye"; // okay arr = "Goodbye"; // illegal ``` Also, as others have said: ``` sizeof(ptr) == size of a pointer, usually 4 or 8 sizeof(arr) == number of characters + 1 for null termin...
I could not understand how the below program code outputs that value.Please help me to understand. ``` #include<stdio.h> char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}"; int main() { printf(s,34,s,34); return 0; } ``` output: ``` char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";main(){printf(s,34...
It isn't actually a macro in use here. It is just a simple call to printf. The first parameter to printf is the format string. In this case it is the value defined in the global variables. The format characters%c%s%care supplied by parameters34,s,34". So the string is just printed in its entirety because of the%s...
I get error in C(Error- Unused Variable) for variable when I type in following code ``` int i=10; ``` but when I do this(break it up into two statements) ``` int i; i=10; ``` The error Goes away ..I am using Xcode(ver-4.1)(Macosx-Lion).. Is something wrong with xcode....
No nothing is wrong the compiler just warns you that you declared a variable and you are not using it.It is just a warning not an error.While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.
I am using BSD sockets over a wlan. I have noticed that my server computer's ip address changes occasionally when I connect to it. The problem is that I enter the ip address into my code as a literal string. So whenever it changes I have to go into the code and change it there. How can I change the code so that it wil...
Use a domain name that can be looked up in your hosts file or in DNS, rather than an IP address.
Can anyone shed a little light on how I would go about creating an approach algorithm for a target time; having sleep(x), where x is initially large and decreases as the target time approaches?
It depends on your constraints, but an easy solution is to always divide the remaining time by 2 and then sleep for that time. It has logarithmic complexity and that is fine. Often the OS only guarantees a granularity of 10 ms, so stop sleeping when time falls below 20 ms.
I have just started reading about threading in C, using pthreads. I know that Pthreads are available for Windows, but do multithreaded WIndows based C/C++ applications mostly use Pthreads? Also in Unix/Linux are Pthreads the main way developers write multithreaded C/C++ code?
No, most will use the thread abstraction of the application/gui library they are using, e.g. MFC. Or in the plain C case, using the windows API directly. Pthreads stands for "POSIX" threads, which is basically standarized unix(-like), a standard that has little meaning on Windows outside dedicated POSIX emulations l...
I'm trying to open a connection to a webpage (e.g. www.google.com) via localhost, port 80. How can I do this programatically in C? I want get all the HTML headers and not just the content ;( I hope someone can help. Many thanks in advance,
Here is some example code on how to do this withlibcurl: http://curl.haxx.se/libcurl/c/getinmemory.html There is another one right there, that shows you how to get some header data: http://curl.haxx.se/libcurl/c/getinfo.html These examples and many others are available as part of thelibcurldistribution. It should ...
I have ``` char *path; ``` and I store the string "/home/juggler/file1.txt" in path. How do I truncate path so that I just have the parent of the last file/directory? In the example I would like to truncate path to "/home/juggler" I was thinking of counting the number of characters(count) from the end to the last "...
Trydirname(3)since you are on Linux. Being specified bySUSv3, it's quite portable. char *dirname(char *path);In the usual case, dirname() returns the string up to, but not including, the final '/'.
What doeschar buf[MAXDATASIZE] = { 0 };'s{0}means? tried to print it out but it print nothing. ``` #include <stdio.h> int main(void) { char buf[100] = { 0 }; printf("%s",buf); return 0; } ```
This is just an initializer list for an array. So it's very like the normal syntax: ``` char buf[5] = { 1, 2, 3, 4, 5 }; ``` However, the C standard states that if you don't provide enough elements in your initializer list, it will default-initialize the rest of them. So in your code, all elements ofbufwill end up...
This program outputs 1. I could not understand how it outputs 1 as the for loop will fail ata[2][3]which contains the value 12. So 12 will get assigned to k and the output will have to be 12. ``` #include<stdio.h> int main() { int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}; int i,j,k=99; for(i=0;i<3;i++) {...
The first time through the loop the if is evaluated as a[0][0] < k which is 1 < 99 which is true. The second time through he loop if the if is a[1][0] < k which is 2 < 1 which evaluates as false thus the value of k is not updated k is never reassigned another value, thus at the end k=1.
I Just began Gtk3 development with natty and for my first app , the Interface looks horrible.It's like that of windows 98 O.o !A screenshot to show you what i mean >>http://www.dumpyourphoto.com/photo/view/69642/2pnZdXI\m using the sample code from getting started with gtk.
This isn't a programming issue, it's a system configuration issue. You need to install a GTK3 theme. (For best results, I'd advise installing a theme package that comprises a GTK2andGTK3 theme, like Adwance. Otherwise your GTK2 apps will look poor instead.)
If I have a bit of code looking like this: ``` if(someInteger || somecomplexfunction() > 0) { // do something } ``` Will the function be called ifsomeIntegerevaluates to true? p.s. compiling with GCC with-O2
No, it won't. Logical operators in C short circuit, so if the left hand side of an||is true, the right hand side won't evaluate (and thus the function won't execute, and no side effects that it might have will take effect). Likewise with&&, if the left hand side evaluates false, the right hand side won't get evaluated...
What should be the output of this C program? ``` int main() { int x=1,y=1,z; if (z=(y>0)) x=5; printf("%d %d",x,z); return 0; } ``` As expected, the output is X is 5 and Z is 1. This is because when expression y>0 is evaluated it is true and so on and so forth. Now the problem is in this program: ``...
No,(x=y)returns the new value after setting x to y's value. However,(x==y)returns 1 if they are equal, and 0 if not.
This part of K&R (The C book) got me thinking: From the book: ``` struct tnode { char *word; int count; struct tnode *left; struct tnode *right; }; ``` The recursion declaration of a node might look chancy, but it's correct. Because tnode's defiition doesn't u...
Pointers have a fixed size (32/64 bit depending on the platform) so the compiler knows how much memory is need for the left and right pointers and can calculate the whole size of the struct. For the same reason if you need a pointer it's enough to do a forward declarationstruct tnode;and you can use a pointer for tha...
Themallocfunction always allocate memory on the heap. However, while studying theEscape Analylis Article on Wikipedia, I came to know that as an optimization, a compiler can convert heap allocations to stack allocations. For example, if it sees that an allocated memory is only used and then freed inside a function. N...
alloca()is what you're looking for. Of course, if you know your structures dimensions statically, it'd be better to use local variables instead.
How would I create a delayed execution of code or timeout events usingepoll? Both libevent and libev has the functionality but I can't figure out how to do this using epoll. Currently the main loop looks like this: ``` epoll_ctl(epfd, EPOLL_CTL_ADD, client_sock_fd, &epev); while(1) { int nfds = epoll_wait(epfd,...
You can createtimerfdand add the file descriptor to the epoll_wait
Ok this has been become sooo confusing to me. I just don't know what is wrong with this assignment: ``` void *pa; void *pb; char *ptemp; char *ptemp2; ptemp = (char *)pa; ptemp2 = (char *)pb; ``` Can anyone tell me why I'm getting this error: error: invalid conversion from ‘void*’ to ‘char*’
Actually, there must be something wrong with your compiler(or you haven't told the full story). It is perfectly legal to cast avoid*tochar*. Furthermore, the conversion isimplicitin C (unlike C++), that is, the following should compile as well ``` char* pChar; void* pVoid; pChar = (char*)pVoid; //OK in both C and C...
Can anyone shed a little light on how I would go about creating an approach algorithm for a target time; having sleep(x), where x is initially large and decreases as the target time approaches?
It depends on your constraints, but an easy solution is to always divide the remaining time by 2 and then sleep for that time. It has logarithmic complexity and that is fine. Often the OS only guarantees a granularity of 10 ms, so stop sleeping when time falls below 20 ms.
I have just started reading about threading in C, using pthreads. I know that Pthreads are available for Windows, but do multithreaded WIndows based C/C++ applications mostly use Pthreads? Also in Unix/Linux are Pthreads the main way developers write multithreaded C/C++ code?
No, most will use the thread abstraction of the application/gui library they are using, e.g. MFC. Or in the plain C case, using the windows API directly. Pthreads stands for "POSIX" threads, which is basically standarized unix(-like), a standard that has little meaning on Windows outside dedicated POSIX emulations l...
I'm trying to open a connection to a webpage (e.g. www.google.com) via localhost, port 80. How can I do this programatically in C? I want get all the HTML headers and not just the content ;( I hope someone can help. Many thanks in advance,
Here is some example code on how to do this withlibcurl: http://curl.haxx.se/libcurl/c/getinmemory.html There is another one right there, that shows you how to get some header data: http://curl.haxx.se/libcurl/c/getinfo.html These examples and many others are available as part of thelibcurldistribution. It should ...
A compiler checks the syntax of source code from the text file. Why is it necessary to save it with an extension.cor.cpp? I tried this on gcc but it does not compile a file with an extension other than.cand.cpp!!
GCC (you name it on your tags) checks the file extension, if you do not specify a language with the-xoption. If the extension is not recognized, the file is passed directly to the linker.
I am getting an error related toerr_sys()in this code: ``` #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> int main() { int sockfd; if ((sockfd=socket(AF_INET,SOCK_STREAM,0))<0) err_sys("can't create socket"); close(sockfd); return 0; } ``` I am getting the linker error: ...
Place this on top of your code: ``` void err_sys(const char* x) { perror(x); exit(1); } ``` perror is defined in stdio.h err_sys is used in the book "UNIX Network Programming: The sockets networking API" by Richard Stevens. It's not something common, as far as I know. edit:fixed code error
There are two functions in epoll: epoll_ctlepoll_wait Are theythread-safewhen I use the same epoll_fd?What will happen if one thread calls epoll_wait and others call epoll_ctl at the same time?
It is thread-safe, but there isn't much documentation that explicitly states that. Seehere BTW, you can also have multiple threads waiting on a singleepoll_fd, but in that case it can get a bit tricky. (I.e. you might want to use edge-triggeredEPOLLETor oneshot modeEPOLLONESHOT. Seehere.)
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer...
Lawrence Livermore National Laboratory has an excellent tutorial at: https://computing.llnl.gov/tutorials/pthreads/
While searching for an answer tothis questionI foundthis sample codewhich looks like just what I need except it calls ``` select_wait() ``` which is defined innon_blocking.hbut which is otherwise unlocatable. Is select_wait() proprietary code? Is it an entrypoint in some DLL I can get? How do I duplicate whatever...
Apparently it's part of the proprietaryBSAFElibrary/framework
The below code runs in an infinte loop. 'i' has been intialised with the value 1 and then compared with 0. So printf() stmt should execute once but it runs infinetly. ``` unsigned int i = 1; for (; i >= 0; i--) { printf("Hello: %u\n",i); } ``` please explain this behaviour.
Becauseiisunsignedit can't go negative, soi>=0is always true. Wheniis zero and you doi--, the value ofiwraps round to themaximumvalue anunsigned intcan have (which is greater than zero). You should use a signed integer, by removing theunsignedmodifier.
In scanf space and \n is delimiter for the character i/p. The below program accepts only two input. I could not understand why does it accept two input.Please explain about this behaviour. ``` char a,b,c; scanf("%c%c%c",&a,&b,&c); printf("%c%c%c",a,b,c); return 0; ```
Itdoesaccept 3 inputs if you don't put spaces between the input characters. If you want to allow space(s) between inputs usescanf("%c %c %c",&a,&b,&c);.
Theprintf()function will return the number of characters printed. But in the code below why is it printing 5. ``` int a=1000; printf("%d",printf("\n%d",a)); ``` It prints "1000" once and a space, so altogether we have 5 characters. It should output "1000 2". But its outputting "1000 5".
The number of characters output is 5.1000is four characters.\nis one character. printfdoesn't return the number of "items" output like thescanffamily of functions do for input. It returns the actual character count.