question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
I'm designing an editor in GTK+ and wanted to add a feature of the gedit text editor to represent the line number at the left side of the text. I've added animage of gedit showing the line number at the left of each line. I require guidance of which widget I should use and how to use it.
Thanks in advance :).. !
| To get line numbering, useGtkSourceViewinstead ofGtkTextView.
|
I am trying to reallocate memory to my table using the below expression.But I always keep getting the below error.Please kindly advise me.
```
typedef char *OFAttribs[6];
OFAttribs *tmp = realloc(pTable, sizeof(*tmp) * (nTableLen+1));
Error: invalid conversion from âvoid*â to âchar* (*)[6]â
```
| Try this:
```
OFAttribs *tmp = (OFAttribs*) realloc(pTable, sizeof(*tmp) * (nTableLen+1));
```
|
Im trying to figure out what the function declarations mean:
```
int *f();
```
and
```
int (*g)();
```
| ```
int *f();
```
The above line is the declaration of a functionfthat has an unspecified number of parameters and that returns anint *.
```
int (*g)();
```
The above line is the declaration of a pointergto a function that has an unspecified number of parameters and that returns anint.
|
I'm developing a note-taking utility and want to add a feature for voice-recording and playback in full duplex asynchronous mode.What cross-platform c/c++ libraries/API's can I evaluate for my purpose? Google isn't much help in this case and the existing QA's on SO doesn't quite cover this.
| PortAudiocan accomplish what you want. It has lots of backends for different technologies like ALSA, ASIO, DirectSound etc.
|
I am trying to reallocate memory to my table using the below expression.But I always keep getting the below error.Please kindly advise me.
```
typedef char *OFAttribs[6];
OFAttribs *tmp = realloc(pTable, sizeof(*tmp) * (nTableLen+1));
Error: invalid conversion from âvoid*â to âchar* (*)[6]â
```
| Try this:
```
OFAttribs *tmp = (OFAttribs*) realloc(pTable, sizeof(*tmp) * (nTableLen+1));
```
|
Im trying to figure out what the function declarations mean:
```
int *f();
```
and
```
int (*g)();
```
| ```
int *f();
```
The above line is the declaration of a functionfthat has an unspecified number of parameters and that returns anint *.
```
int (*g)();
```
The above line is the declaration of a pointergto a function that has an unspecified number of parameters and that returns anint.
|
How to make sure, that my code is compatible with every gcc compiler set to the most strict level? Is there any tester tool or do I need to test it manually somehow? Thanks
| Every gcc compiler is easy, just use an old one and it will compile for sure with the newer ones.
If you want it to compile with any compiler it's a bit more hard. As suggested you might use the -ansi switch to disable gcc extensions.
|
How can I open a.txtfile usingexecl()function? Is there any other function in c to open a file ingeditin Ubuntu.
Regards
| Is there any other function in c to open a file in gedit
Th easiest would be
```
system("gedit file.txt");
```
As a side-note you might want to look intoxdg-open.
|
How to make sure, that my code is compatible with every gcc compiler set to the most strict level? Is there any tester tool or do I need to test it manually somehow? Thanks
| Every gcc compiler is easy, just use an old one and it will compile for sure with the newer ones.
If you want it to compile with any compiler it's a bit more hard. As suggested you might use the -ansi switch to disable gcc extensions.
|
How can I open a.txtfile usingexecl()function? Is there any other function in c to open a file ingeditin Ubuntu.
Regards
| Is there any other function in c to open a file in gedit
Th easiest would be
```
system("gedit file.txt");
```
As a side-note you might want to look intoxdg-open.
|
If I chdir within a thread, will that affect the cwd of the parent program?
| Yes.
If you need relative paths in a multithreaded application, it's safest to use theat()versions of functions. For example,openat()is likeopen():
```
int openat(int dirfd, const char *pathname, int flags);
```
The first parameter is the fd to a directory. The path is relative to that directory.
|
Say I want to create a folder myFolder, and I want it to be hidden. I'm having trouble finding the answer to this for Unix.
| Seeman 2 mkdirfor creating a folder in C. To make it hidden you must prefix the name with a dot. It's just a one-liner:
```
mkdir(".myFolder", 0755);
```
|
Say I want to create a folder myFolder, and I want it to be hidden. I'm having trouble finding the answer to this for Unix.
| Seeman 2 mkdirfor creating a folder in C. To make it hidden you must prefix the name with a dot. It's just a one-liner:
```
mkdir(".myFolder", 0755);
```
|
I just have a simple question, I cannot find what the key code is for space bar in curses.h.
ex. I know the code for down is KEY_DOWN.
can anyone help?
| There is no macro for the space key. Just use ' ' to represent a space. You can find a complete list of curses key macroshere.
Ex.
```
char mychar = ' ';
if (mychar == ' ') {//Do this...}
```
|
What should I do if I want to use identifierNULLingdb's call statement?
Is it because I didn't include stdio.h in gdb?
I have tried :call #include <stdio.h>but this doesn't seem to work.
| Just use0or(void*)0. Nothing fancy.
|
I have long value of 12 digits as output from an arithmetic operation. So i want only the middle 4 value. for example i got 823954957346 and i only want 5495 to store in a variable. can i do this in C or C++ ?
| You can use something like:
```
main() {
unsigned long i = 823954957346;
printf ("%lu\n", i);
printf ("%lu\n", i / 10000 % 10000);
}
```
Output:
```
823954957346
5495
```
|
hi i have this function
```
int printofarray(int *j,double *n)
{
int x,k;
k=*j;
if(n==NULL) {
printf("array was not created\n");
return 1;}
for(x=0;x<k;x++){
printf("%.2lf\n",*(n+x));}
return 0;
}
```
when i use it the output is like this
```
34.77
6114.05
410.70
```
but i want to write them this way
```
34.77
6114.05
410.70
```
idea how?
| Offhand, try %f instead of %lf for f1. Edit: %lf is for double.
|
What I was always doing is:
```
int arr[] = {2, 3, 4};
```
and it always worked.
I've heard of a better way to initialize new array, using the pointer:
```
int *arr = {2, 3, 4};
```
However, it doesn't work in any IDE, it throws some errors likeint differs in levels of indirection from int, ortoo many initializers. How should I do this?
| ```
int arr[] = {2, 3, 4};
```
is just fine, and completely correct. No need to change.
|
How do I programmatically get the core a given thread is running on? Something like Unix'sgetcpuid. This is for Linux, and C.
| Doessched_getcpu()not give you a different value for the cores?
|
I can't reproduce this with a simple program, but somewhere in my program I have something like:
```
float e = f(...);
if (e > 0.0f) {
...
```
printf("%f", e)shows thateis0.000000, yete > 0.0fis true... So ise > 0ande > 0.0. What am I missing?
| The floating point value is larger than zero, but less than 1e-7. It's printing issue. Use scientific notation printf("%e", value); or "%g" for shortest notation.
|
Can I use pipe between two process without using fork and share file descriptors with for example socket ? I don't need another solution, I need pipe between two process that not forked.
| You could use a named pipe (FIFO):
if you domkfifo <common path>, you an use this path in both processes, one for reading and one for writing. Then you have the same behaviour as with a normal pipe.
|
I am working with Ubuntu 12.04. I want to use the AUX library for OpenGL. Can anybody tell me what steps are involved in getting the AUX library for my system?
| I want to use the AUX library for OpenGL.
No, you don't! GlAux is unmaintained and a most annoying PITA.
You want to use GLFW, SDL, SMFL, or maybe FreeGLUT.
|
I'm going to write a code which will extensively execute other programs. I don't want it to have root privileges if someone set a set-user-id bit(and root is an owner). So I'm going to drop privileges at startup.
My question is:
How can I understand from within the program whether it run inset-user-idmode?
| You can compare result ofgetuid()andgeteuid()library calls.
Ifgeteuid()returns 0 (root), butgetuid()returns not 0, you can say that suid is active.
|
I usually get a warning from the compiler if I tell it to return anything else.
| This is the exit code provided to whoever called your program. Non-zero value usually signifies error.
|
I usually get a warning from the compiler if I tell it to return anything else.
| This is the exit code provided to whoever called your program. Non-zero value usually signifies error.
|
I want to write a C++ wrapper for the Linux Socket API. In the socket() ctor the adress family (AF) is requested. I dont want to require the AF in the connect() signature again, becuase it has been already given in the constructor of socket. So how do I get the AF from an existing socket?
| Damn. Searched about half an hour. Now after posting this question I found immiediately the answer.
getsockopt([...])with option SO_DOMAIN (seesocket options)
|
I need to make a rule in my lex file that will identify the start of a newline and a sequence of spaces I did this^( )*but the compiler says it is wrong what is the right way to define it?
| Try something like this:
```
^[\n\t ]+
```
|
So all I need is simple: if object color is (255, 10, 10) then each visible point of it shall be rendered as (255, 10, 10). No lights, no shadows, no shades, no reflections/refractions and no transparency. I only want to provide vertex meshes and colors for them and see them rendered. Can such thing be implemented with OpenGL (on Renderer setup level - not via post/pre shading)?
| You need to disable the lighting :
```
glDisable(GL_LIGHTING);
```
|
Could you post some examples how to read list of meanings from/procfiles?
```
list_head* get_from_proc_file()
{
struct file* file = fopen("example","r");
seq_open(file, &seq_ops);
struct seq_file *p = file->private_data;
READ LIST OF DATA?????
}
```
| You can't usefopenas this is a libc function. The example bellow shows how to read a file from the kernel.
http://www.wasm.ru/forum/viewtopic.php?pid=467952#p467952
|
Is there any way to extrude gluPartialDisk in OpenGL - have been looking around
but cant seem to find one. If there isn't any way is there something similar I can
look at.
| There is no function in OpenGL to do this (note: gluPartialDisk is not an OpenGL function. It's a GLU function, which is not part of OpenGL itself). So if you want to do extrusion, you'll have to compute the vertices yourself.
|
I know that JPG, BMP, GIF and others formats compress image. But can I get snapshot of display and save it without compressing(in binary file) in programming way (using c/c++ for example or other stuff)?
| BMP files aren't compressed by default. See here:https://en.wikipedia.org/wiki/BMP_file_format
|
I declared a variable in this way:
```
int i = 0;
```
I get the warning:
ISO C90 forbids mixed declarations and code
How can I fix it?
| I think you should move the variable declaration to top of block. I.e.
```
{
foo();
int i = 0;
bar();
}
```
to
```
{
int i = 0;
foo();
bar();
}
```
|
I'm expecting h here.But it is showing g. Why?
```
char *c="geek";
printf("%c",++*c);
```
| You are attempting to modify a string literal, which isundefined behaviour. This means that nothing definite can be said about what your program will print out, or indeedwhetherit will print anything out.
Try:
```
char c[]="geek";
printf("%c",++*c);
```
For further discussion, see theFAQ.
|
Can if defined (XX) be placed inside a struct/union in aheader file?
```
struct
{
int i;
#if defined(xx)
int j;
#endif
}t;
```
I am dealing with a large file base of .c and .h files and I need to know the possible cons of this type of usage.
| While completely valid, a definite con to using this is any time you need to uset.jyou would also have to surround it with your#if defined(xx)otherwise you will invoke compiler errors
|
I have a struct like this:
```
typedef struct
{
int a;
int b;
int c;
int d;
} Hello;
```
then I declare it in this way:
```
Hello hello[6] = {};
```
Then I got this warning: ISO C forbids empty initializer braces, anyhow I think I need to initialize it, how to do it in the right way?
| That's not valid C. The universal zero initializer in C is{0}, not{}.
|
I know that JPG, BMP, GIF and others formats compress image. But can I get snapshot of display and save it without compressing(in binary file) in programming way (using c/c++ for example or other stuff)?
| BMP files aren't compressed by default. See here:https://en.wikipedia.org/wiki/BMP_file_format
|
I declared a variable in this way:
```
int i = 0;
```
I get the warning:
ISO C90 forbids mixed declarations and code
How can I fix it?
| I think you should move the variable declaration to top of block. I.e.
```
{
foo();
int i = 0;
bar();
}
```
to
```
{
int i = 0;
foo();
bar();
}
```
|
I'm expecting h here.But it is showing g. Why?
```
char *c="geek";
printf("%c",++*c);
```
| You are attempting to modify a string literal, which isundefined behaviour. This means that nothing definite can be said about what your program will print out, or indeedwhetherit will print anything out.
Try:
```
char c[]="geek";
printf("%c",++*c);
```
For further discussion, see theFAQ.
|
My registry.arm.bin is 600 KB large, and every time my application starts, it takes ~ 0.25 seconds to read and parse it.
The problem is that i don't need all the plugins that are located there.
I only want almost all of the plugins for AUDIO, and none for VIDEO.
How can i trim down my registry, so i reduce it size and loading time ?
| Just remove the plugins you don't need from your system. They are in /usr/lib/gstreamer-0.10 (or -1.0).
|
How are called these "widgets" in Gtk+: the widget with blue border and the widgets inside on it? is there equivalent in Gtk+?
Note: I'm calling "widget" by following Gtk terminology, because I don't know what its real nomenclature in the KDE environment.
| That is called aTreeView, inside it you will findTreeViewColumnandCellRenderer.
The documentation ishere.
|
Does anyone know where can I find a simple client/server WinAPI message queue example?
I'd like to create a program that sends data from a client to a server using message queues and I can't find anything useful on the web.
Thank you.
| TheWM_COPYDATAmessage can be used, but only synchronously. Without usingMSMQ, you'd have to implement your own message queue using named shared memory & named semaphores for asynchronous queues.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:C and C++ : Partial initialization of automatic structure
I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following:
```
HANDLE hHandles[32] = {0};
```
does it zero out the first element or all 32?
| It initializes all the 32 elements to zero.
|
Let's say I have astructwith a fieldxthat is also astruct(not a pointer to astruct).
If I sayobject.x = 0, what is actually happening under the hood?
| You'll get a compile error.
```
error: incompatible types in assignment
```
You can't assign anintto a struct variable.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:C and C++ : Partial initialization of automatic structure
I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following:
```
HANDLE hHandles[32] = {0};
```
does it zero out the first element or all 32?
| It initializes all the 32 elements to zero.
|
Let's say I have astructwith a fieldxthat is also astruct(not a pointer to astruct).
If I sayobject.x = 0, what is actually happening under the hood?
| You'll get a compile error.
```
error: incompatible types in assignment
```
You can't assign anintto a struct variable.
|
Real short and simple:
saycol = 10,size = 8. Then the following is executed:
```
col -= size--;
```
So does size get subtracted to 7 before doing the subtraction on col (so col = 3)? Or col = 2?
Thanks
| size--yields the previous value ofsize, so this is equivalent to:
```
col -= size;
-- size;
```
|
I'm not fairly familiar in C++ stream API and I want to convert a C code using stream in C++,
```
char sHex[20] = {0};
int numid = 2;
snprintf( sHex, sizeof(sHex) - 1, "%X", numId );
```
| ```
stringstream ss;
ss << uppercase << hex << numId;
string res = ss.str();
```
|
Problem is - I have to implement my own exit(status) with setjmp and longjmp. Maybe someone could give some pointers?
| The only solution I think of right now, is to callsetjmpearly inmain, and then create aMyExitfunction which does alongjmpto thesetjmpinmainand does areturnwith some value (provided from thelongjmpcall).
|
I need to print 2 vector in openGL but I cannot sent a pointer with the functionglutDisplayFunc.
glutDisplayFunc(graphfunct)I have this once the window is created but I need send the 2 pointers with the address of vector to set the coordinates.
| You cannot pass parameters to the function you register withglutDisplayFunc. You must use a globally-accessible variable instead.
|
I need to print 2 vector in openGL but I cannot sent a pointer with the functionglutDisplayFunc.
glutDisplayFunc(graphfunct)I have this once the window is created but I need send the 2 pointers with the address of vector to set the coordinates.
| You cannot pass parameters to the function you register withglutDisplayFunc. You must use a globally-accessible variable instead.
|
How do I find a substring from the string path "/user/desktop/abc/post/" using C/C++? I want to check if folder "abc" is present or not in that path.
Path is character pointerchar *ptr = "/user/desktop/abc/post/";
| Usestd::stringandfind.
```
std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;
```
|
I'm opening several files , and want to add to my struct the creation time of the file and the last write time. Is there a way I can do it?
| You can usefstatto read the last write time (seestat.st_mtime).
I'm not aware of a portable way to read creation time. On Windows you could useGetFileTime
|
```
void func(char a, int num)
{
printf("%c",a);
}
int main()
{
func("a", 6); //not func('a',6);
printf("\n");
func("b", 2); //not func('b',6);
}
```
I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?
| It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.
|
```
void func(char a, int num)
{
printf("%c",a);
}
int main()
{
func("a", 6); //not func('a',6);
printf("\n");
func("b", 2); //not func('b',6);
}
```
I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?
| It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.
|
```
void func(char a, int num)
{
printf("%c",a);
}
int main()
{
func("a", 6); //not func('a',6);
printf("\n");
func("b", 2); //not func('b',6);
}
```
I understand I am passing a char array of a and b with a null character\0.
Could someone how it ends up printing the characters$and&?
| It could end up printing anything pretty much, probably part of the adresses of"a"and"b"match the ascii code of$and&.
|
Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function?
The code below is not valid in ANSI C (C89, C90):
```
int main()
{
printf("Hello world!");
int a = 5; /* Error: all variables should be declared at the beginning of the function. */
return 0;
}
```
Is it valid source code in C11?
| Yes. This was already valid in C99 (see the second bullethere).
|
Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function?
The code below is not valid in ANSI C (C89, C90):
```
int main()
{
printf("Hello world!");
int a = 5; /* Error: all variables should be declared at the beginning of the function. */
return 0;
}
```
Is it valid source code in C11?
| Yes. This was already valid in C99 (see the second bullethere).
|
I want to declare character array and later want to fill it. But getting error:
```
char line[BUFSIZE+1];
strcpy(line,"Memory is Full", sizeof(line));
```
Error is:
```
wrong number of arguments in call to strcpy.
```
Is there any alternative to achive this?
| If you have it, usestrlcpy(). It does what you might expectstrncpy()to do.
Failing that, I would recommend usingsnprintf(), if you have it.
|
I want to declare character array and later want to fill it. But getting error:
```
char line[BUFSIZE+1];
strcpy(line,"Memory is Full", sizeof(line));
```
Error is:
```
wrong number of arguments in call to strcpy.
```
Is there any alternative to achive this?
| If you have it, usestrlcpy(). It does what you might expectstrncpy()to do.
Failing that, I would recommend usingsnprintf(), if you have it.
|
Is there any way (or a useful function) to know whether interrupts are disabled or not?
| You can useirqs_disabled()function:
```
#include <linux/irqflags.h>
int i = irqs_disabled();
```
|
Is there any way (or a useful function) to know whether interrupts are disabled or not?
| You can useirqs_disabled()function:
```
#include <linux/irqflags.h>
int i = irqs_disabled();
```
|
I know that in winapi existReadFile()function for reading data from file, but I don't know how can I set the position of reading from file. Can I do this using WinAPI?
| Yes, you can do that withSetFilePointerEx. However, unless you have a good reason for using the raw WinAPI, it's generally a better idea to use a cross-platform I/O library, such as C's stdio library or C++'s iostream library. That way, your code is portable to any platform.
|
Is there any way to identify if a buffer was allocated by 'malloc'? like a function with the following signature:
```
bool is_malloced(void *buf);
```
Does such a mechanism exist in posix?
| Nope. Neither C11 nor POSIX provide any such mechanism.
|
I have the following code:
```
volatile unsigned int * address;
char * array="0x10000008";
```
Please tell me, what is a correct way of writing the "array" value to "address" variable?
| You could usesscanf:
```
#include <stdio.h>
sscanf(array, "%p", &address);
```
orstrtoull:
```
#include <stdlib.h>
address = (unsigned int *)strtoull(array, NULL, 0);
```
|
I have the following code:
```
volatile unsigned int * address;
char * array="0x10000008";
```
Please tell me, what is a correct way of writing the "array" value to "address" variable?
| You could usesscanf:
```
#include <stdio.h>
sscanf(array, "%p", &address);
```
orstrtoull:
```
#include <stdlib.h>
address = (unsigned int *)strtoull(array, NULL, 0);
```
|
I want to know howls -Rimplemented in C language.
Is it use the recursion algorithm?
| "ls" (at least the implementations that I know of) usefts_open,fts_read... to traverse a file hierarchy. These are "non-recursive" methods which maintain a list of the visited directories internally.
Use "man fts_read" orhttp://linux.die.net/man/3/fts_readto get more information about these functions.
|
I want to know howls -Rimplemented in C language.
Is it use the recursion algorithm?
| "ls" (at least the implementations that I know of) usefts_open,fts_read... to traverse a file hierarchy. These are "non-recursive" methods which maintain a list of the visited directories internally.
Use "man fts_read" orhttp://linux.die.net/man/3/fts_readto get more information about these functions.
|
How can I get a version of language C/C++(downloaded??) where the functions sound, nosound, delay are present in the library DOS.H?
For example it doesn't exist in the version c/c++ on code::blocks. What have I to do in order to use/find the functions sound/nosound/delay?
thank you for your help !
| download (sigh) a copy of TurboC/TurboC++.
|
Is it possible to verify the type and number of arguments supplied to a variable length argument?(...)?
| At runtime? The type, no. The number, only if the caller places a NULL (or something recognisable) at the end, which is unreliable.
At compile time, you can get the compiler to check the arguments in the same way that it will check the args to printf. Google for gcc __attribute__ format
|
I write simple console functions and use freopen to redirect printf statements to a file. Can the output to the file be "turned off" and the printf outputs redirected back to the console window later in the code?
| fprintflets you to print to a specific file stream. For example,
```
fprintf(stdout, "message");
```
printmessagein the standard output (the console), so... as you see,printfis just an specialization offprintf.
I hope this help.
|
I see two option to assign a pointer
1.
```
int p=5;
int *r=&p
```
2.
```
int p
int *r;
r=&p;
```
Why do they use in 1 with asterisk
and in two without?
| You should read this:
```
int *r [...]
```
as:
```
(int *) r [...]
```
The type ofrisint *. If you look at it that way, you'll see that both versions are identical.
|
I need my program go to some specific directory then run
system( ... );there and get me back where I was before. How can I do it?
| Just do thecdin yoursystemcall:
```
system("cd wherever; command");
```
The whole string gets passed tosh(1), so you can do any normal shell things in there. Since it's in a subshell, the working directory of your program won't be changed.
|
Is it guaranteed that this piece of code print always values from 0 to 15 on any platform?
```
#include <stdio.h>
typedef struct UI4{
unsigned value: 4;
} ui4;
int main(void)
{
ui4 u;
u.value = 0;
while (1) {
printf("%u\n", u.value++);
}
return 0;
}
```
| Yes, unsigned integer overflows are guaranteed to "wrap around" by the standard.
|
What are the correct JNA mappings of the C types uint8_t and int8_t? Thank you!
| The only 8-bit integer data type in Java isbyte, so you would use that. Unfortunately it is signed, souint8_tvalues over 127 will be seen as negative when converted into Javabyte. This is not really a problem because the stored bits are the same.
|
So I was looking at some c++ source code and wanted to know just what the heck this meant. I think it means call tmp as a function but I'm not sure.
```
char* tmp;
///stuff filling tmp with values
((void (*)())tmp)();
```
| Yes, it's castingtmpas pointer to a function that accepts no arguments and returns nothing, then calling it.
Looks like a recipe for disaster, if you ask me.
|
I am getting an error when trying to call the method:
```
int box(int rows, int cols, int [rows][cols])
```
from the main method using this call:
```
box(arrayDimensions, arrayDimensions, array);
```
But i am not sure what the problem is.
Thanks.
| ```
int box(int rows, int cols, int [rows][cols])
```
needs to be
```
int box(int rows, int cols, int something[rows][cols])
```
|
What are the correct JNA mappings of the C types uint8_t and int8_t? Thank you!
| The only 8-bit integer data type in Java isbyte, so you would use that. Unfortunately it is signed, souint8_tvalues over 127 will be seen as negative when converted into Javabyte. This is not really a problem because the stored bits are the same.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Postfix to Infix conversation
What would be the prefix notation of this expression? I can not solve this expression
```
6 a b 7 * + - c d g / + e ^ f * +
```
Any suggestion will be appreciated.
| The in-order expression will be
```
[6-(a + b*7)] + [(c + d/g) ^ e]*f
```
from that you can find the pre-order, which is
+ -6 + a * b 7 * ^ + c / d g e f
|
I find myself typing
```
double foo=1.0/sqrt(...);
```
a lot, and I've heard that modern processors have built-in inverse square root opcodes.
Is there a C or C++ standard library inverse square root function that
uses double precision floating point?is as accurate as1.0/sqrt(...)?is just as fast or faster than the result of1.0/sqrt(...)?
| No. No, there isn't. Not in C++. Nope.
|
I am using bool datatype in C std99 whose definitions are defined in<stdbool.h>. Now I want the user to give me input. What format specifier I must use in scanf to input the boolean value of 1 byte from the user and then manipulate it afterwards in my program.
| There is none.
Use a temp object as the size of_Boolis implementation dependent.
```
#include <stdbool.h>
#include <stdio.h>
bool b;
int temp;
scanf("%d", &temp);
b = temp;
```
|
I find myself typing
```
double foo=1.0/sqrt(...);
```
a lot, and I've heard that modern processors have built-in inverse square root opcodes.
Is there a C or C++ standard library inverse square root function that
uses double precision floating point?is as accurate as1.0/sqrt(...)?is just as fast or faster than the result of1.0/sqrt(...)?
| No. No, there isn't. Not in C++. Nope.
|
I am using bool datatype in C std99 whose definitions are defined in<stdbool.h>. Now I want the user to give me input. What format specifier I must use in scanf to input the boolean value of 1 byte from the user and then manipulate it afterwards in my program.
| There is none.
Use a temp object as the size of_Boolis implementation dependent.
```
#include <stdbool.h>
#include <stdio.h>
bool b;
int temp;
scanf("%d", &temp);
b = temp;
```
|
I get this error in a C header file in this line :
```
char * getFechaHora(time_t & tiempoPuro);
```
In a C source code file i am including the header file and giving the function an implementation
```
char * getFechaHora(time_t &tiempoPuro){...}
```
also in my header file i am including correctly the "time.h" library.
| ```
char * getFechaHora(time_t & tiempoPuro);
```
This is not C. C has no reference (&).
|
I am using functiongetopt_longto get command line options.
I want to ignore error when a invalid option is given.
Currently it printing error to stderr like:
```
invalid option -- 's'
```
| There's variableopterrin getopt.h which will avoid printing the the error tostderrif you set it to 0.
Just set it to 0:
```
extern int opterr;
opterr = 0;
```
|
I get this error in a C header file in this line :
```
char * getFechaHora(time_t & tiempoPuro);
```
In a C source code file i am including the header file and giving the function an implementation
```
char * getFechaHora(time_t &tiempoPuro){...}
```
also in my header file i am including correctly the "time.h" library.
| ```
char * getFechaHora(time_t & tiempoPuro);
```
This is not C. C has no reference (&).
|
```
char* output= (char*) argv[2];
92 fp = fopen(output, "w");
93 if( fp = NULL )
94 {
95 printf("writing output failed");
96 return 0;
97 }
98 fprintf(fp,"hello");
```
This is causing seg fault exc bad memory at line 98.
What am I missing??
| Your line
```
if( fp = NULL)
```
is assigning the value ofNULLtofp, instead of comparing.
You should be using
```
if( fp == NULL)
```
|
For example if my program name istest.c
Then for the following run command theargc = 2instead of4.
$test abc pqr* *xyz*
| Try to run:
```
$ echo abc pqr* *xyz*
```
and you will understand why you don't get theargcvalue you were expecting
|
I have this matrix:
```
1 2 3 4 5
6 7 8 9 A
B C D E F
0 1 2 3 4
```
And I want it printed in one line as following:
```
1 6 2 B 7 3 0 C 8 4 1 D 9 5 2 E A 3 F 4.
```
How is the easiest way to do that?
| use a nested loop.
outer loop is over the distance from (0,0)
inner loop over all valid combinations of i and j that sum up to the distance.
|
I wonder why when I try to declare the array using#defineI get errors from compiler, while using literal instead of the size allows me to do so.
some_name.h:
```
#define size 10;
int* waitingBench[size];
```
| What you have will be pre-processed to:
```
int* waitingBench[10;];
// ^ notice this guy!
```
Remove the semicolon from the#define.
(Andsizeis a really bad identifier to#define.)
|
I have a program with 2 threads. I want the first thread to be run under user permissions of USER_1, and the second under USER_2 of Windows. When I log in as USER_1, both threads have USER_1 permissions. How can I change the user of the thread!?
| You need to assign an impersonation token to a thread usingSetThreadToken(). It may not be very trivial to do, though.
|
Can somebody please explain to me why the below code got the "invalid operands to binary ==" error?
```
typedef int (*func_t)(int);
#define NO_FUNC ((func_t) 0)
struct {
const char *name;
func_t func;
} table[] = { {"func1", NO_FUNC} };
if (table[0] == NO_FUNC) { // invalid operands to binary ==
}
```
| And you should refer to the correct member in the struct:
```
if (table[0].func == NO_FUNC)
```
|
I need to discover name of audio device by ID. I use WaveOut functions. please help me
| This is an example on how to enumerate waveIn and waveOut devices on your system:
http://blogs.msdn.com/b/matthew_van_eerde/archive/2012/03/13/sample-how-to-enumerate-wavein-and-waveout-devices-on-your-system.aspx
So, you can just compare dev id you need and get name of the device.
|
I need to discover name of audio device by ID. I use WaveOut functions. please help me
| This is an example on how to enumerate waveIn and waveOut devices on your system:
http://blogs.msdn.com/b/matthew_van_eerde/archive/2012/03/13/sample-how-to-enumerate-wavein-and-waveout-devices-on-your-system.aspx
So, you can just compare dev id you need and get name of the device.
|
Is there a replacement forpiconst on OS X 10.8?
When I use it I get the following warning:
```
'pi' is deprecated: first deprecated on Mac OS X 10.8
```
It works but I want to get rid of that warning.
| Try includingmath.h, which defines the C standard library macroM_PI.
|
Is there a replacement forpiconst on OS X 10.8?
When I use it I get the following warning:
```
'pi' is deprecated: first deprecated on Mac OS X 10.8
```
It works but I want to get rid of that warning.
| Try includingmath.h, which defines the C standard library macroM_PI.
|
This question already has an answer here:Closed10 years ago.
Possible Duplicate:How would you convert from ASCII to Hex by character in C?
I like to convert a hex value, represented in ascii code to the number represented by the hex value.
As an example:
A5should convert to0xA5(which is 165)
ButA5is represented inASCII(so something like0x4135I guess)
Any ideas?
Thx!
| Usestrtol.
```
long x = strtol("A5", 0, 16)
// x is now 165
```
|
I'm having problems with applesexamplesfor vDSP. I tried all of them but i need the convolution sample in the end.
I can't even get it through the linker:
```
Undefined symbols for architecture i386:
"_conv", referenced from:
_ConvTiming in main.o
ld: symbol(s) not found for architecture i386
```
Is the error message (no matter what architecture i build for or).
| You need to include the Accelerate framework in the build.
|
I have the followingcharinside an Arduino sketch:
```
char inData[80];
```
When I print to the serial console:
```
Serial.print(strlen(inData) - 1);
```
I'm expecting to see:79instead I see:655356553501234567
Can someone shed some light as to why this is happening?
| strlenis looking for a terminating nul. Calling it on an uninitialized array or pointer results in undefined behavior. You wantsizeof(inData)instead.
|
How do I cut off decimal places in C without rounding?
For example if the number is4.48
it will just show4.4
%.1frounds to4.5
| You can (ab)use the fact that integer division truncates and doesn't round:
```
float original = 4.48;
int tmp = original * 10; // 44.8 truncated to 44
float truncated = tmp / 10.0; // 4.4
```
|
I have a code like:
```
int contains(LPCTSTR name)
{
char * data = "test.txt";
}
```
How can i check whethernamecontains 'data'? Thanks!
| Since you are using Windows andTCHAR, a more idiomatic solution would be:
```
BOOL contains(LPCTSTR lpName) {
return _tcsstr(name, _T("data"));
}
```
Unless yourdatais deliberately achar *, in which case the answer changes.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.