question
stringlengths
25
894
answer
stringlengths
4
863
Please explain the output of this program: ``` int main() { int a,b,c,d; a=10; b=20; c=a,b; d=(a,b); printf("\nC= %d",c); printf("\nD= %d",d); } ``` The output which I am getting is: ``` C= 10 D= 20 ``` My doubt is what does the "," operator do here?I compiled and r...
The,operator evaluates a series of expressions and returns the value of the last. c=a,bis the same as(c=a),b. That is why c is 10 c=(a,b)will assign the result ofa,b, which is 20, toc. As Mike points out in the comments, assignment (=) has higher precedence than comma
In C, it isconsidered poor formto typecast the result of a call tomalloc. However, it seems that the result of calls tomallocin C++shouldbe typecast, even though bothmallocandnewhave return typevoid*and calls toneware not typecast. Is there a reason why in C++ the void pointer returned bynewis automatically promoted w...
You are confusingoperator newwith thenewoperator.operator newjust allocates raw memory and returns avoid*, whereasnew Talso calls the constructor after allocation and returns aT*. Also, you have to cast the result ofmallocin C++, because unlike C, C++ does not allow implicit conversions fromvoid*to other pointer type...
crypt (const char *key, const char *salt) I saw it in code, but i could not find the implementation of this function. Is it some of the conventions of C?
It's specified byPOSIXbut not by any version of the C standard. Careful though: The crypt() function is a string encoding function.The algorithm is implementation-defined.
I have a variable that can take any 3 values. If it can take only 2 values I would have assigned a bool type. But my variable can take 3 values. If I assign a int8_t type I am wasting 6 bits. Though this looks like preemptive optimization, I have millions of instances of this type, which is going to make a huge differ...
If youreally(although I'm not sure it's the case) need this data type, you can use a bitfield. However, this could be constraining, since you can't define a pointer to such type. Wasting a bit: ``` struct s { int n:2; /* 4 states instead of 3 */ }; ```
Why is there a number added to the name of a local static variable in the symbol table? ``` int main(void) { static stat_var = 20; return 0; } ``` 8: 0000000000000008 4 OBJECT LOCAL DEFAULT 2 stat_var.1604
There can be many local static variables with the same name (across different functions). The compiler is giving them disambiguating suffixes to avoid a potential name collision.
I'm getting an error (error: dereferencing pointer to incomplete type ) with addData->s = s and addData->type = type, and I'm not sure why... it seems like it should work to me (I'm a bit rusty with C, however) Here's the code: ``` int addSym(char *s, var_type type){ struct syment* addData= malloc(sizeof(syment...
Try changing ``` typedef struct syment_s { char *s; int offset; var_type type; struct syment_s *next; }*syment; ``` to ``` typedef struct syment_s { char *s; int offset; var_type type; struct syment_s *next; } syment; ``` Pointer overload and this is not Crufts (Pointer is a dog, Crufts is a dog sh...
I am creating a public key generator and I do c= p*q; Where p and q are large prime numbers, but I keep getting this for C 11875820813; ``` long unsigned int c= p*q; printf("C is: %d\n", c); ``` I know I has something to do with my numbers, but I don't know how to fix this. I am trying to multiply: 872017*533297
You might be overflowing the value. Remember that on a 32-bit platform anunsigned longcan be at most a little over 4 billion.
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.Closed10 years ago. I have a short int, which is 2 byte...
You could try this approach ``` int someNum = 0x1234; int leftByte, rightByte; leftByte = (someNum >> 8) & 0xff; rightByte = (someNum) & 0xff; ```
``` #include <stdio.h> int main(int argc, char *argv[]) { char s[]="help"; printf("%d",strlen(s)); } ``` Why the above output is 4, isnt that 5 is the correct answer? it should be 'h','e','l','p','\0' in memory.. Thanks.
strlen: Returns the length of the given byte string not including null terminator; ``` char s[]="help"; strlen(s) should return 4. ``` sizeof: Returns the length of the given byte string, include null terminator; ``` char s[]="help"; sizeof(s) should return 5. ```
From this Web sitehttp://www.programmingsimplified.com/c-program-find-characters-frequencyThey have an example that will count a - z but not A-Z or spaces or standard punctuations. ``` while ( string[c] != '\0' ) { /* Considering characters from 'a' to 'z' only */ if ( string[c] >= 'a' && string[c] <= 'z...
To count all characters in the string use anint a[256]and use the characters of the string as indexes into the array and increment: ``` int counts[256] = { 0 }; /* Initialize all elements to zero. */ while (string[c]) counts[(unsigned char)string[c++]]++; ```
I get the error: warning: format argument is not a pointer (arg 2) with this line:printf("%s \n", *(group_list->name)); I don't understand why this is a problem considering thatnameis a pointer to a char. Is it a problem with usings? Do I have to use a different specifier?
Use this instead: ``` printf("%s \n", group_list->name); ``` sconversion specifier expects achar *not achar.
printf("%d, ", packet[i]); How to display variable correctly. It should be from 0 to 255 but if I use%dit prints: -1 as 255 up to the number 128 is displayed correctly, larger are negative. when I use%uit prints 4294967295 instead of 255.
Use%hhuconversion specification: ``` printf("%hhu, ", packet[i]); ```
I have to assign a static variable a value which I am getting from a function. I tried doing the following but I am getting initializer element is not constant. ``` int countValue() { return 5; } void MatrixZero() { static int count=countValue(); count++; printf("count value %d \n",count); } int main() { ...
Because... well... the initializer of your static variable is not a constant. It must be a constant expression. Try this: ``` static int count = SOME_VALUE_OUT_OF_RANGE; if (count == SOME_VALUE_OUT_OF_RANGE) { count = countValue(); } ``` to check if it has already been initialized.
I have download Android source code and flashed it to device. I have written LKM which reads/writes information to /proc/myFile. I want to write to /proc/myFiLE file from my android activity but using java code not native. I know in native code we can can usesystem( )system call to write using echo command but i do no...
Just treat them as normal files. You can use the usualFileand*Streamobjects to write what you need.
The sending C-side ``` double tmp = htonl(anydouble); send(socket, (char *) &tmp, sizeof(tmp), 0); ``` On the Java side, im reading the network data into a char[8] What is the proper way of performing the conversion back to double? Is it the way to go to simply send a string and parse it back to double?
This should work. ``` char[] sentDouble = readBytes(); // get your bytes char[8] String asString = new String(sentDouble); // make a string out of it double myDouble = Double.parseDouble(asString); // parse it into a double ``` With a byte[] you can do ``` import java.nio.ByteBuffer; public static double toDouble(...
What is the defined behavior in C forUINT_MAX + 1u? How safe is to assume it is zero?
From the standard (C11, 6.2.5/9, emphasis mine): [...] A computation involving unsigned operands can never overflow, because a result that cannot be represented bythe resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting...
My simplified code looks like something below: ``` char decrypted[64] = "P@ssw0rd "; int realsize = 8; realloc(decrypted, realsize); char *dec2 = (char *) malloc(realsize+1); // Exe crashes at this point ``` I am guessing it has to do withchar *dec2, but this only crashes Win XP for some reason....
You cannotrealloc()what hasn't been allocated withmalloc()orcalloc()orrealloc().
Withfopen()I read the file line by line withfgets(). Are there a function likefgets()inorder to read stream opened byopen()?
There is no such function. The problem is, unless you do buffering in userspace (likeFILE*routines do), there is no way to implement it efficiently: you'll have toreadcharacters one-by-one. On POSIX systems you can usefdopento wrap aFILE*structure around a file descriptor, and then usefgets.
I am facing a problem while compiling this code. Any solution would be much appreciated. The code is as follows : ``` #include<stdio.h> typedef struct nx_string_t { char *buf; int number; }nx_string_t; typedef struct nx_value_t { ...
vale->strnghas typenx_string_t.checkexpects anx_value_t*so you need to passvaleinstead ``` check(vale); ```
I have a matrixM[2][2]and want to make a call to functiondontModify(M)that will play around with the elements of M but not change them. Something like: ``` dontModify(M): swap off-diagonal elements; take determinant of M; return determinant; ``` ...but without having the function change M in the process. An...
Create a local copy of the matrix inside the function, one that you can do whatever you want with. ``` int some_function(int matrix[2][2]) { int local_matrix[2][2] = { { matrix[0][0], matrix[0][1] }, { matrix[1][0], matrix[1][1] }, }; /* Do things with `local_matrix` */ /* Do _not_ ...
I am working on a legacy source code for computing data. In order to debug few error conditions I have added the following printf in the code ``` printf("What???!!!!....\n"); ``` The logs were maintained in a file and I was searching for the string "What???!!!!...." but II never found this because the output of it ...
the output is related to trigraph, the string ??! corresponds to | Check your makefile for -trigraphs Make sure to have more sensible prints now-on :-)
This question already has answers here:Developing C wrapper API for Object-Oriented C++ code(6 answers)Closed10 years ago. I'm currently developing a SDK for our product in C++. However, some of our customers have a code base written in C that will need to interface with our SDK. I need to provide C Interfaces and am...
Here are my suggestions: Provide some C language interfaces or functions that use static C++ objects to invoke functionality.Add static functions to your classes for use with the C language.Change your design so that there are free standing functions that accept structures and classes.Also, don't overload free standi...
This question already has answers here:Does C have a standard ABI?(9 answers)Closed10 years ago. It seems to me that C libraries almost never have issues mixing libraries compiled with different versions or (sometimes) even different compilers, and that many languages seem to be able to interface with C libraries eit...
ABIs are not codified in the language standard. You can get a copy of any of the C standard drafts to see it yourself. And there's a good reason for ABIs not being in the standard. The standard cannot anyhow foresee all hardware and OSes for which C compilers can be implemented.
I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c: ``` #include <stdio.h> void hello() { printf("Hello world!\n"); } ``` How do I create a .so file that exportshello(), using gcc from the command line?
To generate a shared library you need first to compile your C code with the-fPIC(position independent code) flag. ``` gcc -c -fPIC hello.c -o hello.o ``` This will generate an object file (.o), now you take it and create the .so file: ``` gcc hello.o -shared -o libhello.so ``` EDIT: Suggestions from the comments: ...
I'm writing a memory manager for a linux kernel that shares a cyclic list of PIDs between threads (project for school). This program finds zombies and kills them using a 1 producer, 2 consumer model. (forced on us so that we can understand shared memory). I would like to make this list an object and have functions de...
to say that a 'function' owns the mutex doesn't quite make sense. It is the thread that owns it. So yes, it is possible, whatever thread called your external function would own the mutex. if you look in your kernal code for the implementation of threads, you'll see that one of its variables is a list of mutexes it ow...
I am on an IOS project and we use objective-c. I function passes some data with type const char*. I can view the data in the debugger: ``` expr -- (void)printf("[%s]\n",(const char *)xml) ``` but I would like to change the value of the xml variable on the fly via the debugger. How can be done?
The same way you would do forchar*: Forconst char *xml = "<xml></xml>";you can assign to xml with expr -- xml = "<foo></foo>" Of coursexml(The pointer to your string) is in the functions scope, so you only change wherexmlin the function is pointing to, not the string thatxmloriginally points to (which you can't, be...
This question already has answers here:C Char pointers(4 answers)why this code works in C(2 answers)Closed10 years ago. Why can I store more than 3 characters in the array "char array[3]" ? For example, in this code: ``` #include <stdio.h> char array[3]; main() { scanf("%s", array); putchar(array[5]); return 0; } ...
Your code is able to print the entire word because it has not been overwritten yet. You are setting the memory and then immediately reading from it. If you were to attempt to read from that memory location later in your program's execution, you may get an entirely different result. This is undefined behavior... and i...
Here is howstrtolhas to be declared according to§ 7.22.1.4from C11 (n1570): ``` #include <stdlib.h> long int strtol (const char *restrict nptr, char **restrict endptr, int base); ``` As far as I know, therestrictkeyword means that the object referenced by the lvalue*nptrwill be acc...
No. Nothing is accessed via**endptrinstrtol. Only*endptr, a completely separate object, is accessed.
This question already has answers here:Does C have a standard ABI?(9 answers)Closed10 years ago. It seems to me that C libraries almost never have issues mixing libraries compiled with different versions or (sometimes) even different compilers, and that many languages seem to be able to interface with C libraries eit...
ABIs are not codified in the language standard. You can get a copy of any of the C standard drafts to see it yourself. And there's a good reason for ABIs not being in the standard. The standard cannot anyhow foresee all hardware and OSes for which C compilers can be implemented.
I'm trying to create a hello world project for Linux dynamic libraries (.so files). So I have a file hello.c: ``` #include <stdio.h> void hello() { printf("Hello world!\n"); } ``` How do I create a .so file that exportshello(), using gcc from the command line?
To generate a shared library you need first to compile your C code with the-fPIC(position independent code) flag. ``` gcc -c -fPIC hello.c -o hello.o ``` This will generate an object file (.o), now you take it and create the .so file: ``` gcc hello.o -shared -o libhello.so ``` EDIT: Suggestions from the comments: ...
I'm writing a memory manager for a linux kernel that shares a cyclic list of PIDs between threads (project for school). This program finds zombies and kills them using a 1 producer, 2 consumer model. (forced on us so that we can understand shared memory). I would like to make this list an object and have functions de...
to say that a 'function' owns the mutex doesn't quite make sense. It is the thread that owns it. So yes, it is possible, whatever thread called your external function would own the mutex. if you look in your kernal code for the implementation of threads, you'll see that one of its variables is a list of mutexes it ow...
I am on an IOS project and we use objective-c. I function passes some data with type const char*. I can view the data in the debugger: ``` expr -- (void)printf("[%s]\n",(const char *)xml) ``` but I would like to change the value of the xml variable on the fly via the debugger. How can be done?
The same way you would do forchar*: Forconst char *xml = "<xml></xml>";you can assign to xml with expr -- xml = "<foo></foo>" Of coursexml(The pointer to your string) is in the functions scope, so you only change wherexmlin the function is pointing to, not the string thatxmloriginally points to (which you can't, be...
This question already has answers here:C Char pointers(4 answers)why this code works in C(2 answers)Closed10 years ago. Why can I store more than 3 characters in the array "char array[3]" ? For example, in this code: ``` #include <stdio.h> char array[3]; main() { scanf("%s", array); putchar(array[5]); return 0; } ...
Your code is able to print the entire word because it has not been overwritten yet. You are setting the memory and then immediately reading from it. If you were to attempt to read from that memory location later in your program's execution, you may get an entirely different result. This is undefined behavior... and i...
Here is howstrtolhas to be declared according to§ 7.22.1.4from C11 (n1570): ``` #include <stdlib.h> long int strtol (const char *restrict nptr, char **restrict endptr, int base); ``` As far as I know, therestrictkeyword means that the object referenced by the lvalue*nptrwill be acc...
No. Nothing is accessed via**endptrinstrtol. Only*endptr, a completely separate object, is accessed.
I've been asked to create this for loop for my C Programming class but I do not know how to alternate the positive and negative values. Thank you in advance! sum2=1-x+x^2-x^3+⋯+/-x^n
Hint: consider the expression as sum of (-1*x)^i, with i = 1, 2, 3, ..., n. If n is even then (-1*x)^i is positive, if odd then negative.
I've to link libcurl to a project compiled on Windows XP with VS 2010 (MSVC 10). The dependencies found at urlhttp://windows.php.net/downloads/php-sdk/deps/are only for VC 2008 (MSVCR 9) and VS 2012 (MSVCR 11). Does anybody know where to find compiled libcurl binaries or its dependencies (for building by its makefil...
Problem solved : open and convert the root DSW file, then compile with VS!
in C , i have ``` struct a { int a; char b[16]; int c; }; ``` How is the memory of instances ofstruct a, will it be flat with the struct area, or insidestruct athere are pointer, for example , will the struct sizeof be 4+16+4 , or 4+4+4 ? what will happen if i have ``` struct a A,B; A->b = B->b; ``` ?...
how is the memory of instances of struct a, will it be flat with the struct area, or inside struct a there are pointer Flat. The array member is a real array, the size of thestructwill be ``` 2*sizeof(int) + 16 (+ padding) ``` what will happen if i havestruct a A,B A->b = B->b A compilation error. Arrays are not ...
Linux C program: What function call can check if running in X Window? If not in X Window, then printf.
Do you mean something like this: ``` #include <X11/Xlib.h> // ... char *display_name = NULL; /* connect to X server */ if ( (display=XOpenDisplay(display_name)) == NULL ) { //printf or whatever } ```
I have to read from standard input two numbers as strings, in C. How can I print their sum as a string too? I have: ``` char a[10],b[10]; printf("enter the two numbers"); scanf("%s%s",&a,&b); char sum[20]; sum=? ``` A little tip,please? Thank you!
Just do it like in elementary school Let's say the input was "...69 + ...63" ``` 9 + 3 = 2 and 1 to go 6 + 6 + 1 = 3 and 1 to go ... ```
I am doing programs in The C Programming Language by Kernighan and Ritchie. I am currently at exercise 1-24 that says: Write a program to check a C Program for rudimentary syntax errors like unbalanced parentheses, brackets and braces. Don't forget about quotes, both single and double,escape sequences, and comme...
In"\"", there are three double quote characters, but still it's a valid string literal. The middle"is escaped, meaning the outer two balance each other. Similarly,'\''is a valid character literal. Parentheses, brackets and braces are not affected, unless of course they appear in a string literal that you don't parse ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed10 years ago.Improve this question How can I prevent system (while my application is open) from suspending ? (Linux ...
In python ``` import dbus _session_bus = dbus.SessionBus() _dbus_screensaver = _session_bus.get_object('org.freedesktop.ScreenSaver','/ScreenSaver') simulate_activity = _dbus_screensaver.get_dbus_method('SimulateUserActivity','org.freedesktop.ScreenSaver') simulate_activity() ``` In bash: ``` qdbus org.freedeskt...
I have the following code which stores string-input from a user N times in a multidimensional array. And then print out the second element. ``` main() { // Array to store 10 strings, 20 characters long. char strStorage[10][20]; printf("\nEnter how many strings: "); scanf( "%d" , &num); fflush(st...
strStorage[2]is thethirdstring, so ifnumis less than3, you won't initialize it and it will contain garbage.
I've a strange problem with CMake. I'm importing Curl into my project, so I write for you a simplified summary of my CMakeLists.txt file. ADD_LIBRARY (libcurlSHAREDIMPORTED)SET_PROPERTY(TARGET libcurl PROPERTY IMPORTED_LOCATION ../lib/libcurl.lib) When I run CMake it generates the project files for MS VC++ (also fo...
For a shared library, theIMPORTED_LOCATIONmust point to the DLL, not the import lib. See thedocumentation. You might also want to set theIMPORTED_IMPLIBproperty. BTW, CMake also has afind packagefor Curl; perhaps you could use that?
I try to build profiler to some c project. I want that gcc plant some assembly instruction in all the function entries and function exit points in compile time. I try to search some guides in the web but without success. where can I learn how to do that? thank in advance.
Apparently you can use the-finstrument-functionsflag to get gcc to generate instrumentation calls ``` void __cyg_profile_func_enter(void *func, void *callsite); void __cyg_profile_func_exit(void *func, void *callsite); ``` at function entry and exit. I've never used this, but a quick search brings up information an...
This question already has answers here:Why do I always get the same sequence of random numbers with rand()?(12 answers)Closed10 years ago. I'm working on an application. I'm using: ``` int rand_num = rand() % 100; ``` To get a random integer between 0 to 99. Now, let's say I got 41, then restarting my application, ...
You have to randomize the seed by callingsrand(...)(usually withtime(0)) whenever you start your application. Note that it is a pseudo-random number generator i.e. the values generated by therand()function are not uniformly distributed.
How can I determine the type of file-system that a file is stored on? I might have the filename, or later, just a descriptor. I would happily use a script at first, but would likealsoto know how to do it with syscalls from C.
On the command line/script, You can usestat: ``` $ stat -f -c "%T" someFileOnExt2Ext3 ext2/ext3 $ stat -f -c "%T" someFileOnNFS nfs ``` This eventually leads to thestatfs(2)system call: ``` int statfs(const char *path, struct statfs *buf); ``` The function statfs() returns information about a mounted file system....
I am currently using the zint barcode library for generating barcodes in my application. It works very fine and generates in .txt, .eps,.svg formats. It also supports ".png" format, but the problem is as the header file "png.h" is missing, im not able to generate barcodes in "png" format. The zint version i am using ...
What platform are you developing on? It sounds like you need to install the PNG development libraries. For example, if you are on Ubuntu, 'apt-get install libpng-dev'.
On SDL 2, there is the functionSDL_GL_MakeCurrent, is there any thing like that for SDL 1.2?
Not in the public API, no. Theprivate video backend interfacehas a function pointer for it though.
I have a c++ application, which contains large amount ofstd::cout. It runs on linux 2.6.x. I need to test the performance of the application, so i am thinking of redirecting thestd::coutto/dev/null. In C, i could simply usedup2. Is there an equivalent in c++ to redirectstd::ostreamto a file or/dev/null?
Thedup2trick will still work in C++, since just like<stdio.h>,<iostream>is just a buffering layer atop the UNIX system calls. You can also do this at the C++ level by disconnecting the buffer fromstd::cout: ``` std::cout.rdbuf( NULL ); ``` Besides severing the relationship betweenstd::coutand any actual output devi...
I have a gtk drawing area embedded in a gtk frame, in a gtk window. I have a callback function responding to "draw" signal that draws something to drawing area initially. Now I have another function that responds to the "click" signal emitted by a few buttons. Each time a button is clicked, i would like to draw som...
It's been a while since I've done anything with Gtk+, but I believe what you want to do is callgtk_widget_queue_draw_area()inside the"click"handler, then do the drawing in response to the "draw" signal that will eventually be raised.
I've a strange problem with CMake. I'm importing Curl into my project, so I write for you a simplified summary of my CMakeLists.txt file. ADD_LIBRARY (libcurlSHAREDIMPORTED)SET_PROPERTY(TARGET libcurl PROPERTY IMPORTED_LOCATION ../lib/libcurl.lib) When I run CMake it generates the project files for MS VC++ (also fo...
For a shared library, theIMPORTED_LOCATIONmust point to the DLL, not the import lib. See thedocumentation. You might also want to set theIMPORTED_IMPLIBproperty. BTW, CMake also has afind packagefor Curl; perhaps you could use that?
I try to build profiler to some c project. I want that gcc plant some assembly instruction in all the function entries and function exit points in compile time. I try to search some guides in the web but without success. where can I learn how to do that? thank in advance.
Apparently you can use the-finstrument-functionsflag to get gcc to generate instrumentation calls ``` void __cyg_profile_func_enter(void *func, void *callsite); void __cyg_profile_func_exit(void *func, void *callsite); ``` at function entry and exit. I've never used this, but a quick search brings up information an...
This question already has answers here:Why do I always get the same sequence of random numbers with rand()?(12 answers)Closed10 years ago. I'm working on an application. I'm using: ``` int rand_num = rand() % 100; ``` To get a random integer between 0 to 99. Now, let's say I got 41, then restarting my application, ...
You have to randomize the seed by callingsrand(...)(usually withtime(0)) whenever you start your application. Note that it is a pseudo-random number generator i.e. the values generated by therand()function are not uniformly distributed.
How can I determine the type of file-system that a file is stored on? I might have the filename, or later, just a descriptor. I would happily use a script at first, but would likealsoto know how to do it with syscalls from C.
On the command line/script, You can usestat: ``` $ stat -f -c "%T" someFileOnExt2Ext3 ext2/ext3 $ stat -f -c "%T" someFileOnNFS nfs ``` This eventually leads to thestatfs(2)system call: ``` int statfs(const char *path, struct statfs *buf); ``` The function statfs() returns information about a mounted file system....
I am currently using the zint barcode library for generating barcodes in my application. It works very fine and generates in .txt, .eps,.svg formats. It also supports ".png" format, but the problem is as the header file "png.h" is missing, im not able to generate barcodes in "png" format. The zint version i am using ...
What platform are you developing on? It sounds like you need to install the PNG development libraries. For example, if you are on Ubuntu, 'apt-get install libpng-dev'.
On SDL 2, there is the functionSDL_GL_MakeCurrent, is there any thing like that for SDL 1.2?
Not in the public API, no. Theprivate video backend interfacehas a function pointer for it though.
I have a c++ application, which contains large amount ofstd::cout. It runs on linux 2.6.x. I need to test the performance of the application, so i am thinking of redirecting thestd::coutto/dev/null. In C, i could simply usedup2. Is there an equivalent in c++ to redirectstd::ostreamto a file or/dev/null?
Thedup2trick will still work in C++, since just like<stdio.h>,<iostream>is just a buffering layer atop the UNIX system calls. You can also do this at the C++ level by disconnecting the buffer fromstd::cout: ``` std::cout.rdbuf( NULL ); ``` Besides severing the relationship betweenstd::coutand any actual output devi...
I have a gtk drawing area embedded in a gtk frame, in a gtk window. I have a callback function responding to "draw" signal that draws something to drawing area initially. Now I have another function that responds to the "click" signal emitted by a few buttons. Each time a button is clicked, i would like to draw som...
It's been a while since I've done anything with Gtk+, but I believe what you want to do is callgtk_widget_queue_draw_area()inside the"click"handler, then do the drawing in response to the "draw" signal that will eventually be raised.
I am writing an ANSI C cgi-bin server program. Each instance of program can access to the same files simultaneously. I do as follows: ``` handle = fopen(name,type); fd = fileno(handle); MyLockFile(fd) //I use fcntl ..... ``` The problem is that I open file with "fopen", not with "open". Will "locking" work in such ...
Your open() function is wrong, when you specify O_CREAT, the permission bits needs to be the 3. argument, e.g. ``` open(name,O_CREAT|O_WRONLY, S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); ```
I want to call a function, lets say every 10 or 20 seconds. When I searched, I came up with threads andsleep()method everywhere. I also checked for time and clock classes in C but I could not find anything helpful specific to my question. What is the most simple way to call functions periodically?
Uselibevent, in my opinion, is the cleaner solution because, in the meantime, you can do other operations (even other timed functions) look at this simple and self explaining example that print out Hello every 3 seconds: ``` #include <stdio.h> #include <sys/time.h> #include <event.h> void say_hello(int fd, short ev...
Why when we want to convert an ASCII value of a digit into an integer, we need to do: value - '0'? And the other way around, to convert Integer to ASCII, we need to do: ``` value + '0' ``` Why is that?
Because the integral values of the digit characters are guaranteed by the C standard to be consecutive. Therefore'1' - '0' == 1,'2' - '0' == 2, etc. from which you can infer that your formulas really do work. Sidenotes: Since this is guaranteed by the standard, it works even if the target platform does not use ASCI...
I have a problem with a text file which contains a list of 55 random numbers (all in one column). What I'm trying to do is to ask the user to choose a line number so that I can bring it up but I dont know what to put in the code for this. I'm trying to do a little game, the whole point is to ask the user to choose a ...
Look at thefgets()function in the standard library, it's one of the best ways to read a line of text.
Why Static variables are assigned a value 0?
Because the standard mandates that this is true. §6.7.8.10 of the C99 standard says: If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:— if it has pointer type, it is initialize...
If I declare two arrays -arr1andarr2- of, say, typeintof size 10 each, and initialize first array, and I wish to create a copy ofarr1inarr2; why can't I just give the instructionarr2 = arr1? I know two structures of same type can be assigned. Why is that not the case with arrays?
The problem with arrays is that in all expressions (except when passed to thesizeofand the unary&operators) they convert to a pointer to their first element. So, supposing you have: ``` int arr1[10]; int arr2[10]; ... ``` Then if you write something like ``` arr1 = arr2; ``` you are actually attempting to do this...
I am writing an ANSI C cgi-bin server program. Each instance of program can access to the same files simultaneously. I do as follows: ``` handle = fopen(name,type); fd = fileno(handle); MyLockFile(fd) //I use fcntl ..... ``` The problem is that I open file with "fopen", not with "open". Will "locking" work in such ...
Your open() function is wrong, when you specify O_CREAT, the permission bits needs to be the 3. argument, e.g. ``` open(name,O_CREAT|O_WRONLY, S_IREAD|S_IWRITE|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); ```
I want to call a function, lets say every 10 or 20 seconds. When I searched, I came up with threads andsleep()method everywhere. I also checked for time and clock classes in C but I could not find anything helpful specific to my question. What is the most simple way to call functions periodically?
Uselibevent, in my opinion, is the cleaner solution because, in the meantime, you can do other operations (even other timed functions) look at this simple and self explaining example that print out Hello every 3 seconds: ``` #include <stdio.h> #include <sys/time.h> #include <event.h> void say_hello(int fd, short ev...
Why when we want to convert an ASCII value of a digit into an integer, we need to do: value - '0'? And the other way around, to convert Integer to ASCII, we need to do: ``` value + '0' ``` Why is that?
Because the integral values of the digit characters are guaranteed by the C standard to be consecutive. Therefore'1' - '0' == 1,'2' - '0' == 2, etc. from which you can infer that your formulas really do work. Sidenotes: Since this is guaranteed by the standard, it works even if the target platform does not use ASCI...
I have a problem with a text file which contains a list of 55 random numbers (all in one column). What I'm trying to do is to ask the user to choose a line number so that I can bring it up but I dont know what to put in the code for this. I'm trying to do a little game, the whole point is to ask the user to choose a ...
Look at thefgets()function in the standard library, it's one of the best ways to read a line of text.
Why Static variables are assigned a value 0?
Because the standard mandates that this is true. §6.7.8.10 of the C99 standard says: If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:— if it has pointer type, it is initialize...
If I declare two arrays -arr1andarr2- of, say, typeintof size 10 each, and initialize first array, and I wish to create a copy ofarr1inarr2; why can't I just give the instructionarr2 = arr1? I know two structures of same type can be assigned. Why is that not the case with arrays?
The problem with arrays is that in all expressions (except when passed to thesizeofand the unary&operators) they convert to a pointer to their first element. So, supposing you have: ``` int arr1[10]; int arr2[10]; ... ``` Then if you write something like ``` arr1 = arr2; ``` you are actually attempting to do this...
Can anyone tell me what would be the cause of the error /mysql_com.h:306:5: error: token @ is not valid in preprocessor expressions while this mysql_com.h file does not contain any@. So how can I fix this error. I think it's similar to the error when we open windows edited file in linux, then at that time^V appers...
Looks like this sort of problem has been reported when a '.h.in' file is included at some point, instead of the usual '.h' header file (eg.this) - perhaps because of some missing files or misconfigured include paths? As has been previously suggested, I'd try tracing things back through the definition ofMYSQL_VERSION_...
Right now, when I use write system call over and over again, it just appends to a file lets call file.txt if I were to call sys call write in C, on file.txt, it would just constantly. There is a circumstance where given that same file, I want to erase everything from it, and add just one line. How would I go by doing ...
Just calltruncateorftruncateto cut the file to zero bytes. Then write the line you want. You don't need to close or re-open the file, you can use your existing handle.
I'm using the C libYAML library for handling YAML configuration files, and I a little confused about this struct element in its code: ``` /** The stack of mapping pairs (key, value). */ struct { /** The beginning of the stack. */ yaml_node_pair_t *start; /** The end of the stack. */ yaml_node_pair_t *...
Start and end refer to the maximum boundaries of the stack. The top is a dynamic pointer referring to the current position, and changes as you call nested levels of functions.
the error is : request for member 'a' in something not a structure or union. ``` #include<stdio.h> typedef struct mia { int a; }hola; typedef struct m { hola **r; }bic; int main() { bic y; scanf("%d", &(y.r->a)); printf("%d", (y.r->a)); return 0; } ```
You will need a more complex syntax for this should do it: ``` int main() { hola x; hola *ptr = &x; bic y = { &ptr }; scanf("%d", &((*y.r)->a)); printf("%d\n", (*y.r)->a); printf("%d\n", ptr->a); printf("%d\n", x.a); return 0; } ``` Input ``` 100 ``` Output ``` 100 100 100 ``` N...
How do you append a number to an LPCTSTR? A library I am using takes an LPCTSTR for a com port address. I know how to do this with char* , but not with a LPCTSTR. This is what I want to do (assuming sprintf as is worked with these, which I know it doesn't) ``` LPCTSTR PortString; int ComPortNumber; sprintf(PortSt...
You can use the secure versions from tchar.h. ``` TCHAR PortString[32]; int ComPortNumber; _stprintf_s( PortString, 32, _T("COM%d"), ComPortNumber ); ``` http://msdn.microsoft.com/en-us/library/ce3zzk1k%28VS.80%29.aspx
I am trying to build WildMagic 5.9 on Visual Studio 2012 but here are error: ``` Error 3 error C2039: 'greater' : is not a member of 'std' c:\wildmagic5\libmathematics\intersection\wm5intrellipsoid3ellipsoid3.cpp 142 1 LibMathematics_VC100 ``` Why? What to fix to get this to compile?
Need include: ``` include <functional> ```
If I have a buffer in memory, which contains an image in YUV format, how can I save the buffer contents to a file, i.e., what file format should I use, and can I view the file later in an image viewer?
If you're in a hurry and it's proprietary, just dump it out. It's a lot easier than linking to PNG or TIFF libraries and getting the support code right. I don't seem to recall most image viewers supporting UYVY format. This would be for television video, right? I used to just use my own formats and have a Cg shade...
This question already has answers here:Receiving a part of packet via recvfrom (UDP)(2 answers)Closed10 years ago. In simple client-server program, Client is sending 12 bytes of data. I am using recvfrom(), requesting 2 and 10 bytes in successive calls. In case of first call recvfrom() is returning 2 bytes. But secon...
Theman pagehas the following pertinent information (bold added): For message-based sockets, such as SOCK_RAW, SOCK_DGRAM, and SOCK_SEQPACKET, the entire message shall be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument,the excess bytes s...
I am using the Big Nerd Ranch book Objective-C Programming, and it starts out by having us write in C in the first few chapters. In one of my programs it has me create, I use the sleep function. In the book it told me to put#include <stdlib.h>under the#include <stdio.h>part. This is supposed to get rid of the warning ...
The sleepman pagesays it is declared in<unistd.h>. Synopsis: ``` #include <unistd.h> ``` unsigned int sleep(unsigned int seconds);
Given these strings ``` char * foo = "The Name of the Game"; char * boo = "The Name of the Rose" ``` I want to determine the address of the first mismatched character, in order to extract the common header ("The Name of the"). I know the hand-coded loop is trivial, but I'm curious if there's any variant ofstrcmp(...
Nope. No such standardstring.hfunction exists.
I have an issue with sockets. I'm creating a socket between my computer and my phone to send messages. When I close the server or the client it sends a FIN packet and it stays in the FIN_WAIT2 state for like a minute. However, the other side get stuck in the CLOSE_WAIT state, apparently incapable of closing the socket...
You need to close both ends of a socket channel. If the server closes a connection to a client, the client needs to close the connection on the client-end, for the lastFINpacket to be transmitted (from client to server). This will trigger the last state transition in theTCP state machine.
I know the default page size of a 32-bit process running on 32-bit Windows is 4K, whereas that of a 64-bit process running on 64-bit Windows is 8K. However, what is the actual page size of a 32-bit process running on 64-bit Windows (i.e. WOW64) ? 4K? 8K?
Ideally, you should callGetSystemInfo()and examineSYSTEM_INFO.dwPageSize. Btw, I doubt that you have 8KB pages in 64-bit Windows. x86/64 CPUs support pages of the following sizes: 4KB (all modes), 4MB (32-bit non-PAE), 2MB (32/64-bit PAE), 1GB (64-bit, always PAE). You can find this in the CPU manual from Intel (or A...
Hi I'm trying to do something which should be simple, but I can't figure it out. I have a pointer to an array of unsigned chars, and I get the first element, which is a hex number. I want to convert it to binary so I can check if it's equal to a number such as 0x01101000. ``` unsigned char arr[] = {0x25}; //just fo...
Seethisanswer. If you are using GCC then you can use GCC extension for this: int x = 0b00010000; So in your case, it would be: ``` if( byte == 0b01101000 ) ... ``` Be sure to put only 8 bits in your literal though.
I have an application which writes data (control data, access information etc) to one end of the pipe at parent process. At the child process, I want to read that data as it is. Parent process performs many write() operation at many location. For reading the data into the buffer, we need to specify the length of the ...
Two most common and simplest methods are to either write the length first in a fixed-size, or to have a special record-terminator that tells that the record has ended.
I have a function that takes in pointers to different arrays which can look like this: ``` unsigned char *arr[] = {0x34, 0x10, 0x3f, 0x00, 0x00 } ``` I want to know how many elements (bytes) are in each array my function is getting. For example, I need a way to find that this array has 5 bytes. I pass this into a fu...
Unless you're using a convention like "the array is null-terminated" (like C strings nominally are) you can't determine the size of the array at run-time. All you have at that point is a pointer.
The below code in unix takes ~9s reported bytimecommand. ``` int main() { double u = 0; double v = 0; double w = 0; int i; for (i = 0;i < 1000000000;++i) { v *= w; u += v; } printf("%lf\n",u); } ``` I don't understand why the execution times almost double when i changev *=...
When you changev *= wtov *= uthen there is an inter-dependency between the 2 statements. Hence, the first statement has to be completed before executingu += vwhich could be the reason for the increased performance as the compiler can't parallelize the execution.
I know in C, one way to solve the "initializer element is not constant" error is to create the strcuture inside the main() function. But suppose that I have an array of structs and want to use it as a global array. How can I create and initialize it? ``` struct A *b = malloc(10*sizeof(struct A)); // Want to keep the ...
If you want an array, why don't you declare it as an array? ``` struct A { const char *str; int n; }; struct A b[3] = { { "foo", 1 }, { "bar", 2 }, { "baz", 3 } }; ``` If youwanta global pointer, thenusea global pointer: ``` struct A *b; int main() { b =...
I'm currently adding Toolbar controls to a Windows application. I noticed going through the documentation (MSDN Toolbar) that there's no message or function to remove strings from a Toolbar control, which seems strange since buttons and images can be removed. It's not exactly essential to have this feature, just wonde...
For anyone else that comes across this problem I solved it by using theTB_SETBUTTONINFOmessage to set button text. This way you don't have to add strings to a Toolbar control's string pool. ``` #define ID_BUTTONCOMMAND 101 //... TBBUTTONINFO tbButtonInfo; tbButtonInfo.cbSize = sizeof( TBBUTTONINFO ); tbButtonI...
``` static inline int my_function() __attribute__((always_inline)); static inline int my_function() { //... } ``` So I have declared my function as above although in the binary the function is branched to and not inlined, therefore a simple NOP could render the whole function useless. How can I force Xcode 4...
Your function as you give it here has no prototype: you don't provide the type of the arguments. In C just having()in the declaration means that the function receives an unknown number of arguments. Probably the compiler then supposes not to know enough about the function to inline it. Use(void)to declare a function w...
My codes are like this: ``` #include <iostream> using std::cout; using std::endl; int main(int argc, char *argv[]) { cout << (int)('\0') << endl; cout << (char)(0) << endl; return 0; } ``` I expected to see in terminal like this: ``` $ test-program 0 $ ``` However, what I saw is like this: ``` $ tes...
^@is just how your terminal emulator renders'\0'.
I am trying to write my own C floor function. I am stuck on this code detail. I would just like to know how I can zero out the bottom n bits of an unsigned int. For example, to round 51.5 to 51.0, I need to zero out the bottom 18 bits, and keep the top 14. Since it's a floor function, I want to make a mask to zero ou...
A much simpler way is doing just this: ``` value = (value >> bits) << bits ``` because the shift left will fill it in with zeroes, not whatever was in there.
In C, I encountered an error when I coded the following example: ``` int *pointer; int i = 0; pointer = malloc(10 * sizeof(int)); pointer[i - 1] = 4; ``` Clearlyiis a negative index intopointer. Even if the incorrect piece memory was altered, why was an error only triggered uponfree(pointer)[later on in the code]? ...
Most if not all memory managers (eg: malloc) allocate extra data around the memory you've requested. This extra is to help the memory manager manage the various allocations by adding some of its own data to the allocation. When you did your negative index, you overwrote this extra data. It's not invalid memory per se,...
What I want to do isNOTinitilize a pointer that aligned to a given boundary, instead, it is like some function that can transform/copy the pointer (and the contents it is pointed to)'s phyiscal address to a aligned memory address back and forth, likealignedPtr()in the following code: ``` void func(double * x, int len...
Assuming that the size of the allocated buffer is sufficiently large i.e.len+ alignment required, the implementation would require 2 steps. newPtr = ((orgPtr + (ALIGNMENT - 1)) & ALIGN_MASK);- This will generate the new pointerSince the intended design is to have an inplace computation, copy fromnewPtr + lenbackwards...
How do I open an external EXE file from inside C? I'm trying to write a C program that opens Notepad, and some other applications and I am stuck. Thanks for putting up with my noob level of C ;p
Please trysystem("notepad");which will open the notepad executable. Please note that the path to the executable should be part ofPATHvariable or the full path needs to be given to thesystemcall.
I am wondering if it is possible to connect two pipes or socket. Lets suppose that have two pipes/socketpairs. The first one has two file descriptors A and B, the second one has two file descriptors C and D. Is it possible to connect B to C to be able to write to A and read the data from D? Other then just reading for...
If you simply want to read from one socket and write to another without copying the data to user-space, look athttp://linux.die.net/man/2/sendfile. You need a fairly recent Linux.
I'm writing some self-modifying code and I want to call a C function (call itfoo) from MIPS. I've loaded the mem add offoo,&foointo$t1. Now Ijr/jalr $t1. Will C set$raas my current PC(+8) (before the jump) allowing me to useJRor will I have toJALRinstead (ie, take care of it because C won't)? I can't test this righ...
You have to useJALR. How could the C function possibly know how to set$rafor you?
I am experiencing a strange behaviour for send() function the call , where socketfd is 0, p is "test\n" , length is 5 , flags is 0 : ``` size_t n = 0; n = send(socketfd, p, length, flags); ``` send seems to return a value in n 18446744073709551615 The function documentation says it returns -1 on error. The code...
size_tis an unsigned type, it can't contain negative values. In fact if you check the manpage of send, its return type isssize_t, which is the signed version and can contain negative values. Try changing the type.
I've been looking for a way to convert a string (in Epoch time) into a date. Basically, I need to take this:1360440555(in string form) and make it into this:Feb 9 12:09 2013. I've been looking at strptime and strftime, but neither seems to be working for me. Any suggestions? Edit: Thanks, guys. I converted it to a...
If only you had that value in an integer instead of a string, you could just callctime. If only there were some way to convert a string to an integer.... ``` time_t c; c = strtoul( "1360440555", NULL, 0 ); ctime( &c ); ```
Issize_tthe word size of the machine that compiled the code? Parsing with g++, my compiler viewssize_tas anlong unsigned int. Does the compiler internally choose the size ofsize_t, or issize_tactually typdefed inside some pre-processor macro instddef.hto the word size before the compiler gets invoked? Or am I way of...
In the C++ standard, [support.types] (18.2) /6: "The typesize_tis an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object." This may or may not be the same as a "word size", whatever that means.
I want to create aqueue timer. I callCreateTimerQueueTimerbut it doesn't compile because it says undefined reference to CreateTimerQueueTimer and I showed the linker the path to the Kernel32.lib. I use CodeBlocks, right click on project name -> Build Option -> Linker Setting tab -> then clicked Add and went to the ...
CreateTimerQueueTimer is a more recent API in Win32. To enable it you need to define _WIN32_WINNT as 0x0500 or later. Add to your preproccessor defines _WIN32_WINNT=0x0500.