question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
I have a string being moved and i want to print it based on the register.
I did the following:
```
gdb x $esp
0xbffff110: "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"
{then I copied the address}
>> x *0xbffff110
0x80485bc <__dso_handle+12>: "test1"
```
Is there any way to do this in one step?
| Is there any way to do this in one step?
```
(gdb) print *(char**)$esp
```
|
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.
|
I have a string being moved and i want to print it based on the register.
I did the following:
```
gdb x $esp
0xbffff110: "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"
{then I copied the address}
>> x *0xbffff110
0x80485bc <__dso_handle+12>: "test1"
```
Is there any way to do this in one step?
| Is there any way to do this in one step?
```
(gdb) print *(char**)$esp
```
|
I have a string being moved and i want to print it based on the register.
I did the following:
```
gdb x $esp
0xbffff110: "\274\205\004\b\324\361\377\277\334\361\377\277]\257\344\267\304s\374\267"
{then I copied the address}
>> x *0xbffff110
0x80485bc <__dso_handle+12>: "test1"
```
Is there any way to do this in one step?
| Is there any way to do this in one step?
```
(gdb) print *(char**)$esp
```
|
We found that C will compile the log function when used with magic numbers, but not with a variable. Any ideas?
| Because you didn't link your program to the math library and with a literal your compiler is probably using a builtin function.
Withgccyou will get the same error with-fno-builtinwith a literal.
Link with lib math this way:gcc bla.c -o bla -lm
|
In C/C++, what's the difference between the following two line code:
```
char *str1="hello";
char *str2={"hello"};
```
| Per the 2011 C standard, clause 6.7.9 Initialization, paragraph 11: “The initializer for a scalar shall be a single expression, optionally enclosed in braces…”
That is it. There is no semantic difference; the braces simply may be present or may be absent, with no change to the meaning.
|
I run into a code:printf("\tout:\t%-14.14s\n", (sprintf(tmpbuf[0], "[%s]", mystring), tmpbuf[0]));What does those sentence in () with sprintf mean?
| It is an expression involving the comma operator, to put the following into a single line:
```
sprintf(tmpbuf[0], "[%s]", mystring);
printf("\tout:\t%-14.14s\n", tmpbuf[0]);
```
The comma operator evaluates both arguments and returns its right argument, i.e.tmpbuf[0].
|
```
#define START ((void (**)(int)) 0x0fff)
*START = &fun_foo();
```
I haven't seen this before. What is happening here? Is void (**)(int) a function pointer?
| void (**)(int)is a pointer to a pointer to a function that takes anintand returns nothing.
SoSTARTis apointer to a function pointer, and*STARTis the actual function pointer which is set to point tofun_foo.
|
```
#define START ((void (**)(int)) 0x0fff)
*START = &fun_foo();
```
I haven't seen this before. What is happening here? Is void (**)(int) a function pointer?
| void (**)(int)is a pointer to a pointer to a function that takes anintand returns nothing.
SoSTARTis apointer to a function pointer, and*STARTis the actual function pointer which is set to point tofun_foo.
|
In JavaScript i would usually do..
```
var myObject = { "Name" : "Liam", "Address" : "UK"};
```
How do i make something similar in C?
Preferably something of the structure
```
myObject { CHAR : INT}
```
| ```
struct myObj
{
char* string;
int num;
};
```
that's the most basic. you should learn c if you want to use this.
|
```
int age;
char name[10];
scanf("%d", &age);
scanf("%s", name);
```
In firstscanffunction we use'&'symbol before age, but in secondscanfwe don't use'&'as it is a char array. Can anybody tell me why is so?
| Because the array is already passed as an address, whereas the integer variable is not (and thus explicitly needs its address passed via the&address-of operator).
|
If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?
| Initialisers can be nested for nested structs, e.g.
```
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
```
|
Say I have two variables x and y, and I want to align the most significant 1s, how would I write this in C? For example, I have x=11 and y = 1011, and I want to align x with y by making it 1100. How could I do this?
| Run aBitScanReverse(or appropriate intrinsic for you compiler, like__builtin_clzfor GCC), subtract the smaller from the larger and shift the smaller to the left by the difference.
|
If I have a struct in C that has an integer and an array, how do I initialize the integer to 0 and the first element of the array to 0, if the struct is a member another struct so that for every instance of the other struct the integer and the array has those initialized values?
| Initialisers can be nested for nested structs, e.g.
```
typedef struct {
int j;
} Foo;
typedef struct {
int i;
Foo f;
} Bar;
Bar b = { 0, { 0 } };
```
|
Say I have two variables x and y, and I want to align the most significant 1s, how would I write this in C? For example, I have x=11 and y = 1011, and I want to align x with y by making it 1100. How could I do this?
| Run aBitScanReverse(or appropriate intrinsic for you compiler, like__builtin_clzfor GCC), subtract the smaller from the larger and shift the smaller to the left by the difference.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:C String literals: Where do they go?
If I have the following code
```
char *str = "Tryout" ;
```
where is the string going to be stored? Stack? If stack, does the pointer point to a stack location then?
| The string has a static storage class, (likely in read only data) andstris a local variable with automatic storage. This is why it is better declared asconst char *.
|
I have a linux based OS with a lot of system libraries compiled as static libraries.
How can I use such libraries in my application, andlinkthem to my final binary?
| You use them as you do use shared libraries, except that you link against statically.An introduction to GCC - shared libraries and static librariesarticle will get you started.
|
Is it possible to know the CPU usage of a running/idle process programatically (in any language) in Windows?
| If you don't care on support old Windows versions (earlier than Windows XP SP1) you could useGetSystemTimes Win32 API function.
Otherwise you have to usePerformance Counters.
|
How can I get the number of channels used by my video before initiating a capture?
I thought I could usecvGetCapturePropertybut there is no property_id I could set to get the number of channels.
| Yes, you're right - there are noproperty_idfor number of channels. You can get number of channels only from single frame of capture.
|
I am currently building 3.1 kernel for android (tegra/goldfish branch). I would like to write a program in C that gets the sensor values. I do have inc/hardware/sensors.h and some relevant files but I keep getting an error when trying to open the sensor device.
Thanks
| Take a look at the samples that are packed with the NDK,native-activityin particular.
|
Is it possible to know the CPU usage of a running/idle process programatically (in any language) in Windows?
| If you don't care on support old Windows versions (earlier than Windows XP SP1) you could useGetSystemTimes Win32 API function.
Otherwise you have to usePerformance Counters.
|
How can I get the number of channels used by my video before initiating a capture?
I thought I could usecvGetCapturePropertybut there is no property_id I could set to get the number of channels.
| Yes, you're right - there are noproperty_idfor number of channels. You can get number of channels only from single frame of capture.
|
I am currently building 3.1 kernel for android (tegra/goldfish branch). I would like to write a program in C that gets the sensor values. I do have inc/hardware/sensors.h and some relevant files but I keep getting an error when trying to open the sensor device.
Thanks
| Take a look at the samples that are packed with the NDK,native-activityin particular.
|
I am looking for a way to know how much time will my C program use, preferably before I run it, but if this cannot be known before, then after it has ended.
Is there a way?
| After, yes. On most (all?) UNIX-y systems, you can use this:
```
time ./myprog
```
Before, no, because the program could depend on external input.The halting problemmight also be an obstacle to finding the amount of time a program would take to execute beforehand.
|
I am looking for a way to know how much time will my C program use, preferably before I run it, but if this cannot be known before, then after it has ended.
Is there a way?
| After, yes. On most (all?) UNIX-y systems, you can use this:
```
time ./myprog
```
Before, no, because the program could depend on external input.The halting problemmight also be an obstacle to finding the amount of time a program would take to execute beforehand.
|
i have a code like this:
```
int i = 123;
char myString[100];
strcpy(myString, "my text");
```
and how i want to add the 123 after "my text". how to do this in c/c++?
at the endmyStringsould bemy test123
| In C++:
```
std::stringstream ss;
ss << "my text" << i;
std::string resultingString = ss.str();
```
There's no such thing as C/C++.
|
Im new to Pro*C coding. is there any difference between VARCHAR and char? can i select a
VARCHAR data into an character array? will there be any side effects?
| TheVARCHARis a special type added by the Pro*C pre-compiler, it doesn't exist in the base C language. However, in C you can access aVARCHARvariable as a structure if I'm not mistaken.
|
Im new to Pro*C coding. is there any difference between VARCHAR and char? can i select a
VARCHAR data into an character array? will there be any side effects?
| TheVARCHARis a special type added by the Pro*C pre-compiler, it doesn't exist in the base C language. However, in C you can access aVARCHARvariable as a structure if I'm not mistaken.
|
I'm trying toexecvea process that reads from stdin. I want to prepare stdin with some data so it can execute successfully. How can I do that?
| You will need to fork the execve call into a child process and then create a pipe from the parent process to the child's stdin.
Take a look at this link for a detailed example on how to use pipes:http://tldp.org/LDP/lpg/node11.html
|
How do I get the contents from one character buffer into another? For instance I have
```
char buffer[SMALLVALUE];
char new_buffer[BIGGERVALUE];
```
I'd like to copy the contents ofbufferintonew_buffer. What's the shortest way to do this?
| ```
#include <string.h>
memcpy(new_buffer, buffer, sizeof buffer);
```
|
Here is the thing,1024 = 0x400, and I assume its binary representation (little endian) is\\x00\\x4\\x00\\x00. And I try to do something like this,
```
int main()
{
const char *str = "\\x00\\x4\\x00\\x00";
const int *p = (const int *)str;
printf("%d\n", *p);
}
```
But why the above code can't give me1024?
| Because you escaped\. Unescape them:
```
const char *str = "\x00\x4\x00\x00";
```
|
Can anybody tell how to write a program which when compiled withgccprintsc, and withg++printsc++?
| ```
#ifdef __cplusplus
printf("c++\n");
#else
printf("c\n");
#endif
```
You may run into issues if your file extension isn't right.
|
What is the order of evaluation in C in the case ofx<<y>>z? Is it(x<<y)>>z, because of the Left to Right associativity ?
EDITNeed to know what the standards tell about it, and not guess what's going on by inspection for a particular compiler.
| Yes,>>and<<are left associative and of the same precedence, sox << y >> zis equivalent to(x << y) >> z.
|
moin-moin,
I need the MS Visual C (6.0) equivalent for the functions "DosEnterCritSec()" and "DosExitCritSec()", which garantees, that no two threads are executing the enclosed code at the same time.
Can anybody please point me into the right direction?
Thanks a lot,
Peter
| EnterCriticalSection() / LeaveCriticalSection()
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682608(v=vs.85).aspx
|
I am having this problem whenever I try to debug my project:
It's in French, here is my translation:
"Error while trying to run project: Failed Loading assembly "DBZ buu's
Fury Text Editor" or one of it's dependencies. The given assembly name
or codebase was invalid. (Exception from HRESULT: 0x80131047)"
Can anyone help me please?
| If you are usingAssembly.Load()to load file try to change it withAssembly.LoadFile()instead.
|
I'm dealing with some code written in manner that is really, honestly, ugly. Is there a way to auto enforce proper tabs and remove all of the random multi-line white space entries?
| Old Unix people have a solution for everything, including lazy programmers. EnterGNU indent.
|
I am readingGoogletest doc, and I am learning that there is one syntax for comparing string, and another for comparing C string. I dont see what is referred to as C string and as string. How are these different?
| If you try to useASSERT_EQto C-Strings, you only compare two pointers, but not really null-terminated C-Strings. For that existsASSERT_STREQsyntax.
|
How can I check if a directory exists on Linux in C?
| You can useopendir()and check ifENOENT == errnoon failure:
```
#include <dirent.h>
#include <errno.h>
DIR* dir = opendir("mydir");
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
} else {
/* opendir() failed for some other reason. */
}
```
|
I want to convert an array ofuint8_tto auint32_tinNesC.
Does anyone know how I can do this?
| The solution that i were found is the use of the function :
```
void * memcpy ( void * destination, const void * source, size_t num );
```
There is also the function :
```
void * memset ( void * ptr, int value, size_t num );
```
In my code i use memcpy and it works fine. Thanks to all people that answer my question
|
How can I find all words with at least one non latin letter (arabic, chinese...) in them using regex.h library?
cityدبي
| How about:
```
(?=\pL)(?![a-zA-Z])
```
This will match a letter in any alphabet that is not a latin letter:
```
not ok - cityدبي
ok - city
not ok - دبي
```
|
Are there any generally-applicable tips to reduce the accumulation of floating-point roundoff errors in C or C++? I'm thinking mainly about how to write code that gets compiled into optimal assembly language instructions, although strategies on overall algorithm design are also welcome.
| Numerical analysisis a whole field of mathematics and it isn't reduced to some tips one can apply blindly.
|
I want to convert an array ofuint8_tto auint32_tinNesC.
Does anyone know how I can do this?
| The solution that i were found is the use of the function :
```
void * memcpy ( void * destination, const void * source, size_t num );
```
There is also the function :
```
void * memset ( void * ptr, int value, size_t num );
```
In my code i use memcpy and it works fine. Thanks to all people that answer my question
|
How can I find all words with at least one non latin letter (arabic, chinese...) in them using regex.h library?
cityدبي
| How about:
```
(?=\pL)(?![a-zA-Z])
```
This will match a letter in any alphabet that is not a latin letter:
```
not ok - cityدبي
ok - city
not ok - دبي
```
|
Are there any generally-applicable tips to reduce the accumulation of floating-point roundoff errors in C or C++? I'm thinking mainly about how to write code that gets compiled into optimal assembly language instructions, although strategies on overall algorithm design are also welcome.
| Numerical analysisis a whole field of mathematics and it isn't reduced to some tips one can apply blindly.
|
I have something like this:
```
DIR *dir = opendir(curdir);
struct dirent *de = readdir(dir);
struc stat st;
lstat(de->d_name, &st);
```
I would like to know ifdeis a directory or a file, what should I do with st?
| The correct and simple way is to checkif (de->d_type == DT_DIR).
You don't have to uselstatfor that.
|
I have something like this:
```
DIR *dir = opendir(curdir);
struct dirent *de = readdir(dir);
struc stat st;
lstat(de->d_name, &st);
```
I would like to know ifdeis a directory or a file, what should I do with st?
| The correct and simple way is to checkif (de->d_type == DT_DIR).
You don't have to uselstatfor that.
|
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 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.
|
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 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.
|
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 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.
|
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.
|
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.
|
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.
|
I have an animated png that I want to load in my MFC project to show it animated. I need this because it's a loading animation, and I would love to know how to do it. Would love if you can tell me how this works for png files.
| Maybe this is what you want:
http://www.codeproject.com/Articles/1427/Add-GIF-animation-to-your-MFC-and-ATL-projects-wit
|
I have a MFC Dialog Application. I add a Edit Control in the Dialog and turn the autoSuggestion on by using following code
```
SHAutoComplete(txtPath.m_hWnd, SHACF_FILESYS_DIRS);
```
things work fine. But when I Scroll the Suggestion list and press Enter, The list does not close. How Can I do this? Thanks
| Take a lookhere: How To Use the ENTER Key from Edit Controls in a Dialog Box
|
I have a MFC Dialog Application. I add a Edit Control in the Dialog and turn the autoSuggestion on by using following code
```
SHAutoComplete(txtPath.m_hWnd, SHACF_FILESYS_DIRS);
```
things work fine. But when I Scroll the Suggestion list and press Enter, The list does not close. How Can I do this? Thanks
| Take a lookhere: How To Use the ENTER Key from Edit Controls in a Dialog Box
|
How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?
| Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.
|
How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?
| Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.
|
How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?
| Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.
|
I want to find "\r\n\r\n" in a HTTP header.
I know it's at the end of the packet, so if I reverse search "\r\n\r\n" I'll get good performance.
Is there a function implement reverse search in C or C++ ?
If so, which one?
Thanks.
| Reverse searching for "\r\n\r\n" might give you wrong result. It is not correct logic, because the HTTP body might contain "\r\n\r\n".
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:2GB limit on file size when using fwrite in C?
I realized that for my C compiler, the fread function can only correctly read a file smaller than 2GB (2147483648). I am wondering whether we could read >2GB file at all. Thanks
| You need to compile withlarge file support. Alternatively, on some platforms you can usefopen64.
|
I have achar buf[3];array where I need to put:buf[0] = chwherechis anint. But the compiler give the following warning:
conversion to ‘char’ from ‘int’ may alter its value
How do I remove this? I tried cast tounsigned charbut no luck.
| Use an explicit cast:
```
buf[0] = (char)ch;
```
|
In GNU-GCC with Linux this is working#define sprintfc(string, ...) sprintf(string+strlen(string), ##__VA_ARGS__)Is there definition with same effect for Visual Studio 2010?
| Microsoft Visual C compilerdoes support variadic macros. However, the problem isthe GCC extension ##, which removes the leading comma if no arguments are passed.
Because sprintf() is never called without a second argument, your code should work fine if you just remove the ##.
|
Where can we write code like
```
struct Foo
{
int bar;
int baz;
} foo()
{
}
```
C89/C90? C99? C11? Or maybe it's K&R only?
And what about this
```
void foo(bar, baz)
int bar;
int baz;
{
}
```
| It's standard since C89. In K&R C, it was not possible to return structs, only pointers to structs.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Writing GUI applicatins on Mac OS X with c++
I am looking for an easy to use program/framework for making c++ GUI on a mac.
| Qt is a very popular C++ GUI framework that targets Mac (and Windows and Linux and mobile)
http://qt.nokia.com/
|
I use to define multi-line stuff, something like a help message, like this:
```
#define HELP_MSG "blabla\r\n" \
"Some other line"
```
Is there a way that I can avoid putting "\r\n" here, since I already have it defined in multiple line.
| No,\is merely used as a linecontinuationmarker. If you need a line break, you need to include it explicitly in the string, as you're doing.
|
I have the following code. Why its undefined to derefrence union pointers in the following way ?
```
extern union MyUn *P1;
extern union MyUn *P2;
extern void myfunc(void)
{
*P1 = *P2;
}
```
| If you haven't also defined the union in this source file, the compiler doesn't know how much to copy.
What is the size of the union?
|
Why if I callRSA_size()on an RSA object do I obtain a value less than the return value ofi2d_RSAPublicKey(the size of the public key) called on the same RSA object?
| Becausei2d_RSAPublicKeygives you a PKCS#1 encoded version of the key, including public exponent and DER elements.
RSA_size()gives you just the size in bytes of the pure modulus (which is also the size of any unencoded signature or ciphertext for that key).
|
Does ~0 mean its flipping 000000000 to 1111111111?
```
printf("Check: %i", ~0);
```
The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?
| Does ~0 mean its flipping 000000000 to 1111111111?
Yes, it does.
Does -1 essentially mean the same thing as 11111111111111111 bits?
In2s complementrepresentation, it does.
|
Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
| No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.
It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.
|
I use to define multi-line stuff, something like a help message, like this:
```
#define HELP_MSG "blabla\r\n" \
"Some other line"
```
Is there a way that I can avoid putting "\r\n" here, since I already have it defined in multiple line.
| No,\is merely used as a linecontinuationmarker. If you need a line break, you need to include it explicitly in the string, as you're doing.
|
I have the following code. Why its undefined to derefrence union pointers in the following way ?
```
extern union MyUn *P1;
extern union MyUn *P2;
extern void myfunc(void)
{
*P1 = *P2;
}
```
| If you haven't also defined the union in this source file, the compiler doesn't know how much to copy.
What is the size of the union?
|
Why if I callRSA_size()on an RSA object do I obtain a value less than the return value ofi2d_RSAPublicKey(the size of the public key) called on the same RSA object?
| Becausei2d_RSAPublicKeygives you a PKCS#1 encoded version of the key, including public exponent and DER elements.
RSA_size()gives you just the size in bytes of the pure modulus (which is also the size of any unencoded signature or ciphertext for that key).
|
Does ~0 mean its flipping 000000000 to 1111111111?
```
printf("Check: %i", ~0);
```
The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?
| Does ~0 mean its flipping 000000000 to 1111111111?
Yes, it does.
Does -1 essentially mean the same thing as 11111111111111111 bits?
In2s complementrepresentation, it does.
|
Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
| No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.
It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.
|
Does ~0 mean its flipping 000000000 to 1111111111?
```
printf("Check: %i", ~0);
```
The printf results to -1, which is why I am confused.Does -1 essentially mean the same thing as 11111111111111111 bits?
| Does ~0 mean its flipping 000000000 to 1111111111?
Yes, it does.
Does -1 essentially mean the same thing as 11111111111111111 bits?
In2s complementrepresentation, it does.
|
Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
| No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.
It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a-Dor a comparable option of your C compiler.
|
Has any C guru ever implemented a Epoll Non-blocking selector in C that I can call from Java so I don't have to use Java's NIO Epoll implementation?
| You can find epoll sample program written in C by me. I hope that will help youCould you recommend some guides about Epoll on Linux
|
The below code snippet is used to convert a string to lower case.
```
int main()
{
unsigned char s[] = "AbS.d_";
tolower(s);
printf("%s\n", s);
return 0;
}
```
I am getting theoutputas:
```
AbS.d_
```
Why the string is not being converted?
| tolowertakes int and return lowered int.
This should work:
```
int i=0;
for(i=0; s[i]; i++)
{
s[i]=tolower(s[i]);
}
```
|
I am currently working on a embedded C project and I "inherited" some old code containing statements such as:
```
rxStruct = rxStruct;
```
where rxStruct is a variable.
What could be the use of such statements?
| Without further information, one use of such a statement is to prevent an unused parameter compiler warning ifrxStructis passed in as a parameter and then otherwise not used.
|
The below code snippet is used to convert a string to lower case.
```
int main()
{
unsigned char s[] = "AbS.d_";
tolower(s);
printf("%s\n", s);
return 0;
}
```
I am getting theoutputas:
```
AbS.d_
```
Why the string is not being converted?
| tolowertakes int and return lowered int.
This should work:
```
int i=0;
for(i=0; s[i]; i++)
{
s[i]=tolower(s[i]);
}
```
|
I am currently working on a embedded C project and I "inherited" some old code containing statements such as:
```
rxStruct = rxStruct;
```
where rxStruct is a variable.
What could be the use of such statements?
| Without further information, one use of such a statement is to prevent an unused parameter compiler warning ifrxStructis passed in as a parameter and then otherwise not used.
|
I defined a static struct in C like this:
```
typedef static struct {
int a;
int b;
} Hello;
```
Do I need to initiate the struct before I use it? How to access the variable inside of it?
| You need to define the struct first, then instantiate it in a static variable
```
typedef struct {
int a;
int b;
} Hello;
static Hello hello;
```
Then you can access your data like this :
```
hello.a = 42;
```
|
I don't know what the compilar is doing with++*p;
Can anyone explain me pictorically what is going on inside the memory in this code?
```
int main()
{
int arr[]={1,2,3,4};
int *p;
p=arr;
++*p;
printf("%d",*p);
}
```
| The answer should be 2
The reason is ++*p is is actually incrementing the first member in the array by 1.
|
I defined a static struct in C like this:
```
typedef static struct {
int a;
int b;
} Hello;
```
Do I need to initiate the struct before I use it? How to access the variable inside of it?
| You need to define the struct first, then instantiate it in a static variable
```
typedef struct {
int a;
int b;
} Hello;
static Hello hello;
```
Then you can access your data like this :
```
hello.a = 42;
```
|
I don't know what the compilar is doing with++*p;
Can anyone explain me pictorically what is going on inside the memory in this code?
```
int main()
{
int arr[]={1,2,3,4};
int *p;
p=arr;
++*p;
printf("%d",*p);
}
```
| The answer should be 2
The reason is ++*p is is actually incrementing the first member in the array by 1.
|
How should i create my own Events (This includes the code to bind the necessary callback) in c/C++ programming? It is directly available in Java.
| There aren't built-in events in C++, but if you don't want to reimplement your own classes, tryboost signals.
|
How should i create my own Events (This includes the code to bind the necessary callback) in c/C++ programming? It is directly available in Java.
| There aren't built-in events in C++, but if you don't want to reimplement your own classes, tryboost signals.
|
```
bool somemethod(int number){
return true;
}
```
I keep getting this error message when I try to compile code with this method
```
/Users/user/Desktop/test.c:14: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘somemethod’
```
| Thing isboolisn't a true keyword in C. Includestdbool.hif you need it - this should work with C99 implementations.
|
I just wanted to know that there is any free stack usage analyzer for C, something likehttp://www.absint.com/stackanalyzer/index.htm
| I think that gprof is a good tool.
http://www.cs.utah.edu/dept/old/texinfo/as/gprof.html
|
When I try to compile (on windows xp, with visual c++ 6.0) a c (NOT A C++) program which has the winusb.h header file, I get problems with c++ annotations (__in) like:
```
__in HANDLE DeviceHandle,
```
What do I need to get this compiled in c?
Thanks alot in advance!
| Just ignore it (and the similar annoations):
```
#define __in
#define __out
#define __in_opt
```
|
Functions likememPartInfoGet()requirePART_ID, in the manual it states thatmalloc()uses free lists of system memory partition. Is there a way to getstruct mem_part* PART_IDthat identifies with the system partition? To be able to use those functions?
| memSysPartIdis what I was looking for.
|
Given this macro:
```
#define SOME_MACRO(ret, f, args) \
typedef ret (*some_func_##f) args; \
static some_func_##f my_func_##f = NULL;
```
Please let me know the equivalent for:
```
SOME_MACRO(void, myFunctionName, (int a));
```
Thanks.
| You can use the-Eflag of gcc to see how the macro is expanded:
```
typedef void (*some_func_myFunctionName) (int a); static some_func_myFunctionName my_func_myFunctionName = ((void *)0);;
```
|
I have a question about enum variable in c++:
```
type enmu {
DAY1 = 1,
DAY2,
DAY3,
DAY4
} DAYS;
void main() {
DAYS days;
}
```
then what is the default value of days?
| It's uninitialized andundefined behaviorto read the value.
Just like saying
```
int x;
```
xdoesn't have a value until you initialize it.
|
How to return 1000 variables from a function in C?This is an interview question asked which I was unable to answer.
I guess with the help of pointers we can do that. I am new to pointers and C can anyone give me solution to solve this problem either using pointers or different approach?
| Pack them all in a structure and return the structure.
```
struct YourStructure
{
int a1;
int b2;
int z1000;
};
YouStructure doSomething();
```
|
I saw this code inthis .c file.
```
struct node {
Item data;
struct node *next;
};
struct stack_type {
struct node *top;
};
```
What are the benefits of creating two structs when one would do?
| It may make the code clearer to distinguish between the whole stack and a single node.
|
We have
```
int main(int argc, char** argv, char** envc)
```
for the ordinary. but I want to know if there is any other argument main can have instead of these. And if there is any, what does it point to?
| Well, heres the breakdown:
argc-- C standardargv-- C standardenv-- Works on most UNIX and MS Win, but not standardapple-- Other information passed as forth argument by Mac OSX and Darwin
|
Suppose a program has memory leaks.
1) When a process dies (normally or segmentation fault), are those leaked memory freed?
2) What aboutother resourcesa process holds?
| With most modern operating systems (linux, windows from around NT 3.5), yes.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.