question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
How can I access theElementsof anIplImage(single channel and IPL_DEPTH_8U depth).
I want to change the pixel value at a particular (x, y) position of the image.
| opencv provide CV_IMAGE_ELEM method to access elements of IplImage,it's a macro,
```
define CV_IMAGE_ELEM( image, elemtype, row, col ) \
(((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)])
```
second parameter is the type of
|
I've seen parsers where the the handling of each keyword is controlled by an array of structures containing each keyword and function pointers to how to handle that keyword. What is this pattern called?
Rather than trying to include a vague example here, I'll just point you to myproject.
| It sounds very much likeTable-Driven parsing, which is generally employed byLR parsers.
|
If I try to executes these commands:
```
int main(int argc, char* argv[])
{
execl("/bin/echo","echo","list ","of", "files:\n",NULL);
execl("/bin/ls","ls","-al",NULL);
return 0;
}
```
Only the first one gets executed, why?
| execl REPLACES the current process - it's not a subroutine. You might try usingsystem()instead.
|
I am debugging a program using gdb. First Iloadmy executable, then Icontinueto run the program. I sometimes want to interrupt execution of my program, so I doCtrl + C.
My problem is that this closesbothmy program and gdb. How can I exit my program without exiting gdb?
| Have you tried to usekillfrom inside gdb?
|
I have the following code:
```
int *pa;
int a[3] = {1, 2, 3};
```
Why pa = a is ok, but a = pa is not allowed?
| The main difference is that type ofais still an array but it justdecaysinto a pointer when you dopa=a;.pawill now point to thefirstelement of the array not the entire array itself. When you doa=pait doesnot make any sense as you are trying point a datatype which is holding 3 integers to a type which can point only to a single integer.
|
How can i add a label next to a toolbar item in GTK+?For instance i want to show a save button and the text "Save" next to it like gedit or so.
| gtk_action_set_is_important()if you're using GtkActions,gtk_tool_item_set_is_important()if you're using GtkToolItems.
|
I expectuint32means "unsigned 32-bit integer".
What does thetstand for?
| The suffix_tdenotes atype name. For example,size_tis the type for size.
Another popular line of thought regards it as a convention for namingtype definitions.
|
I have the following binary number
```
uint64_t = 0b0100;
```
And I want to negate it to
```
0b1011
```
This is a specific example but I want it to work for any binary number variable. For example,
uint64_t a
So is there a function like negate that would make the following true
```
a == negate(negate(a));
```
| Simply use thebitwise negation operator:
```
bar = ~bar
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:What is a fast C or Objective-C math parser?
I have a NSString which represents a calculation eg.@"(10+10)*2"and I want to evaluate the string as if it was actually something like this;
```
double result = (10+10)*2;
```
What is the most straightforward approach to take in iOS?
| Take a look at Dave DeLong'sDDMathParser framework.
|
Is there any macro or function to construct a float (double) from a given sign, mantissa and exponent (all binary or decimal) that either returns a valid float (double) number or returns NaN if the number specified by input is not representable as float (double)?
| The function you're looking for isldexp.
|
Is there a good C/C++ library for creating PNG files and that supports colored polygons and shapes? This library should be OS independent, since I need it for both Linux and Windows.
| TheCairolibrary meets your requirements.
|
I have an embedded device with Python installed on in. Is it possible to explicitly access registers in pure Python, or should I write C extensions for my Python code?
| It seems that you can't access the low level registers. I recommend just writing a short C extension code to allow Python to access the registers you need.
|
How can I check in C# whether a directory is shared?
And is it done in C/C++ under Windows?
The directory is on the same PC!
| As for C#: To check wether you can access (read access at least) a network share / unc path with the current logged in user, do aIO.Directory.Exists(@"\\YourUNCShare")
For C++:
Check out this question
There's alsothisMSDN article, usingPathFileExistswhich should do forC.
|
How can I check in C# whether a directory is shared?
And is it done in C/C++ under Windows?
The directory is on the same PC!
| As for C#: To check wether you can access (read access at least) a network share / unc path with the current logged in user, do aIO.Directory.Exists(@"\\YourUNCShare")
For C++:
Check out this question
There's alsothisMSDN article, usingPathFileExistswhich should do forC.
|
I am looking for an native function from the C libraries or code example to implement it: I have a string that contains byte values that I want to convert it to int value. how do I this? I tried usingatoi()andatol()but it get only0from0xbff18c08. Thanks.
| Then you are likely looking forstrtoul(str, NULL, 16).
|
I have written client-server application in C. I run the server in linux.
I need to do simple logs of what server do. I print it to the screen.
Please how can I copy output of the screen also to the file.
Thx
| You can use theteecommand as:
```
./server_program | tee server.log
```
|
Is there a way to programmatically determine the type(/name) of the underlying file system? The file system in this case can be a parallel file system like lustre/pvfs. So I need to query this name, and not the name of the underlying file system like ext3.
Thank you.
| What is thef_typefield from thestatfs()function giving you?
|
Could help about making that code pure C.
```
struct edge
{
char key;
char values[5];
};
edge* a = new edge[9];
```
| ```
typedef struct
{
char key;
char values[5];
} edge ;
edge *a = malloc(9 * sizeof(edge)) ;
```
This should do it
|
```
char str1[20] = "Something";
char *str2 = "Random";
strcat(str1, str2[1]);
```
It gives the error pointer from integer without a cast
why is str2[1] treated as an integer?
so what should I do if I want to strcat individual elements in a string
Thanks!
| Because an element from achararrayisachar, which is an integral type. If you want a pointer to the second element, trystr2 + 1or&str2[1].
|
I have searched through a lot of folders, but found definition only (in stdio.h) - not the realization.
| It's in the source code for the C library:
http://opensource.apple.com/source/Libc/Libc-763.12/stdio/getline-fbsd.c
|
I have a GtkImage that I am manipulating with a GdkPixbuf. When I change it, I need to redraw it to make the changes take effect. Right now I am doing this by hiding and then showing the image. What would be the proper way of doing this?
| gtk_widget_queue_draw()function invalidates the widget area and forces redrawing.
|
I have a C program in which two scanf() are done.
I need to write a shellscript that will run the program and give it the arguments too.
The problem is that all I could come up with is how to pipeline an argument into the program as a command line arguments which is not what I need.
Any help appreciated.
| This should work
```
echo "some input" | yourprog
```
e.g. echo "1 1 + p" | dc
|
I need to write a program in BSD sockets which behaves like a file transfer protocol for transferring file contents. It has to use two TCP connections between client and server.
If not code, please provide any other reference material such as flowchart or algorithm for the implementation.
| Try going through the FTP documentation availablehere.
|
I am working on a game in C using SDL and I created a window with SDL_NOFRAME so I loosed minimize & close native buttons , I added 2 buttons " _ " and " X " onclick " X " quit the game but I couldn't find a solution for Minimize " _ " any idea ?!!
| You can useSDL_WM_IconifyWindowto minimize your window.
http://www.libsdl.org/cgi/docwiki.cgi/SDL_WM_IconifyWindow
|
I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg.
But I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?
| The Wikipedia page onstdarghas probably everything you need.
|
CODE :
```
int *Array[8];
Array[0] = (int *) malloc(sizeof(int) * 5);
printf("%d" , sizeof(Array)/sizeof(int)); // Result = 8 : True
printf("%d" , sizeof(Array[0])/sizeof(int)); // Result = 1 : False
```
How do I get length of Array[0] that is 5?
| You can't.
Dynamic arrays in C don't carry around their length information with them. So you'll need to write your code to remember that it allocated something of length 5.
|
I am working on a game in C using SDL and I created a window with SDL_NOFRAME so I loosed minimize & close native buttons , I added 2 buttons " _ " and " X " onclick " X " quit the game but I couldn't find a solution for Minimize " _ " any idea ?!!
| You can useSDL_WM_IconifyWindowto minimize your window.
http://www.libsdl.org/cgi/docwiki.cgi/SDL_WM_IconifyWindow
|
I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg.
But I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?
| The Wikipedia page onstdarghas probably everything you need.
|
CODE :
```
int *Array[8];
Array[0] = (int *) malloc(sizeof(int) * 5);
printf("%d" , sizeof(Array)/sizeof(int)); // Result = 8 : True
printf("%d" , sizeof(Array[0])/sizeof(int)); // Result = 1 : False
```
How do I get length of Array[0] that is 5?
| You can't.
Dynamic arrays in C don't carry around their length information with them. So you'll need to write your code to remember that it allocated something of length 5.
|
I am working on a game in C using SDL and I created a window with SDL_NOFRAME so I loosed minimize & close native buttons , I added 2 buttons " _ " and " X " onclick " X " quit the game but I couldn't find a solution for Minimize " _ " any idea ?!!
| You can useSDL_WM_IconifyWindowto minimize your window.
http://www.libsdl.org/cgi/docwiki.cgi/SDL_WM_IconifyWindow
|
I have a nice C++ function, which supports multiple arguments through va_list + va_start + va_arg.
But I had to convert my project to C. After conversion, this va_list construction gets rejected by the compiler (multiple errors). Is there any way to do that thing in C, and (if yes) what I need to change?
| The Wikipedia page onstdarghas probably everything you need.
|
CODE :
```
int *Array[8];
Array[0] = (int *) malloc(sizeof(int) * 5);
printf("%d" , sizeof(Array)/sizeof(int)); // Result = 8 : True
printf("%d" , sizeof(Array[0])/sizeof(int)); // Result = 1 : False
```
How do I get length of Array[0] that is 5?
| You can't.
Dynamic arrays in C don't carry around their length information with them. So you'll need to write your code to remember that it allocated something of length 5.
|
I have a variable type:
```
char (*p)[12] = calloc(n, sizeof(*p));
```
I need the variable to stay this way, but I am having trouble passing it as a parameter due to the function type giving me errors:
```
void myMethod(char *p) { ... }
```
What can I use in myMethod as the parameter to make this work?
| What can I use in myMethod as the parameter to make this work
Possibly this:
```
void myMethod(char (*p)[12])
```
|
I have a program (main.c) that calls an external assembly function (function.s).
Themain.cdeclare and use the assembly function:
```
extern int function(int n);
res = function(3);
```
It works:
```
> gcc function.s main.c -o test
```
But, how can I have to configure Netbeans to build and debug it?
Thanks in advance!
| Perhaps an issue for copying the code.
Writing from scratch works well.
That's all
|
I've read that the ideal size of a structure for performance, that's going to be used in a large collection, is 32 bytes. Is this true and why? Does this effect 64bit processors or is it not applicable?
This is in context of modern (2008+) home Intel-based systems.
| The ideal size of a struct is enough to hold the information it needs to contain.
|
I know there are similar questions answered but I did not find the answer I am looking for.
Is there any short and simple way of converting an integer(1digit) to char? Something similar to how we do it with char to int, just by adding+'0'
| Assuming you are asking how to go from'9'to9, just apply the inverse operation, i.e., subtract'0':
```
char digit= value + '0';
int value= digit - '0';
```
|
I currently have something of the form
```
char** args = { "a", "s", "d", "f" };
```
What I want is
```
char** newArgs = { "s", "d", "f" };
```
What's the easiest way to do this?
Thanks.
| Perhaps this:
```
newargs = args + 1;
```
Or maybe:
```
newargs = &args[1];
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:In C arrays why is this true? a[5] == 5[a]
Is this instruction correct in c :
5["abcdef"]
If yes, what does it mean ?
I had this question in a c test.
| Yes, it is correct, and means the same as"abcdef"[5], which evaluates to'f'.
It is becausea[b] == *(a+b) == *(b+a) == b[a]by definition.
|
Can fragment shader in OpenGL ES 2.0 change the Z value (depth) of a pixel?
How is this achieved in OpenGL ES 2.0?
| No --gl_FragDepth(which is part of the desktop version of GLSL) is not present in OpenGL ES.
You can, however, check for the existence ofGL_EXT_frag_depth. If it's available, then you can write the depth togl_FragDepthEXT.
Theextension papergives more details about how to enable the extension and such.
|
a friend of mine gave me a piece of his software and I'm trying to compile it on Ubuntu 11.04.Now gcc says thatev.his not installed and I thought you could tell me where to get it because I did not find it by myself.
| libev?
If so, you'd need to install the libev-devUbuntu package.
|
I'm trying to match a pattern and this keeps failing (return 1):
```
fnmatch(findme, d_name, FNM_PATHNAME)
```
when findme= "cproject", d_name="./.cproject" Also in gdb debugger I tried this:
```
//in gdb
p fnmatch("f","fa",0x10)
```
returns 1. If match "f" and "f" it returns 0 (match).
| f only matches f. You need f* to match fa.
|
I have one clarification
What is the difference between calling a function through function pointer and calling a function directly by name ?
Anybody help me in this.
| There is no difference in the actual call. Parameters are passed the same way, the function runs the same way, and the return value comes back the same way.
The only difference is that you can make the function pointer point somewhere else.
|
I'm trying to set up theHg-Git Mercurial Extension, which recommends using the C compiler for Microsoft Visual C++ 2008. I've installed Visual C++ 2008, but I can't figure out where the C compiler is located so that I can add it to my path.
| Windows 7 / Vista:
```
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Bin\cl.exe
```
Windows XP:
```
C:\Program Files\Microsoft Visual Studio 9.0\VC\Bin\cl.exe
```
|
How do I take an input of 2 32 bit unsigned integers, multiply them and get the output as a 64 bit integer in C? Any help is appreciated! Thanks.
| ```
#include <stdint.h>
uint64_t mul64(uint32_t x, uint32_t y) {
return (uint64_t)x*(uint64_t)y;
}
```
|
How do I take an input of 2 32 bit unsigned integers, multiply them and get the output as a 64 bit integer in C? Any help is appreciated! Thanks.
| ```
#include <stdint.h>
uint64_t mul64(uint32_t x, uint32_t y) {
return (uint64_t)x*(uint64_t)y;
}
```
|
I am trying to get network interface information fromstruct ifaddrs
How can I determine if the interface I am looking at is of inet (ipv4) or inet6 (ipv6)?
| You test theifa_addr->sa_family- it will beAF_INETfor IPv4 addresses, andAF_INET6for IPv6 addresses.
You can then cast theifa_addrmember to eitherstruct sockaddr_in *orstruct sockaddr_in6 *as appropriate.
|
Suppose I have a pointer to a function calledfoo. How do I now run the function that this is pointing to?
| If you function has the following signature:
```
void foo(int x);
```
And you have defined the following pointer:
```
void (*ptr)(int) = foo;
```
You can execute foo, through "ptr", like this:
```
ptr(12); //actually calls foo(12);
```
|
I have trouble loading my driver using OSR driver loader. I point the path to my driver, register service successfuly, but when I click start service I receive error message "The system cannot find the file specified."
In the concrete, I have tried to make driver from the sample:
http://www.ndis.com/ndis-ndis6/inspect/packetinspect.htm
Any ideas please?
| Making and Signing Driver Packages for NDIS Protocol Drivers
|
In C i can do this:
```
ppackage ppnull() {
return (ppackage) {
.type = NULL
}
}
```
However, in C++ I get syntax errors. I use the GNUg++compiler. Is there a switch to enable this?
| Withc++11you can use initializer list:
```
struct ppackage
{
void* type;
};
ppackage ppnull()
{
return {nullptr};
}
```
Or just
```
ppackage ppnull()
{
return {};
}
```
|
I have a file stream in C and I want to know how many lines are in it without iterating through the file. Each line is the same length. How might I go about this?
| How about something like this:
Do afgetsand find out how long one line isFind the size of the file usingfseekandftellfseek(fp, 0, SEEK_END);
size = ftell(fp);Divide by the size of the line
You can also usefseekoandftellowhich work withoff_t.
|
How will you implement a tree structure in C for navigation in preorder depth-first manner?
| A tree can be represented by two arrays: one that holds pre-order traversal and the second hold in-order traversal.This threaddiscusses [among other things] how it can be done.
Since array traversal is usually faster then tree traversal [due to cache performance mainly], you can represent the tree as 2 arrays, and use the pre-order traversal one to iterate.
|
Tell me please why this function may take'\0'as second argument, compile and crash?
```
char var[9];
/*some initialization of var */
strcat(var, '\0');
```
| That function takes aconst char *as the second parameter. You're passing anint.
```
char *strcat(char *restrict s1, const char *restrict s2);
```
You're basically trickingstrcatinto dereferencing\0as a pointer - it dereferencesNULL.
|
I got aliba.socontaining a functionsay_hi(),
```
char *say_hi()
{
return "hello, world";
}
```
In Python, I accessedliba.soviactypes,
```
>>>liba = ctypes.CDLL("./liba.so")
>>>liba.say_hi()
16422018
```
How can I retrieve the string"hello, world"returned byliba.say_hi()in Python?
PS
Besidesrestype, any other way?
| Does this answer your question?
http://docs.python.org/library/ctypes.html#return-types
|
How to implement a program in c to calculate 2^999 ?
| You need to use a big integer library which work with arbitrarily sized arrays. GMP is popular:http://gmplib.org/.
If you're willing to sacrifice precision you can use adoublewhich can represent values up to about 1.8 * 10^308 by just usingpow()(2^999 = ~5.4 * 10^300).
|
I would like to create a array having 21 values between 0 to 20.I would like them to be in random and at the same time non-repeated.
I know how to create a random number between 0 to 20.
```
0 + rand()/(RAND_MAX/(20-0+1)+1)
```
But i don't know how to create those numbers such that it is not repeated comparing to previous numbers
| You probably want to use something like theFisher-Yates shuffle.
|
On ARM architecture, unfortunately I don't know exactly what chip it is, is a 32 bit int read/write atomic?
Is there any sort of guarantees about reads/writes to basic types?
| It should be atomic, EXCEPT if that int is stored on a non-aligned address.
|
I want to assign some value (say 2345) to a memory location(say 0X12AED567). Can this be done?
In other words, how can I implement the following function?
```
void AssignValToPointer(uint32_t pointer, int value)
{
}
```
| The fact that you are asking this question kind of indicates that you're in over your head. But here you go:
```
*(int *)0x12AED567 = 2345;
```
|
In a header file a definition is given by
```
static void (*foo[CONST]) (void);
```
What is its meaning ?
| It's meaning is an array withCONSTamount of elements of function pointers with signaturevoid f(void);
These things get used most often for callbacks, for example the functionatexit.
|
What is the practice on comparing a pthread_t variable to int. I display a list of all thread ids and I take in input from the user specifying which thread to kill, using the id. So how do I compare the input from the user to all of the pthread_t variables.
| What is the practice on comparing a pthread_t variable to int.
You don't. The typepthread_tis opaque: it need not be an integer. You should instead use thepid_tas returned bygettid.
|
I'm learning ODBC, and my application needs to use multiple connections concurrently. Should I be allocating a single environment, and then multiple connections from this?
Or an environment for each connection?
Many thanks!
| I'm not sure there is anything to be gained from creating multiple environments unless you are going to change something at the environment level e.g., call SQLSetEnvAttr with different arguments on each environment handle.
|
I've used:
```
sprintf(hex, "%02x", (unsigned int) buffer[0] & 0xff);
```
to get hexadecimal representation of binary file. After that I save this representation to txt file.
Now I' d like to execute inverse operation. How can I create binary file from my hex data?
| sscanf()will let you do the inverse ofsprintf()
```
int output;
int we_read_an_integer = sscanf(inputString, "%02x", &output);
```
Repeat as necessary.
|
When i try to include SDL, it prints an error:
```
error: SDL.h: No such file or directory
```
My system is Mac OSX Lion and i´ve installed SDL.
I use this:
```
#include "SDL.h"
```
| Specify the include directory of theSDL.hheader togccwith the option-I.
For example:
```
gcc -I/usr/include/SDL -c test.c
```
|
I want to assign a string like:"22 33"to a variable likechar*av[129]. How can i do that in C/C++?
| ```
strcpy(av[0], "22 33");
```
IFyou knowav[0]is long enough (length of string you want to put in plus one for theNUL).
Otherwise, usestrncpy.
|
When i try to include SDL, it prints an error:
```
error: SDL.h: No such file or directory
```
My system is Mac OSX Lion and i´ve installed SDL.
I use this:
```
#include "SDL.h"
```
| Specify the include directory of theSDL.hheader togccwith the option-I.
For example:
```
gcc -I/usr/include/SDL -c test.c
```
|
I want to assign a string like:"22 33"to a variable likechar*av[129]. How can i do that in C/C++?
| ```
strcpy(av[0], "22 33");
```
IFyou knowav[0]is long enough (length of string you want to put in plus one for theNUL).
Otherwise, usestrncpy.
|
When i try to include SDL, it prints an error:
```
error: SDL.h: No such file or directory
```
My system is Mac OSX Lion and i´ve installed SDL.
I use this:
```
#include "SDL.h"
```
| Specify the include directory of theSDL.hheader togccwith the option-I.
For example:
```
gcc -I/usr/include/SDL -c test.c
```
|
I want to assign a string like:"22 33"to a variable likechar*av[129]. How can i do that in C/C++?
| ```
strcpy(av[0], "22 33");
```
IFyou knowav[0]is long enough (length of string you want to put in plus one for theNUL).
Otherwise, usestrncpy.
|
What is the name ofgcc's intrinsic for comparing__m256and__m256i(AVX instruction set)?
| As said in theIntel AVX documentation
```
_mm256_cmp_ps, _mm256_cmp_pd
```
etc
Note that instead of having multiple comparison instructions, you have to pass an enum indicating the comparison done. E.g :
```
res = _mm256_cmp_ps(a,b, _CMP_LT_OQ); // AVX res = a < b
```
|
I want to do something like this:
```
void* ptr = some_function(&ptr);
```
Is this legal in C?
| Yes, it's totally legal. Beware that your some_function will need to have this signature :
```
void* some_function(void** param)
```
|
I have multiple threads running (pthreads api), each with it's own timer that calls a function handler(int signum) after a certain interval. As these threads call handler and within the function handler, how do I know which thread called it? Is thread-specific data required?
| You can use thepthread_self()function to have the ID of the current thread.
|
I have an ulong value, how can i convert it to LPTSTR? I need to get LPTSTR value. (no printf)
Example code:
```
ULONG value = 1;
LPTSTR valueString = ???
```
Thanks!
| Use one of the_itoa()family of functions orStringCchPrintf(). The links go to the 'safe' versions of the functions, but the winapi also provides 'unsafe' and leagacy variants.
|
I'm testing the perror function in C, and according tothis pageit prints a default message when a null pointer is passed:
```
int main(void)
{
int *p;
perror(p); //crashes
}
```
| Causeint* pcontains a random/garbage value.
It is not anNULLpointer. You need to explicitly initialize it withp = NULL;.
Using an uninitialised variable is Undefined behaviour.
main()also needs toreturn 0;.
|
How to create and bind socket using winsock2, which will be receiving only packets which use ipv6 protocol.
Regards
| Almost everything about network sockets and even windows specific stuff can be found atBeej's Guide to Network Programming. Transition from IPv4 to IPv6 is described in detailhere
|
I have an ulong value, how can i convert it to LPTSTR? I need to get LPTSTR value. (no printf)
Example code:
```
ULONG value = 1;
LPTSTR valueString = ???
```
Thanks!
| Use one of the_itoa()family of functions orStringCchPrintf(). The links go to the 'safe' versions of the functions, but the winapi also provides 'unsafe' and leagacy variants.
|
Say I have a multi-digit integer in C. I want to break it up into single-digit integers.
123would turn into1,2, and3.
How can I do this, especially if I don't know how many digits the integer has?
| ```
int value = 123;
while (value > 0) {
int digit = value % 10;
// do something with digit
value /= 10;
}
```
|
I am wondering if it is possible to generate compiler warnings or errors for specific library functions.
For example, I work all the time on multithreaded programs and I would like to get a compiler warning whenever I try to use a not-threadsafe function like strtok (instead of strtok_r).
Thanks.
| You want to use the poison pragma:http://gcc.gnu.org/onlinedocs/gcc-3.2/cpp/Pragmas.html
```
#pragma GCC poison strtok
```
|
I am trying to concat two const char * strings.
When i have a statement likestrcat(a,b)I get the warningexpected ‘char * restrict’ but argument is of type ‘const char *’
is there a way to call strcat that will not produce the warning?
Thanks!
| strcat()modifies the first operand. Therefore it cannot beconst. But you passed it aconst char*.
So you can't usestrcat()on twoconst *charstrings.
|
In linux kernel how to mapblock_devicetodevicestruct? In other words if we have ablock_devicestruct how we can get correspondingdevicestruct?...
| It appears that shortest way for me is to findbdev_mappointer and perform akobj_lookup(bdev_map, inode->i_rdev, &dummy)operation. This returns akobjectthat correspons to block device (i_rdev).
|
This question already has answers here:Post-increment on a dereferenced pointer?(13 answers)Closed9 years ago.
I'm not really sure what the order here is. Is it:
1) Dereference the value of pointer p after increasing it
2) Dereference the value of pointer p before increasing it
| There is no ordering between the increment and the dereference. However, the*operator applies to the result ofp++, which is the original value ofpprior to the increment.
|
```
static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof(a)/sizeof(int);
```
Is there a shortcut, with ANSI 99?
| I think that there isn't a shortcut, but you cat use macro:
```
#define arrlen(arr) (sizeof(arr)/sizeof(arr[0]))
```
|
I am receiving 2 bytes of binary information via Serial in C.
I am receiving them in a char.
So I need to join the 2 chars to make a int but Im unsure how to do that.. first of all the first byte is in binary format and not char format.. So im unsure how I Can convert it into a useable form for my program.
| JustORthem together ?
```
x = (b1 << 8) | b2;
```
Make sure they're unsigned or cast accordingly (shifting signed stuff is nasty).
|
how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
```
char str[80];
str = "my cat is yellow";
```
How would I get yellow?
| Something like this:
```
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
```
|
I am receiving 2 bytes of binary information via Serial in C.
I am receiving them in a char.
So I need to join the 2 chars to make a int but Im unsure how to do that.. first of all the first byte is in binary format and not char format.. So im unsure how I Can convert it into a useable form for my program.
| JustORthem together ?
```
x = (b1 << 8) | b2;
```
Make sure they're unsigned or cast accordingly (shifting signed stuff is nasty).
|
how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
```
char str[80];
str = "my cat is yellow";
```
How would I get yellow?
| Something like this:
```
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
```
|
how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
```
char str[80];
str = "my cat is yellow";
```
How would I get yellow?
| Something like this:
```
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
```
|
Can someone explain me how to choose the precision of a float with a C function?
Examples:
theFatFunction(0.666666666, 3)returns 0.667
theFatFunction(0.111111111, 3)returns 0.111
| You can't do that, since precision is determined by the data type (i.e.floatordoubleorlong double). If you want to round it for printing purposes, you can use the proper format specifiers inprintf(), i.e.printf("%0.3f\n", 0.666666666).
|
I have a dll with a c interface, the functions of which will return error codes, I will also provide an additional function that returns the last error. Does this sound sensible? can anyone point me at any examples that i can use as a template please?
| "The last error" is not a very useful or reliable concept in the context of a DLL. What if the DLL is being used by several processes or threads?
|
One can get information about a process according to its PID reading files in /proc/PID directory. Is there any library providing such information directly?
| You may uselibproc-dev
Andhereis a little example
|
Is it possible to set values for default parameters in C? For example:
```
void display(int a, int b=10){
//do something
}
main(){
display(1);
display(1,2); // override default value
}
```
Visual Studio 2008, complaints that there is a syntax error in -void display(int a, int b=10). If this is not legal in C, whats the alternative? Please let me know. Thanks.
| Default parameters is a C++ feature.
C has no default parameters.
|
What is the exact difference between thegetchandgetcharfunctions?
| getchar()is a standard function that gets a character from the stdin.
getch()is non-standard. It gets a character from the keyboard (which may be different from stdin) and does not echo it.
|
The current size of long int in my system is 4 bytes. Is it possible to increase its size? In case it is not possible how to deal with situations where we need integral data type with specified byte size. The applications include factorial, permutations, combinations etc.
| how to deal with situations where we need integral data type with
specified byte size
Usestdint.htypes likeuint24_t,uint32_t,uint64_t, etc.
|
was wondering what would be the best data structure to store a telephone directory when it has to be accessed via both name and number?
| There is a bimap:http://commons.apache.org/collections/apidocs/org/apache/commons/collections/BidiMap.html
|
What is theCPU_STATE_MAXmacro and what is it used for? I couldn't find any descriptive/relevant google results or man pages.
I am on Mac OSX Snowleopard, if that makes any difference.
| Seethis--it corresponds to the number of CPU states defined in themachine.hheader. These different states are then used to index different pieces of information about the CPU state, which can differ by CPU state--idle, 'nice', etc.
|
was wondering what would be the best data structure to store a telephone directory when it has to be accessed via both name and number?
| There is a bimap:http://commons.apache.org/collections/apidocs/org/apache/commons/collections/BidiMap.html
|
What is theCPU_STATE_MAXmacro and what is it used for? I couldn't find any descriptive/relevant google results or man pages.
I am on Mac OSX Snowleopard, if that makes any difference.
| Seethis--it corresponds to the number of CPU states defined in themachine.hheader. These different states are then used to index different pieces of information about the CPU state, which can differ by CPU state--idle, 'nice', etc.
|
I am looking for information on the implementation of md5 algorithm using vectorization.
I am interested in the details of SSE* and the AVX instructions.Are there any ready-made library with support for vectorization?
| You could try looking atJohn the Ripper, they used to have highly optimized implementations of various cryptographic algorithms used to hash passwords.
|
I have a global variable, X. I then fork and modify X from the child. I want those changes to show up in the parent, but I don't want the parent to have to wait on the child.
How can I do this?
| You need to put the variable in shared memory. There are many ways to create shared memory. I'd probably just usemmap, but you could also check outshmgetorshm_open.
|
I am looking for information on the implementation of md5 algorithm using vectorization.
I am interested in the details of SSE* and the AVX instructions.Are there any ready-made library with support for vectorization?
| You could try looking atJohn the Ripper, they used to have highly optimized implementations of various cryptographic algorithms used to hash passwords.
|
I have a global variable, X. I then fork and modify X from the child. I want those changes to show up in the parent, but I don't want the parent to have to wait on the child.
How can I do this?
| You need to put the variable in shared memory. There are many ways to create shared memory. I'd probably just usemmap, but you could also check outshmgetorshm_open.
|
How can I split a string into an array of strings based on a dividing character? For instance, how could I split a sentence into an array of words, separated by the space character?
| You should use eitherstrtokorstrtok_r, both of which are describedhere(with examples). I'd recommended to usestrtok_r, sincestrtokis thread-unsafe, and you may add threads to your application in the future.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.