question
stringlengths
25
894
answer
stringlengths
4
863
Currently I have some C code which will every time an arrow key is pressed it will reprint an array of characters to the screen and change only the player's position one spot. I would like to know how to only reprint the two characters that are actually changing, instead of reprinting the entire array of characters. ...
ncursesis a nice portable library which handles terminal graphics; I'd definitely recommend it for your purposes.
This is an interview question.We are given dimensions of various rectangles, we have to find out the area(minimum) of rectangle that can enclose all of them? rectangles can be rotated also . ``` test case:- input: 3 //number of rectangles 8 8 4 3 3 4 output: 88 11x8: + - - - - - - + + - + | | | | | ...
There is no absolute solution to this problem, but there are several approximate solutions, you can read about some of themhere.
Having a C or C++ source code how i can convert those statements in x86 and ARM assembly? And with that i mean a plain text file containing assembly written source code from my C/C++ equivalent source code. edit: i use GCC/CNU toolchains
You will need a cross compiler that can do both then just use ``` g++ -S [Plus all you other switch's and cross compile ones] ``` This will save the intermediate assembler for you
I am trying to use the following C code to print out an array that I have passed in. It should output the text in hexadecimal format one on each line and I have no problems opening the file. When I first wrote it, I had no problems with it working I opened the output file and my array was there. I changed thefileO...
Always clean up after yourself. You're missing anfclose(pOutfile).
While usingzlib 1.2.7andminizipto read zip archives, I found that its only possible for me to read into a byte buffer. I'm passing this data over to another library for processing, but this library requires that the data be in the form of aFILE*. Is it possible for me to create aFILE*using a byte buffer in memory?
Why is this question using a C++ tag? C's isn't extensible with respect to its sources and destinations. Thus, you'd need to rely on platform specific extensions. In C++ you can create a suitable stream buffer to plug things into IOStreams. However, a .zip archive is an archive not a flat file, i.e., you'd need to th...
I want to change the variable's value in the function. my code is like this: ``` void change(char *buf){ char str = "xxxxxxx"; *buf = &str; } int main(){ char *xxx = NULL; change(xxx); } ``` when I debug with valgrind, it says: ``` ==3709== Invalid write of size 1 ==3709== at 0x80483CA: change (t...
Use a pointer to a pointer: ``` void change(char **buf) { *buf = "xxxxxxx"; } int main(void) { char *xxx = NULL; change(&xxx); } ```
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question does somebody know a library (language does not care) for song recognition like the Services provided by Shazzam and Sound...
Yes.http://echonest.comoffer an online API for this. IIRC they're working in collaboration withhttp://musicbrainz.org(a huge, open music database) to gather acoustic fingerprints on the musicbrainz catalogue. Both have a comprehensive selection of open source tools on github related to this activity. You can download ...
I saw this one in one of the .h files provided by my professor for a project, but I'm not too sure what this means. ``` int (*get_console_dev)(void); ``` Is it the same as ``` (int*) get_console_dev(void); ``` (a function named get_console_dev, which returns a pointer to anint?) Thanks
It's a function pointer that can point to a function returningintand taking 0 parameters; it's not equivalent to the second line you posted.
This is an interview question.We are given dimensions of various rectangles, we have to find out the area(minimum) of rectangle that can enclose all of them? rectangles can be rotated also . ``` test case:- input: 3 //number of rectangles 8 8 4 3 3 4 output: 88 11x8: + - - - - - - + + - + | | | | | ...
There is no absolute solution to this problem, but there are several approximate solutions, you can read about some of themhere.
Having a C or C++ source code how i can convert those statements in x86 and ARM assembly? And with that i mean a plain text file containing assembly written source code from my C/C++ equivalent source code. edit: i use GCC/CNU toolchains
You will need a cross compiler that can do both then just use ``` g++ -S [Plus all you other switch's and cross compile ones] ``` This will save the intermediate assembler for you
I am trying to use the following C code to print out an array that I have passed in. It should output the text in hexadecimal format one on each line and I have no problems opening the file. When I first wrote it, I had no problems with it working I opened the output file and my array was there. I changed thefileO...
Always clean up after yourself. You're missing anfclose(pOutfile).
While usingzlib 1.2.7andminizipto read zip archives, I found that its only possible for me to read into a byte buffer. I'm passing this data over to another library for processing, but this library requires that the data be in the form of aFILE*. Is it possible for me to create aFILE*using a byte buffer in memory?
Why is this question using a C++ tag? C's isn't extensible with respect to its sources and destinations. Thus, you'd need to rely on platform specific extensions. In C++ you can create a suitable stream buffer to plug things into IOStreams. However, a .zip archive is an archive not a flat file, i.e., you'd need to th...
I want to change the variable's value in the function. my code is like this: ``` void change(char *buf){ char str = "xxxxxxx"; *buf = &str; } int main(){ char *xxx = NULL; change(xxx); } ``` when I debug with valgrind, it says: ``` ==3709== Invalid write of size 1 ==3709== at 0x80483CA: change (t...
Use a pointer to a pointer: ``` void change(char **buf) { *buf = "xxxxxxx"; } int main(void) { char *xxx = NULL; change(&xxx); } ```
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question does somebody know a library (language does not care) for song recognition like the Services provided by Shazzam and Sound...
Yes.http://echonest.comoffer an online API for this. IIRC they're working in collaboration withhttp://musicbrainz.org(a huge, open music database) to gather acoustic fingerprints on the musicbrainz catalogue. Both have a comprehensive selection of open source tools on github related to this activity. You can download ...
I saw this one in one of the .h files provided by my professor for a project, but I'm not too sure what this means. ``` int (*get_console_dev)(void); ``` Is it the same as ``` (int*) get_console_dev(void); ``` (a function named get_console_dev, which returns a pointer to anint?) Thanks
It's a function pointer that can point to a function returningintand taking 0 parameters; it's not equivalent to the second line you posted.
I am trying to write a C program using GSL to find the roots of a cubic equation following the instructions here:http://www.gnu.org/software/gsl/manual/html_node/Cubic-Equations.html. This is what I came up with: ``` #include <stdio.h> #include <gsl/gsl_poly.h> double *x0,*x1,*x2; int roots; int main (void) { r...
x0, x1 and x2 are just dangling pointers - change the code to: ``` double x0,x1,x2; int roots; int main (void) { roots = gsl_poly_solve_cubic(0,0,0,&x0,&x1,&x2); printf( " %d ", roots); return 0; } ```
I was wondering if there was a way in C language to define#definelike this: ``` #define something #define something a 42 something b 42 ```
No, it's not possible in C. Defining a macro in another macro is not allowed. FromC standard: 6.10.3.4 Rescanning and further replacement3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, but all pragma unary operator ex...
I need to do two things to an array in C: Summing its entries.Finding the position of all non-zero entries. I am doing both by looping through each element of the array. E.g. ``` int sum_array(int a[], int num_elements) { int i, sum=0; for (i=0; i<num_elements; i++) { sum = sum + a[i]; } return(...
For part 2, you don't really have to do any work. if the value in the array is zero, then it would evaluate to false. Any non-zero value would evaluate to true. So you can iterate through the array any time, and ignore the zero values.
C++ hasstd::endl. Does anyone know of anything in C to use for this?
std::endlhas the effect of printing a newline'\n'character and then flushing the output stream. The C equivalent, if you're printing to stdout, would be: ``` putchar('\n'); fflush(stdout); ``` But in most cases thefflushis unnecessary. Note thatstd::endldoesnothave the purpose of providing a platform-independent l...
If we solve an infix expression in to postfix expression with braces and without braces will both of them produce same result? Example: ((2+8)x9)-(5x(5+2))2+8*9-5*5+2 Will both of these examples produce the same results? If No, then why not?
In general, it will not produce the same result, due to the precedence of the operations. For example, if you define*to have higher precedence than+and-, then*must be evaluated before+or-, which changes how the expression is calculated, and also changes the post-fix representation.
I use the following code a lot in C: ``` typedef struct { int member; } structname; ``` Now i'm trying to keep that struct definition local to a particular source file, so that no other source file even knows the struct exists. I tried the following: ``` static typedef struct { int member; } structname...
If you declare the typedef struct within a .c file, it will be private for that source file. If you declare this typedef in a .h file, it will be accesible for all the .c files that include this header file. Your statement: ``` static typedef struct ``` Is clearly illegal since you are neither declaring a variable...
I'm trying to make a deep copy of an array in C (originalBoard being the copy): ``` int gy, gx; for (gy=0; gy<9; gy++) { for (gx=0; gx<9; gx++) { g.originalBoard[gy][gx]=g.board[gy][gx]; } }...
I think you need this: ``` //assuming g.originalBoard is array of array of integers and same for g.board int *originalBoard = malloc(sizeof(g.board)); memcpy(originalBoard, g.board, sizeof(g.board)); ```
In C the following is valid code: ``` if ((a, a+b, a*b) >= 0) { .... } ``` Does the(a, a+b, a*b)part have a special name?
x, yis called a comma expression. ,is called the comma operator in C and(x, y, z)is the same as((x, y), z). It must not be confused with the comma that separates function arguments and which is not the comma operator.
In linux I can get the list of opened posix shared memory segments by getting/dev/shmdirectory listing. How do I programmatically get list of all opened posix shared memory segments in FreeBSD? Assuming segments opened withshm_open()and I don't know even a part of a name that was used as a first argument ofshm_open()...
You can't. See the comment in /sys/kern/uipc_shm.c: ``` * TODO: * * (2) Need to export data to a userland tool via a sysctl. Should ipcs(1) * and ipcrm(1) be expanded or should new tools to manage both POSIX * kernel semaphores and POSIX shared memory be written? * * (3) Add support for this file type...
The question is: ``` int z, x=5, y=-10 ,a=4, b=2; z = x++ - --y * b / a; ``` Just wanted to know the output and how --y will work for the negative value of 'y'. What will be the precedence of solving this?
``` int z, x=5, y=-10 ,a=4, b=2; z = x++ - --y * b / a; z = 5++ - --(-10) * 2 / 4 // Suffix ++/-- goes first z = 5 - --(-10) * 2 / 4 // Prefix ++/-- is next z = 5 - (-11) * 2 / 4 // and then * and / z = 5 - (-22) / 4 z = 5 - (-5) z = 10 ``` Unlike y, x keeps it's value because in suffix notation the operator returns ...
I am porting a win32 app to linux and instead of having bunch of #ifdefs around every _snprintf_s, I was wondering if there is a way to #define it to snprintf somehow. So something like - ``` #define _snprintf_s(1,2,3,4,5) snprintf(1,2,4,5) ``` The third parameter, Maximum number of characters to store, or _TRUNCAT...
#define _snprintf_s(a,b,c,...) snprintf(a,b,__VA_ARGS__)
If I have a struct such as: ``` typedef struct bag { int test; } *bag; ``` Then if a function consumes bag. Let's say: ``` int sample(bag *b) { b->test ... } ``` I get the error that I made a request for member 'b' in something that is not a structure or union. How do I fix this? I could cast b to a (struct ...
You just defined the typebagto be apointerto the typestruct bag. Thus, when you make a variable of typebag *b, you are effectively creating a variable of typestruct bag**. Either change your argument to bebag b, or do a double dereference for your member ((*b)->test). EditAs another poster mentioned, you probably m...
I'm trying to make a deep copy of an array in C (originalBoard being the copy): ``` int gy, gx; for (gy=0; gy<9; gy++) { for (gx=0; gx<9; gx++) { g.originalBoard[gy][gx]=g.board[gy][gx]; } }...
I think you need this: ``` //assuming g.originalBoard is array of array of integers and same for g.board int *originalBoard = malloc(sizeof(g.board)); memcpy(originalBoard, g.board, sizeof(g.board)); ```
In C the following is valid code: ``` if ((a, a+b, a*b) >= 0) { .... } ``` Does the(a, a+b, a*b)part have a special name?
x, yis called a comma expression. ,is called the comma operator in C and(x, y, z)is the same as((x, y), z). It must not be confused with the comma that separates function arguments and which is not the comma operator.
In linux I can get the list of opened posix shared memory segments by getting/dev/shmdirectory listing. How do I programmatically get list of all opened posix shared memory segments in FreeBSD? Assuming segments opened withshm_open()and I don't know even a part of a name that was used as a first argument ofshm_open()...
You can't. See the comment in /sys/kern/uipc_shm.c: ``` * TODO: * * (2) Need to export data to a userland tool via a sysctl. Should ipcs(1) * and ipcrm(1) be expanded or should new tools to manage both POSIX * kernel semaphores and POSIX shared memory be written? * * (3) Add support for this file type...
The question is: ``` int z, x=5, y=-10 ,a=4, b=2; z = x++ - --y * b / a; ``` Just wanted to know the output and how --y will work for the negative value of 'y'. What will be the precedence of solving this?
``` int z, x=5, y=-10 ,a=4, b=2; z = x++ - --y * b / a; z = 5++ - --(-10) * 2 / 4 // Suffix ++/-- goes first z = 5 - --(-10) * 2 / 4 // Prefix ++/-- is next z = 5 - (-11) * 2 / 4 // and then * and / z = 5 - (-22) / 4 z = 5 - (-5) z = 10 ``` Unlike y, x keeps it's value because in suffix notation the operator returns ...
I am porting a win32 app to linux and instead of having bunch of #ifdefs around every _snprintf_s, I was wondering if there is a way to #define it to snprintf somehow. So something like - ``` #define _snprintf_s(1,2,3,4,5) snprintf(1,2,4,5) ``` The third parameter, Maximum number of characters to store, or _TRUNCAT...
#define _snprintf_s(a,b,c,...) snprintf(a,b,__VA_ARGS__)
By default,libboostpython.ais compiled without-fPIC. But I have to make a python extension and it is a dynamic library with-fPICthat links to static libraries. How can I compile a static library (libboostpython.a) with-fPICfromboost.python?
There are a couple options you could use: Compile boost from source and pass extra compiler options to bjam. E.g.bjam ... cxxflags='-fPIC'. That would compile every boost source file as position independent code.Use boost in the form of shared libraries. In this case you probably want to ship boost shared libraries a...
I have an extern code written in C in my C++ project in MS VS 2010. It comes with .h and .c files and I use include like this: ``` extern "C"{ #include "Extern\libname.h" } ``` It worked nice. Then I readGoogle C++ style guideand removed all entries of ``` using namespace std; ``` replaced them with just ``` std:...
add ``` #include <cstdio> ``` above you include.
I am trying to remove a column from a data set. My file looks as below. How can I accomplish this? Input- ``` 1,2,3,4 2,3,4,5 3,4,5,6 ``` Output- ``` 2,3 3,4 4,5 ```
There is no quick way of doing that - you will end up "tokenizing" each line of the file, and then writing only the parts that you want. If you know that each row contains a fixed number of integers (say, 4, as in your example), and you need to "cut out" several columns from it (say, columns 2 and 3), do this in a lo...
I tried doing this in C and it crashes: ``` int nValue=1; void* asd; asd[0]=&nValue; ``` With the following error: ``` *error C2036: 'void**' *: unknown size error C2100: illegal indirection* ``` Can I use a void pointer in C as an array? And if I can, what is the correct way to do so?
Can I use a void pointer in C as an array? Nope. You can convert to and fromvoid*, but you cannot derference it, and it makes sense when you think about it. It points to an unknown type, so the size is also unknown. Therefore, you cannot possibly perform pointer arithmetic on it (which is whatasd[0]does) because y...
I'm looking for thepthreadsstandard for some work I'm doing on parallelism. I have found that it is supposed to be IEEE 1003.1c "EEE Standard for Information Technology--Portable Operating System Interface (POSIX(R)) - System Application Program Interface (API) Amendment 2: Threads Extension (C Language)". However, w...
It's been superseded by a newer edition (2008). It's available as IEEE 1003.1-2008 or ISO/IEC 9945-2009 (for enough money) orThe Open Group Single Unix Specification, version 7(for free). All three have identical content.
I want to have a simple 2DCtype array asx[ 10][20] ;and want to delete it when needed to free memory but cocoa does not have delete method. What is the best way? ( Just as performance issue)
You don't free your memory because the memory was allocated on the stack by just declaring your array. Memory will then be freed when leaving the method. You should free your memory though if is was allocated on the heap using the C malloc function. Have a look to thisdoc. This explains everything about C memory mana...
In my simple program, when it executes thegetcharmethod execute beforeprintfmethod. Why this happen and how to solve this?? ``` #include <stdio.h> #include <stdlib.h> #define SUCCESS 0 void exit_Pro() { printf("Press any Key to exit: "); fflush(stdin); getchar(); } int main(int argc, char **argv) { ...
Flush "stdin"? printf operates on "stdout". Did you mean to flush that? Flushing "stdin" makes no sense.
It only prints the description when I print b again after the if statement, really weird behavior, when I remove the last line it doesn't printdescription is ...dos anyone know why this happens and how I can fix this? Thanks ``` char * b; if (list!= NULL){ b = strdup ( (char *)g_object_get_data(G_OBJECT(list->data), ...
It's seemsstdoutis line-buffered, i.e.printfhoards output until it encounters a newline or its buffer fills up. Add a newline to the firstprintf: ``` printf(" description is %s\n", b); ``` Toensurethe output buffer is flushed, you can say: ``` fflush(stdout); ```
Can anyone pl. explain how the following c program works: Specifically how function 'fun' is assigned to(*p)() = fun; I need to know how compiler compiles this code. ``` #include<stdio.h> int fun(); /* function prototype */ int main() { int (*p)() = fun; (*p)(); return 0; } int fun() { printf("Hello...
Each function exists in memory somewhere. The statement: ``` int (*p)() = fun; ``` is assigning the memory location of the function fun to p. Then the line: ``` (*p)(); ``` is calling the function that exists at the memory location that p is pointing to. The Interweb is full of info on "function pointers."
What is the advantage of using zero-length arrays in C? Eg: ``` struct email { time_t send_date; int flags; int length; char body[]; }list[0]; ```
An array of size0is not valid in C. ``` char bla[0]; // invalid C code ``` From the Standard: (C99, 6.7.5.2p1) "If the expression is a constant expression, it shall have a value greater than zero." Solistdeclaration is not valid in your program. An array with an incomplete type as the last member of a structure ...
I am trying to use pread and pwrite so that I can lseek to the beginning of the file and start reading or writing in one atomic operation. Both of these functions will do that for me however, the issue I am having is that the compiler is giving mewarning: implicit declaration of function ‘pread’even after I added#def...
You need to define_XOPEN_SOURCE 500beforeyour includes: ``` #define _XOPEN_SOURCE 500 #include<unistd.h> ``` Otherwise, theunistd.hheader won't see the macro definition.
is there a "built-in" way to know the exit code passed toexitinside an exit handler installed withatexit? For example, if a callexit(EXIT_FAILURE), my handler will perform different operations than in case ofexit(EXIT_SUCCESS). I could solve that with a global variable, but that would negate the comfort of callingex...
Withatexitno. But you could use theon_exitfunction : Function: int on_exit (void (*function)(int status, void *arg), void *arg)This function is a somewhat more powerful variant of atexit. It accepts two arguments, a function function and an arbitrary pointer arg. At normal program termination, the function is cal...
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. ``` #include<stdio.h> void main...
Always try the boundaries for odd behavior. This worked for me: ``` #include <float.h> int _tmain(int argc, _TCHAR* argv[]) { float i,j; i = FLT_MAX; j = i + 1; if(i == j) { printf("they're the same"); } return 0; } ```
``` #include <stdio.h> int main() { char string[] = "my name is geany"; int length = sizeof(string)/sizeof(char); printf("%i", length); int i; for ( i = 0; i<length; i++ ) { } return 0; } ``` if i want to print "my" "name" "is" and "geany" separate then what do I do. I was thinking to ...
start with a pointer to the begining of the stringiterate character by character, looking for your delimitereach time you find one, you have a string from the last position of the length in difference - do what you want with thatset the new start position to the delimiter + 1, and the go to step 2. Do all these while...
i have an array,int* array, with more than 10.000 int values, but i want to point to each 100 position, it means that I will haveint ** matrix, where:matrix[i][j], I wantifrom my matrix to point toarray[i * 100], how can y substitute the address ? here is what I've done: ``` u_int8_t **matrix = (u_int8_t **)malloc(wi...
Store the address ofarray[i]inmatrix[i / 100]. ``` #define HOW_MUCH_NUMBERS 10000 [...] { int array[HOW_MUCH_NUMBERS]; int i = 0; int **matrix; matrix = malloc(sizeof(*matrix) * (HOW_MUCH_NUMBERS / 100)); while (i < HOW_MUCH_NUMBERS) { matrix[i / 100] = &array[i]; i += 100; } [...] } ```
Can I do ``` write(&'\n', 1); ``` and is it equivalent to ``` char a = '\n'; write(&a, 1); ``` How would you solve this in a fashion way? I'm tring to write the new-line caracter with a function that only take char array as first argument, and its dimension in second argument (dimension has to be specified becaus...
As others already pointed out, you cannot take the address of a character literal. And even if you could, it would be the wrong type, because a character array usually must be zero-terminated. What you are looking for is: write("\n", 1);
I am using thecusplibrary with CUDA to use sparse matrix. Can't I use it in astructin C like: ``` #include <cusp/coo_matrix.h> #include <cusp/multiply.h> #include <cusp/print.h> #include <cusp/transpose.h> struct Cat{ int id; cusp::coo_matrix<int, double, cusp::host_memory> A(2,100,10); };...
That piece of codecoo_matrixlooks suspiciously like a C++ template. If so, provide yourCat structwith constructor and initialize A there: ``` struct Cat { int id; cusp::coo_matrix<int, double, cusp::host_memory> A; Cat(): id(0), A(2,100,10) {} } ```
I am developing an application with GTK+-2.0. I need to access /dev/mmcblk0 device but it needs super user priviliges. It is not user friendly to login as su in terminal and run the program. I want to create a prompt window and ask for super user password and run the program with super user priviliges. GParted is a p...
You could check thegksu pageon live gnome, or if you want to use thepolicy kit frameworkyou can google for sample programs (e.g.like this one).Another way, more straightforward, would require the creation of a group (which would allow users to access /dev/mmcblk0) and ask root to add specific allowed users to this gro...
``` char *vowels = "aeiouyæøå"; int len = strlen(vowels); int counter; for (counter = 0; counter < len; counter++) { char vowel = *vowels++; printf("%c\n", vowel); } ``` Or ``` char *vowels = "aeiouyæøå"; int len = strlen(vowels); int counter; for (counter = 0; counter < l...
``` char c; while ( c = *(vowels++) ) { } ``` No need forstrlen.
This question already has answers here:What is the easiest way to make a C++ program crash?(31 answers)Closed9 years ago. I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults. Is there a simple example program that always segfaults?
main() { *(int *)0xdeadbeef = 37; }should do it.
How is it possible to give a function (B) a function (A) as a parameter? So that I can use function A in the function B. Like the Variable B in the following example: ``` foo(int B) { ... } ```
By usingfunction pointers. Look at theqsort()standard library function, for instance. Example: ``` #include <stdlib.h> int op_add(int a, int b) { return a + b; } int operate(int a, int b, int (*op)(int, int)) { return op(a, b); } int main(void) { printf("12 + 4 is %d\n", operate(12, 4, op_add)); return E...
When doing objective-c, do I have to write out functions like: ``` - (int) someFunction: (int) a someParam: (int) b; ``` Or can I use regular C style: ``` void someFunction(int a, int b); ``` If I can do the C style, is there any benefit to doing it in the Objective-C style?
You can use regular C functions, if you like, since Objective-C is just a super set of C. You need to use Objective-C syntax if you want to use Objective-C features, like classes, messages, inheritance, etc... and of course to use the Cocoa/CocoaTouch SDK. You can mix Objective-C and C code in your files, and have a...
What is the advantage of using zero-length arrays in C? Eg: ``` struct email { time_t send_date; int flags; int length; char body[]; }list[0]; ```
An array of size0is not valid in C. ``` char bla[0]; // invalid C code ``` From the Standard: (C99, 6.7.5.2p1) "If the expression is a constant expression, it shall have a value greater than zero." Solistdeclaration is not valid in your program. An array with an incomplete type as the last member of a structure ...
I am trying to use pread and pwrite so that I can lseek to the beginning of the file and start reading or writing in one atomic operation. Both of these functions will do that for me however, the issue I am having is that the compiler is giving mewarning: implicit declaration of function ‘pread’even after I added#def...
You need to define_XOPEN_SOURCE 500beforeyour includes: ``` #define _XOPEN_SOURCE 500 #include<unistd.h> ``` Otherwise, theunistd.hheader won't see the macro definition.
is there a "built-in" way to know the exit code passed toexitinside an exit handler installed withatexit? For example, if a callexit(EXIT_FAILURE), my handler will perform different operations than in case ofexit(EXIT_SUCCESS). I could solve that with a global variable, but that would negate the comfort of callingex...
Withatexitno. But you could use theon_exitfunction : Function: int on_exit (void (*function)(int status, void *arg), void *arg)This function is a somewhat more powerful variant of atexit. It accepts two arguments, a function function and an arbitrary pointer arg. At normal program termination, the function is cal...
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. ``` #include<stdio.h> void main...
Always try the boundaries for odd behavior. This worked for me: ``` #include <float.h> int _tmain(int argc, _TCHAR* argv[]) { float i,j; i = FLT_MAX; j = i + 1; if(i == j) { printf("they're the same"); } return 0; } ```
``` #include <stdio.h> int main() { char string[] = "my name is geany"; int length = sizeof(string)/sizeof(char); printf("%i", length); int i; for ( i = 0; i<length; i++ ) { } return 0; } ``` if i want to print "my" "name" "is" and "geany" separate then what do I do. I was thinking to ...
start with a pointer to the begining of the stringiterate character by character, looking for your delimitereach time you find one, you have a string from the last position of the length in difference - do what you want with thatset the new start position to the delimiter + 1, and the go to step 2. Do all these while...
i have an array,int* array, with more than 10.000 int values, but i want to point to each 100 position, it means that I will haveint ** matrix, where:matrix[i][j], I wantifrom my matrix to point toarray[i * 100], how can y substitute the address ? here is what I've done: ``` u_int8_t **matrix = (u_int8_t **)malloc(wi...
Store the address ofarray[i]inmatrix[i / 100]. ``` #define HOW_MUCH_NUMBERS 10000 [...] { int array[HOW_MUCH_NUMBERS]; int i = 0; int **matrix; matrix = malloc(sizeof(*matrix) * (HOW_MUCH_NUMBERS / 100)); while (i < HOW_MUCH_NUMBERS) { matrix[i / 100] = &array[i]; i += 100; } [...] } ```
Can I do ``` write(&'\n', 1); ``` and is it equivalent to ``` char a = '\n'; write(&a, 1); ``` How would you solve this in a fashion way? I'm tring to write the new-line caracter with a function that only take char array as first argument, and its dimension in second argument (dimension has to be specified becaus...
As others already pointed out, you cannot take the address of a character literal. And even if you could, it would be the wrong type, because a character array usually must be zero-terminated. What you are looking for is: write("\n", 1);
I am using thecusplibrary with CUDA to use sparse matrix. Can't I use it in astructin C like: ``` #include <cusp/coo_matrix.h> #include <cusp/multiply.h> #include <cusp/print.h> #include <cusp/transpose.h> struct Cat{ int id; cusp::coo_matrix<int, double, cusp::host_memory> A(2,100,10); };...
That piece of codecoo_matrixlooks suspiciously like a C++ template. If so, provide yourCat structwith constructor and initialize A there: ``` struct Cat { int id; cusp::coo_matrix<int, double, cusp::host_memory> A; Cat(): id(0), A(2,100,10) {} } ```
I am developing an application with GTK+-2.0. I need to access /dev/mmcblk0 device but it needs super user priviliges. It is not user friendly to login as su in terminal and run the program. I want to create a prompt window and ask for super user password and run the program with super user priviliges. GParted is a p...
You could check thegksu pageon live gnome, or if you want to use thepolicy kit frameworkyou can google for sample programs (e.g.like this one).Another way, more straightforward, would require the creation of a group (which would allow users to access /dev/mmcblk0) and ask root to add specific allowed users to this gro...
``` char *vowels = "aeiouyæøå"; int len = strlen(vowels); int counter; for (counter = 0; counter < len; counter++) { char vowel = *vowels++; printf("%c\n", vowel); } ``` Or ``` char *vowels = "aeiouyæøå"; int len = strlen(vowels); int counter; for (counter = 0; counter < l...
``` char c; while ( c = *(vowels++) ) { } ``` No need forstrlen.
This question already has answers here:What is the easiest way to make a C++ program crash?(31 answers)Closed9 years ago. I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults. Is there a simple example program that always segfaults?
main() { *(int *)0xdeadbeef = 37; }should do it.
How is it possible to give a function (B) a function (A) as a parameter? So that I can use function A in the function B. Like the Variable B in the following example: ``` foo(int B) { ... } ```
By usingfunction pointers. Look at theqsort()standard library function, for instance. Example: ``` #include <stdlib.h> int op_add(int a, int b) { return a + b; } int operate(int a, int b, int (*op)(int, int)) { return op(a, b); } int main(void) { printf("12 + 4 is %d\n", operate(12, 4, op_add)); return E...
When doing objective-c, do I have to write out functions like: ``` - (int) someFunction: (int) a someParam: (int) b; ``` Or can I use regular C style: ``` void someFunction(int a, int b); ``` If I can do the C style, is there any benefit to doing it in the Objective-C style?
You can use regular C functions, if you like, since Objective-C is just a super set of C. You need to use Objective-C syntax if you want to use Objective-C features, like classes, messages, inheritance, etc... and of course to use the Cocoa/CocoaTouch SDK. You can mix Objective-C and C code in your files, and have a...
i have an array,int* array, with more than 10.000 int values, but i want to point to each 100 position, it means that I will haveint ** matrix, where:matrix[i][j], I wantifrom my matrix to point toarray[i * 100], how can y substitute the address ? here is what I've done: ``` u_int8_t **matrix = (u_int8_t **)malloc(wi...
Store the address ofarray[i]inmatrix[i / 100]. ``` #define HOW_MUCH_NUMBERS 10000 [...] { int array[HOW_MUCH_NUMBERS]; int i = 0; int **matrix; matrix = malloc(sizeof(*matrix) * (HOW_MUCH_NUMBERS / 100)); while (i < HOW_MUCH_NUMBERS) { matrix[i / 100] = &array[i]; i += 100; } [...] } ```
Can I do ``` write(&'\n', 1); ``` and is it equivalent to ``` char a = '\n'; write(&a, 1); ``` How would you solve this in a fashion way? I'm tring to write the new-line caracter with a function that only take char array as first argument, and its dimension in second argument (dimension has to be specified becaus...
As others already pointed out, you cannot take the address of a character literal. And even if you could, it would be the wrong type, because a character array usually must be zero-terminated. What you are looking for is: write("\n", 1);
I am using thecusplibrary with CUDA to use sparse matrix. Can't I use it in astructin C like: ``` #include <cusp/coo_matrix.h> #include <cusp/multiply.h> #include <cusp/print.h> #include <cusp/transpose.h> struct Cat{ int id; cusp::coo_matrix<int, double, cusp::host_memory> A(2,100,10); };...
That piece of codecoo_matrixlooks suspiciously like a C++ template. If so, provide yourCat structwith constructor and initialize A there: ``` struct Cat { int id; cusp::coo_matrix<int, double, cusp::host_memory> A; Cat(): id(0), A(2,100,10) {} } ```
I am developing an application with GTK+-2.0. I need to access /dev/mmcblk0 device but it needs super user priviliges. It is not user friendly to login as su in terminal and run the program. I want to create a prompt window and ask for super user password and run the program with super user priviliges. GParted is a p...
You could check thegksu pageon live gnome, or if you want to use thepolicy kit frameworkyou can google for sample programs (e.g.like this one).Another way, more straightforward, would require the creation of a group (which would allow users to access /dev/mmcblk0) and ask root to add specific allowed users to this gro...
``` char *vowels = "aeiouyæøå"; int len = strlen(vowels); int counter; for (counter = 0; counter < len; counter++) { char vowel = *vowels++; printf("%c\n", vowel); } ``` Or ``` char *vowels = "aeiouyæøå"; int len = strlen(vowels); int counter; for (counter = 0; counter < l...
``` char c; while ( c = *(vowels++) ) { } ``` No need forstrlen.
This question already has answers here:What is the easiest way to make a C++ program crash?(31 answers)Closed9 years ago. I'm trying to set up the way my server handles core dumps. In order to test it, I'd need a program that always segfaults. Is there a simple example program that always segfaults?
main() { *(int *)0xdeadbeef = 37; }should do it.
How is it possible to give a function (B) a function (A) as a parameter? So that I can use function A in the function B. Like the Variable B in the following example: ``` foo(int B) { ... } ```
By usingfunction pointers. Look at theqsort()standard library function, for instance. Example: ``` #include <stdlib.h> int op_add(int a, int b) { return a + b; } int operate(int a, int b, int (*op)(int, int)) { return op(a, b); } int main(void) { printf("12 + 4 is %d\n", operate(12, 4, op_add)); return E...
When doing objective-c, do I have to write out functions like: ``` - (int) someFunction: (int) a someParam: (int) b; ``` Or can I use regular C style: ``` void someFunction(int a, int b); ``` If I can do the C style, is there any benefit to doing it in the Objective-C style?
You can use regular C functions, if you like, since Objective-C is just a super set of C. You need to use Objective-C syntax if you want to use Objective-C features, like classes, messages, inheritance, etc... and of course to use the Cocoa/CocoaTouch SDK. You can mix Objective-C and C code in your files, and have a...
My data.txt content is: ``` 1 2 3 4 5 6 1 2 3 4 5 6 4 5 6 7 8 2 ``` I read the file, and store the value to a two dimension int array ``` int record[line_number][6]; int record2[line_number][8]; int test; for(i = 0; i <line_number; i++) { for(j = 0; j <6; j++) { fscanf(fptr, "%d", &record[i...
You don't check the return value offscanf(), so you don't know that it really succeeds for all the conversions. If it fails, the value inrecord[][]will be uninitialized, and printing it out will print whatever happens to be in memory.
I have a .c and a .h file modified to be used within a cpp application, in fact they have the ``` #ifdef __cplusplus extern "C"{ #endif ``` prepocessor lines. I was wondering if and how I can use the functions defined there within a c# program. Maybe I have to create a dll for that piece of code?
You guys don't seem to get it - he doesn't have a dll, he has c++ source files: You have two options Translate the c++ code to C# and incorporate it directly into your applicationUse a c++ compiler to create a dll from the source files and use PInvoke to access it As far as if you need to modify the c++ code to cre...
I have a c++ active x dll which is built from visual studio 2005 and i need to call it from a "c" code which i has to be compiled in mingw32 compiler. Is it possible to call a c++ active x dll from c or i have to convert the dll from activex to win32. Please give me your suggestions.
ActiveX is COM, and COM is essentially a C API (as it is a part of Win API which itself is a C API) so it is possible., but it requires a good understanding of COM. A good starting point can be found here:http://www.codeproject.com/Articles/13601/COM-in-plain-C
``` #include<stdio.h> int main (void) { int i=257; int *ptr=&i; printf("%d%d",*((char*)ptr),*((char*)ptr+1)); return 0; } ``` Will the output of the above code implementation defined and the output will vary between little endian and big endian machine?
Yes. The classic way to detect endianness at run time is the following way: ``` uint32_t var = 1; uint8_t *ptr = (uint8_t*)&var; if(*ptr) puts("Little Endian"); else puts("Big Endian"); ``` Even though 257 => 0x0101, an int is most likely 32 bits in which case on a BE machine it will print 00 and on LE, 11.
``` struct ifreq { char ifr_name[IFNAMSIZ]; union { caddr_t ifr_d; } ifr; }; ``` Here they have used union, I didn't get the point why have they used when there is only one element used there? I have a idea of using union only if there are 2-3 elements that need to be used. T...
Loads of possibilities. But, in this case, it looks like it's because the definition was cut out of the corresponding Linux header, and they just took the parts they needed.struct ifreqlooks like this, normally: ``` struct ifreq { char ifr_name[IFNAMSIZ]; /* Interface name */ union { ... }; }; ```...
I am trying to compile a Python extension written in C on a CentOS machine. I am getting ``` error: Python.h: No such file or directory ``` It works fine on ubuntu, where I have python-dev installed using apt-get. I tried installing python-devel using ``` yum install python-devel ``` but it is already installed. ...
If you using python3 You could install python34-devel for that It's available onEPEL Repositoryand haspython34-devel packageavailable You simply just run this command to get it installed ``` yum install python34-devel ``` Hope it's help *noteAt this timepython34-develis the most updated version of python 3.4
This question already has answers here:Closed11 years ago. Possible Duplicate:Print an int in binary representation using C How would I print the byte representations of a short int, and double in C. As in lets say I have a function display_shortInt, how would I make it print the byte representation of a short int?...
What about this? ``` void print_bytes(void *p, size_t len) { size_t i; printf("("); for (i = 0; i < len; ++i) printf("%02X", ((unsigned char*)p)[i]); printf(")"); } void print_short(short x) { print_bytes(&x, sizeof(x)); } void print_double(double x) { print_bytes(&x, sizeof(x)); } /...
How can I list all names in the D-Bus sessionBus with C? I'm looking for theC GIOequivalent for thedbus.list_names python method I want to list all names in «org.mpris.MediaPlayer2» which as example could be «org.mpris.MediaPlayer2.clementine, org.mpris.MediaPlayer2.someotherplayer, ...» There is an application cal...
Information about the interface names, methods and arguments should be in theintrospection section. You can request information about an interface (e.g.org.mpris.MediaPlayer2) using theg_dbus_node_info_lookup_interface ()method, to which you can give aGDBusNodeInfoargument, which should contain the path of the dbus o...
I used to have an older version of MinGW installed on my windows machine. When I compiled my program under "Release" mode using the MinGW tool collection for build in NetBeans IDE, my executable was roughly 700KB. Then, I recently installed the latest MinGW (mingw-get-inst-20120426.exe). After the installation, I r...
WOW. It works now. I think removing C:\cygwin\bin from the PATH fixed the problem. Ahhh. Is that right? That's strange though because I specifically told NetBeans to use the MinGW toolset. Thanks for your help everyone.
A friend told me there is a way to check withprintfwithoutmodifying the originalvoidfunction. But I can't see how you can do it. ``` #include<stdio.h> void test() { int a = 1; int b = a; } main() { printf("%d",test()); } ``` I kept getting error: invalid use of void expression Is there a way to do i...
I see from your edit that you want to do this without modifying the function. You can employ the comma operator to make the function call in aprintf: ``` #include <stdio.h> void test() { int a = 1; int b = a; } main() { printf("%d\n", (test(), 0)); // or even this, to be more explicit: printf("...
I'm a Linux user who started learning C and I'm trying to compile this source that I typed: ``` #include <stdio.h> main() { float c,d; c = 10215.3; d = c / 3; printf("%3.2f\n",d); return 0; } ``` It compiled with this using a makefile that I wrote: ``` cc -Wall -g printf....
``` main() ``` should be ``` int main() ``` In C89, the default return type is assumed to beint, that's why it works.
This program crashes at the pointi=(strlen(data));with the message No source available for "strlen() " But Why? ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main (void) { char data[]="Hallo"; char buffer[100]; if (strlen(data)!=0) { size_t i=0; i=(strlen(data...
The error message you cite does not sound like a crash. More like a debugger trying to step into a system library function.
I am writing a C program that forks once it accepts a client connection. Once this happens, I want to spawn two threads, but I cannot seem to get this working. ``` pthread_t t1, t2; void *r_loop(); void *w_loop(); . . . sockfd = accept(r_sockfd, (struct sockaddr *) &address, &len); if (sockfd < 0...
The problem could be this: pthread_create() on success alwasy returns zero. You are passing to pthread_join() an incorrect value (that is zero instead of t1 and t2) making them to return immediately. Then the following exit() also kills the new starting threads
I have a .lib file, source code of which I don't have. I need an exported function from it, but I'm writing in C, and the function is C++ name-mangled. I can't writeextern "C", because I don't have the source code. How do I link mangled function without source code and switching to C++?
Make C++ wrapper: wrapper.cpp: ``` #include "3rdparty.hpp" extern "C" int foo(int a, int b) { return third_party::secret_function(a, b); } ``` consumer.c: ``` extern int foo(int, int); // ... ``` Build:(e.g. with GCC) ``` g++ -o wrapper.o wrapper.cpp gcc -o consumer.o consumer.c g++ -o program consumer.o w...
This question already has answers here:Closed11 years ago. Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) I have encountered with a strange problem regards increment operator. I get different output of same expression in PHP and C. In C language ``` main() { ...
In C the result is undefined because either of the two operands could be evaluated first, thus reading it a second time is erroneous. And, well, in PHP I wouldn't be surprised if the result was 42 pending some changes to php.ini.
I've modified the small part of a simulator but I've faced to strange segmentation fault. GDB shows the error is appear from a class where I've not modified. I guess my code has memory access violation upon accessing its own array which accordingly destroys the content of other array (allocated in the program memory s...
In short,Valgrindwill do this. Just run it asvalgrind /path/to/executable
``` #include<stdio.h> int main (void) { int i=257; int *ptr=&i; printf("%d%d",*((char*)ptr),*((char*)ptr+1)); return 0; } ``` Will the output of the above code implementation defined and the output will vary between little endian and big endian machine?
Yes. The classic way to detect endianness at run time is the following way: ``` uint32_t var = 1; uint8_t *ptr = (uint8_t*)&var; if(*ptr) puts("Little Endian"); else puts("Big Endian"); ``` Even though 257 => 0x0101, an int is most likely 32 bits in which case on a BE machine it will print 00 and on LE, 11.
``` struct ifreq { char ifr_name[IFNAMSIZ]; union { caddr_t ifr_d; } ifr; }; ``` Here they have used union, I didn't get the point why have they used when there is only one element used there? I have a idea of using union only if there are 2-3 elements that need to be used. T...
Loads of possibilities. But, in this case, it looks like it's because the definition was cut out of the corresponding Linux header, and they just took the parts they needed.struct ifreqlooks like this, normally: ``` struct ifreq { char ifr_name[IFNAMSIZ]; /* Interface name */ union { ... }; }; ```...
I am trying to compile a Python extension written in C on a CentOS machine. I am getting ``` error: Python.h: No such file or directory ``` It works fine on ubuntu, where I have python-dev installed using apt-get. I tried installing python-devel using ``` yum install python-devel ``` but it is already installed. ...
If you using python3 You could install python34-devel for that It's available onEPEL Repositoryand haspython34-devel packageavailable You simply just run this command to get it installed ``` yum install python34-devel ``` Hope it's help *noteAt this timepython34-develis the most updated version of python 3.4
This question already has answers here:Closed11 years ago. Possible Duplicate:Print an int in binary representation using C How would I print the byte representations of a short int, and double in C. As in lets say I have a function display_shortInt, how would I make it print the byte representation of a short int?...
What about this? ``` void print_bytes(void *p, size_t len) { size_t i; printf("("); for (i = 0; i < len; ++i) printf("%02X", ((unsigned char*)p)[i]); printf(")"); } void print_short(short x) { print_bytes(&x, sizeof(x)); } void print_double(double x) { print_bytes(&x, sizeof(x)); } /...
How can I list all names in the D-Bus sessionBus with C? I'm looking for theC GIOequivalent for thedbus.list_names python method I want to list all names in «org.mpris.MediaPlayer2» which as example could be «org.mpris.MediaPlayer2.clementine, org.mpris.MediaPlayer2.someotherplayer, ...» There is an application cal...
Information about the interface names, methods and arguments should be in theintrospection section. You can request information about an interface (e.g.org.mpris.MediaPlayer2) using theg_dbus_node_info_lookup_interface ()method, to which you can give aGDBusNodeInfoargument, which should contain the path of the dbus o...
I used to have an older version of MinGW installed on my windows machine. When I compiled my program under "Release" mode using the MinGW tool collection for build in NetBeans IDE, my executable was roughly 700KB. Then, I recently installed the latest MinGW (mingw-get-inst-20120426.exe). After the installation, I r...
WOW. It works now. I think removing C:\cygwin\bin from the PATH fixed the problem. Ahhh. Is that right? That's strange though because I specifically told NetBeans to use the MinGW toolset. Thanks for your help everyone.
A friend told me there is a way to check withprintfwithoutmodifying the originalvoidfunction. But I can't see how you can do it. ``` #include<stdio.h> void test() { int a = 1; int b = a; } main() { printf("%d",test()); } ``` I kept getting error: invalid use of void expression Is there a way to do i...
I see from your edit that you want to do this without modifying the function. You can employ the comma operator to make the function call in aprintf: ``` #include <stdio.h> void test() { int a = 1; int b = a; } main() { printf("%d\n", (test(), 0)); // or even this, to be more explicit: printf("...
I'm a Linux user who started learning C and I'm trying to compile this source that I typed: ``` #include <stdio.h> main() { float c,d; c = 10215.3; d = c / 3; printf("%3.2f\n",d); return 0; } ``` It compiled with this using a makefile that I wrote: ``` cc -Wall -g printf....
``` main() ``` should be ``` int main() ``` In C89, the default return type is assumed to beint, that's why it works.
This program crashes at the pointi=(strlen(data));with the message No source available for "strlen() " But Why? ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main (void) { char data[]="Hallo"; char buffer[100]; if (strlen(data)!=0) { size_t i=0; i=(strlen(data...
The error message you cite does not sound like a crash. More like a debugger trying to step into a system library function.