question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Can someone please break down this code for me? I know it changes text from a user file and I know it could be very useful to me. What is the purpose of "~"? How could I amend this code to read a user file word by word and then change it using the same kind of formula?
```
// first value in the file is the key
if ( f... |
key = ~keyswaps all the bits of key
You know about bits?
asciiA(65) is 100 0001 in binary, so '~' of this is simply swaps each1for0and each0for1giving 011 1110 (62) which is>
So this will replace all theAs in your document with>and similarly for every other character. The nice thing about ~ is that it's exactly th... |
In a particular situation I need to have variable (character array or std:string) where the size should not be more than 10 kB.
How can I limit the size of this variable?
|
Just don't resize it to be more than the size limit:
```
char* realloc_lim(char* data, int new_count, bool &ok)
{
if(sizeof(char) * new_count > SIZE_LIMIT)
{
ok = false;
return null;
} else {
ok = true;
return (char*)realloc((void*)data, sizeof(char) * new_count);
}
}
`... |
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question
see i have one audio track whose sample rate is 44100 then what does it mean ?
what is the duration of one frame of audio... |
A sample of audio is similar to a frame of video, it's a capture of the sound level at a particular time point, in the same way as a frame of video is a capture of the light pattern. A frame rate of 44,100 is 44,100 samples per SECOND, or 44.1 kHz. So a sample duration is 1/44,100 seconds = 2.26e-5 seconds.
We can he... |
I defined a macro as follows:
```
#define ccpd(__X__, __Y__) (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? CGPointMake(__X__ * 0.416667f ,__Y__ * 0.416667f) : CGPointMake(__X__,__Y__)
```
Later:
```
CGPoint p1 = ccpd(1280, 440);
CGPoint p2 = ccpd(1024 + 256, 440);
```
This what I get:
```
(gdb) p p1
... |
You macro in the second case expands to something like:
```
CGPointMake( 1024 + 256 * 0.416667f, ...
```
which is
```
CGPointMake( 1024 + (256 * 0.416667f), ...
```
Add parenthesis around the macro parameters:
```
CGPointMake( (__X__) * 0.416667f, (__Y__) * ...
```
or better: make a proper function and let the c... |
I have a library managed by autotools. I have the following line in theMakefile.am, as well as other necessary configurations
```
lib_LTLIBRARIES = libstuff.la
```
My project also builds a program to run some test suites. This program is configured as follows:
```
noinst_PROGRAMS = runtests
runtests_SOURCES = test/... |
The right way to do this is to add the-staticflag to anLDFLAGSvariable.
For all targets:AM_LDFLAGS = -static
Or specifically for the test program:runtests_LDFLAGS = -static
|
I intend to use syslog for logging in an application. I need to be able to disable logging, at compile time, perhaps using a macro. Is this possible to do with the syslog facilities, or do I need to wrap syslog in my own macros/functions? The ability to disable/enable log messages based on their priority is a plus.
|
Maybe you could wrap a call tosetlogmaskin define block.
setlogmasksets a mask (the “logmask”) that determines which future
syslog calls shall be ignored. If a program has not called setlogmask,
syslog doesn't ignore any calls. You can use setlogmask to specify
that messages of particular priorities shall be ig... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:how does do{} while(0) work in macro?
Example fromthisblog post:
```
#define VTAILQ_INSERT_BEFORE(listelm, elm, field) do { \
(elm)->field.vtqe_prev = (listelm)->field.vtqe_prev; \
VTAILQ_NEXT((elm), field)... |
Long story short:
If you use a non looped macro in an unbraced if else statement, you will get screwed.
```
if (a)
VTAILQ_INSERT_BEFORE(c, d, e);
else
blah(b);
```
Would break terribly in this case.
More detailed answer here:
Why use apparently meaningless do-while and if-else statements in macros?
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:C : pointer to struct in the struct definition
In my beginer course we need to declare a struct for tree search. I need pointers for reference of same type in each node. This decleration seems incorrect, pnode is not known in this context.... |
the C Faq is a good reference.http://c-faq.com/struct/selfref.html
I tend to use the typedef before the struct method
http://c-faq.com/decl/selfrefstruct.html
```
typedef struct a *APTR;
typedef struct b *BPTR;
struct a {
int afield;
BPTR bpointer;
};
struct b {
int bfield... |
If I have:
```
#define MAXLINE 5000
```
What type is MAXLINE understood to be? Should I assume it is anint? Can I test it somehow?
In general, how can one determine the type of#defineed variable?
|
It has no type. It is a simple text substitution. The text 5000 will be dropped in place wherever MAXLINE appears as a token.
For example:
```
int a = MAXLINE;
```
will put the value 5000 ina.
While
```
char *MAXLINE2 = "MAXLINE";
```
will not result in
```
char *50002 = "5000";
```
So, if you want type-checki... |
I need to obtain an inverse cosine and inverse sine from the result of a series of other calculations. If my input value is outside the range -1 to 1 thenacosforasinfreturnnan, which is expected given the definition of the function.
How should I adjust the value so that it falls within the acceptable range, but still... |
There is no normalization process. If the answer is outside [-1,+1], then the preceding calculations are broken.
One exception is if floating-point inaccuracies have lead to a value such as 1.00001. In cases such as these, it is probably safe to clamp the input to the valid range.
|
How can you know ifpopen()succeeded/done running the shell or failed?
|
popen return value:
Upon successful completion, popen() shall return a pointer to an open
stream that can be used to read or write to the pipe. Otherwise, it
shall return a null pointer and may set errno to indicate the error.
```
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
```
|
What is the best way to check if a file exists, if not create it and write info by using mac
library <.mach-o/dyld.h> or other..?
|
Your question is unclear.
Checking if a file exists is trivial - usestat()oraccess(), e.g.:
```
#include <unistd.h>
int res = access(path, R_OK);
if (res < 0) {
if (errno == ENOENT) {
// file does not exist
} else if (errno == EACCES) {
// file exists but is not readable
} else {
... |
This question already has an answer here:Closed11 years ago.
Possible Duplicate:Interprocess semaphores sometimes not working as expected
In my application, I notice that a semaphore of typesem_tsometimes become 1 from 0 without executingsem_post. How come? What can cause this? The semaphore is used for inter-proces... |
The code that you are linking to doesn't capture the return values from thesem_tcalls. If you look in the manual you can see that e.gsem_waitcan return prematurely, so-called spurious wakeups.
Always check the return codes of these functions. If the return is-1checkerrnofor the corresponding error and decide if it is... |
Why is GCC giving me this error ? What am I doing wrong here ?
```
temp.c: In function main:
temp.c:6: error: invalid operands to binary +
```
Code:
```
main()
{
char *Address1,*Address2,*NewAddress;
Address1= (char*)0x12;
Address2= (char*)0x34;
NewAddress = Address1+Address2;
}
```
|
Why do you want to do that?
The C language forbids addition of two pointers. It only defines (with severe restrictions) the addition of a pointer and an integer.
Basically, you can only add to a pointer an integer small enough so that the result was inside, or at the ending border, of some allocated memory zone.
|
Hello guys I was reading a C source and I found a notation like this:
```
__no_init __root extern volatile unsigned char var[10] @ 0x4000000;
```
But I've no idea what that __no_init __root means, is it standard C?
Thank you.
|
These are C language extensions used in some compilers targeting embedded systems (for example, IAR'sAVR compiler).
__no_initwould mean that the compiler should not initialize the variable, and would be used when a variable is placed at a hardware register location and you don't want the start-up of the program to se... |
I want to get the current executable's file path without the executable name at the end.
I'm using:
```
char path[1024];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
printf("executable path is %s\n", path);
else
printf("buffer too small; need size %u\n", size);
```
It works, but... |
dirname(path);should return path without executable after you acquire path with, that is on Unix systems, for windows you can do some strcpy/strcat magic.
For dirname you need to include#include <libgen.h>...
|
How to process (in read-only fashion) a big binary file inC/C++onLinuxas fast as possible? Viareadormmap? What buffer size? (No boost or anything.)
|
mmap is faster and optimal for read only applications. See answer here:
https://stackoverflow.com/a/258097/1094175
|
I have a variabletweetthat is a string and it has a character at the very beginning that I want to clip off.
So what I want to do is usestrstr()to remove it. Here's my code:
```
tweet = strstr(tweet, "]");
```
However, I get this error:
```
cannot convert 'String' to 'const char*' for argument '1' to
'char' strs... |
stringhas ac_str()member function that returnsconst char *.
|
Here,I have some Doubt with the output.
Why the Output is same ?
```
int (*r)[10];
printf("r=%p *r=%p\n",r,*r);
return 0;
```
Platform- GCC UBUNTU 10.04
|
Because Name of the array decays to an pointer to its first element.
```
int (*r)[10];
```
Is an pointer to an array of10integers.rgives you the pointer itself.
This pointer to the array must be dereferenced to access the value of each element.So contrary to what you think**rand not*rgives you access to the first e... |
If I'm writing to a file/device in blocking mode does thewrite()call return on writing all the bytes(assume no signal interruption) toBuffered Cache(Kernel Buffer)or it returns on writing all bytes to the file/device? (This is extension to my earlierquestion).
|
If successful,writereturns after writing the data to kernel memory. Thewritesystem call makes no guarantees about writing to the disk, you needfsyncfor that. Actually,fsyncdoes not guarantee that the bits were actually written to the platter itself: just that the IO operation is complete.
(Of course, there are vari... |
If I have:
```
#define MAXLINE 5000
```
What type is MAXLINE understood to be? Should I assume it is anint? Can I test it somehow?
In general, how can one determine the type of#defineed variable?
|
It has no type. It is a simple text substitution. The text 5000 will be dropped in place wherever MAXLINE appears as a token.
For example:
```
int a = MAXLINE;
```
will put the value 5000 ina.
While
```
char *MAXLINE2 = "MAXLINE";
```
will not result in
```
char *50002 = "5000";
```
So, if you want type-checki... |
I need to obtain an inverse cosine and inverse sine from the result of a series of other calculations. If my input value is outside the range -1 to 1 thenacosforasinfreturnnan, which is expected given the definition of the function.
How should I adjust the value so that it falls within the acceptable range, but still... |
There is no normalization process. If the answer is outside [-1,+1], then the preceding calculations are broken.
One exception is if floating-point inaccuracies have lead to a value such as 1.00001. In cases such as these, it is probably safe to clamp the input to the valid range.
|
How can you know ifpopen()succeeded/done running the shell or failed?
|
popen return value:
Upon successful completion, popen() shall return a pointer to an open
stream that can be used to read or write to the pipe. Otherwise, it
shall return a null pointer and may set errno to indicate the error.
```
fp = popen("ls *", "r");
if (fp == NULL)
/* Handle error */;
```
|
What is the best way to check if a file exists, if not create it and write info by using mac
library <.mach-o/dyld.h> or other..?
|
Your question is unclear.
Checking if a file exists is trivial - usestat()oraccess(), e.g.:
```
#include <unistd.h>
int res = access(path, R_OK);
if (res < 0) {
if (errno == ENOENT) {
// file does not exist
} else if (errno == EACCES) {
// file exists but is not readable
} else {
... |
This question already has an answer here:Closed11 years ago.
Possible Duplicate:Interprocess semaphores sometimes not working as expected
In my application, I notice that a semaphore of typesem_tsometimes become 1 from 0 without executingsem_post. How come? What can cause this? The semaphore is used for inter-proces... |
The code that you are linking to doesn't capture the return values from thesem_tcalls. If you look in the manual you can see that e.gsem_waitcan return prematurely, so-called spurious wakeups.
Always check the return codes of these functions. If the return is-1checkerrnofor the corresponding error and decide if it is... |
Why is GCC giving me this error ? What am I doing wrong here ?
```
temp.c: In function main:
temp.c:6: error: invalid operands to binary +
```
Code:
```
main()
{
char *Address1,*Address2,*NewAddress;
Address1= (char*)0x12;
Address2= (char*)0x34;
NewAddress = Address1+Address2;
}
```
|
Why do you want to do that?
The C language forbids addition of two pointers. It only defines (with severe restrictions) the addition of a pointer and an integer.
Basically, you can only add to a pointer an integer small enough so that the result was inside, or at the ending border, of some allocated memory zone.
|
Hello guys I was reading a C source and I found a notation like this:
```
__no_init __root extern volatile unsigned char var[10] @ 0x4000000;
```
But I've no idea what that __no_init __root means, is it standard C?
Thank you.
|
These are C language extensions used in some compilers targeting embedded systems (for example, IAR'sAVR compiler).
__no_initwould mean that the compiler should not initialize the variable, and would be used when a variable is placed at a hardware register location and you don't want the start-up of the program to se... |
I want to get the current executable's file path without the executable name at the end.
I'm using:
```
char path[1024];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
printf("executable path is %s\n", path);
else
printf("buffer too small; need size %u\n", size);
```
It works, but... |
dirname(path);should return path without executable after you acquire path with, that is on Unix systems, for windows you can do some strcpy/strcat magic.
For dirname you need to include#include <libgen.h>...
|
How to process (in read-only fashion) a big binary file inC/C++onLinuxas fast as possible? Viareadormmap? What buffer size? (No boost or anything.)
|
mmap is faster and optimal for read only applications. See answer here:
https://stackoverflow.com/a/258097/1094175
|
I have a variabletweetthat is a string and it has a character at the very beginning that I want to clip off.
So what I want to do is usestrstr()to remove it. Here's my code:
```
tweet = strstr(tweet, "]");
```
However, I get this error:
```
cannot convert 'String' to 'const char*' for argument '1' to
'char' strs... |
stringhas ac_str()member function that returnsconst char *.
|
Here,I have some Doubt with the output.
Why the Output is same ?
```
int (*r)[10];
printf("r=%p *r=%p\n",r,*r);
return 0;
```
Platform- GCC UBUNTU 10.04
|
Because Name of the array decays to an pointer to its first element.
```
int (*r)[10];
```
Is an pointer to an array of10integers.rgives you the pointer itself.
This pointer to the array must be dereferenced to access the value of each element.So contrary to what you think**rand not*rgives you access to the first e... |
This question has been bugging me for a while
Is it usual to have a piece of code that works like this:
```
bool failed = false;
if (ptr)
{
if (ptr->value == foo)
{
print("error");
failed = true;
}
}
if (!failed)
{
print("all systems go");
}
```
Or can it be done with out the bool?
I... |
You can always rely on boolean operatorsshort-circuiting:
```
const bool failed = (ptr != NULL) && (ptr->value == foo);
```
This will not evaluate the second part if the first (ptr != NULL) evaluates to false.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Why i am not getting the expected output in the following c programme?
i am having a doubt in order of evaluation of macros.like for the following code i am not able to understand the ouput:
```
#include <stdio.h>
#define f(a,b) a##b
#def... |
It's a consequence of how macros are expanded, and has an impact on self-referential macros... This is quite nicely explained in detail in theGNU CPP manual
|
If I wrote a server bound to a wildcard address (INADDR_ANY), how to determine which IP address the client is connected to?
I tried the following code when the after a successful accept call, but it just returned 0.0.0.0.
```
inet_ntop(AF_INET, &server_address.sin_addr, s, sizeof(s));
```
|
As stated inHow to determine IP used by client connecting to INADDR_ANY listener socket in C, usegetsockname, which gives you the socket which the connection is bound to (on local level).
This is for C, but is applicable for C++ to.
|
How do I make a process go the background in C?
I know how to do that in UNIX but how to do it in Windows ?
What I want is for the user to double-click the process executable, and it just goes into the background ... and does not open a window while executing.
I'm not looking for complete solution just a reference.
... |
As @ChikaneHimeko has already stated create a Windows application that has no windows:
```
#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
Sleep(5000); /* Just here to... |
Please help me in understanding the following C Output:
```
#include<stdio.h>
int main() {
float x = 4.0;
printf("%f\n",x);
printf("%d\n",x);
int y=x;
printf("%d\n",y);
return 0;
}
```
Ouput on gcc compiler
```
4.000000
0
4
```
As far as i have read when we assign float to an int variable t... |
You're not printingy, you're printingxagain.
As a side note,printfcan't do conversions. So passing a float when a%dis expected is undefined behavior.
|
I am going through an eg pgm to create a make file.
http://mrbook.org/tutorials/make/
My folder eg_make_creation contains the following files,
```
desktop:~/eg_make_creation$ ls
factorial.c functions.h hello hello.c main.c Makefile
```
Makefile
```
all:gcc -c main.c hello.c factorial.c -o hello
```
error:
... |
The syntax of makefiles is very strict:
```
target:dependencies
build_rules
# ^ this space here _needs_ to be a tab.
```
What you wrote makesalldepend ongcc,-c, ... which are not valid targets.
What you need is something like:
```
all: hello
hello: factorial.c functions.h hello.c main.c
gcc -o... |
If all bits are 0 (example Imemsetthe floating point variable to all 0), what is the value of IEEE floating point used in gcc? It is guaranteed to be 0.0 ?
I guess for other floating point formats result may vary. But my question is specific to IEEE floating point used with gcc.
|
If the implementation is IEEE 754 compliant there exist special cases for different bit-combinations, like documentedhere.
For your case: When all bits (sign, exponent, mantissa) are zero the floating point value represents also zero, as defined by IEEE 754. More specifically, that value is a "positive zero", also wr... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:How to measure time in milliseconds using ANSI C?How can I get the Windows system time with millisecond resolution?
We want to calculate the time which a player have taken to finish the game.
But with time.h we could only calculate in seco... |
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX functiongettimeofday().
|
In C, how can i pass more than one argument to a thread?
Normally, I do it in a way like,
```
pthread_create(&th,NULL,dosomething,(void*)connfd);
void * dosomething(void *connfd)
{
// Doing something
}
```
In the above example,I am passing connfd value only to the thread 'th'.
Is there any way to pass ... |
Pack the several values inside astructon the heap (somallocit and fill it before), then callpthread_createwith a pointer to thatstruct.
|
```
#include<stdio.h>
typedef enum ss{
a,
b
}s;
int get(s *dbb)
{
*dbb = 1;
return 1;
}
int printss(s dbs)
{
printf("db no is:%d",dbs);
return 2;
}
int main()
{
s db;
get(&db);
printss(db);
return 0;
}
```
I am getting the deepcheck warning as "unintialised variable" db in the function printss.
But i'm i... |
Simply setdbto any value before usinggetto get it:
```
int main()
{
s db = a; // dummy value for initialization only
get(&db); // really setting the value of db.
printss(db);
return 0;
}
```
|
Say, I have a integer like10101, I would like to unset the third bit to get10001; if I have10001, I will still get10001; how can I achieve it?
```
unset(int i, int j)
int i= 10101 or 10000
int j = 00100
```
|
Assuming that you are indexing bits from the right, this should work to unset a particular bit invalue:
```
int mask = 1 << bitIndex;
value &= ~mask;
```
You can set the bit using similar code:
```
value |= mask;
```
wheremaskis as before. (This assumes that bit indexing starts at 0.)
|
So quick, odd question:
I took an exam, and a question was:
```
char c = 'A'
char *p =&c
char **p2 = &p
void *v = &p2
```
Write the type (i.e. int, void*, etc.) of the following expression:
&vp2 + 1v[0]
I answered:
void **char**ILLEGAL
and lost full credit. I just wanted to get a second opinion from someone befo... |
Your answers are correct, for the reasons you gave (apart for the bit about dereferencingv, although it sounds like you already know that you can't dereference avoid *).
|
Can someone explain please how to set a filter usingstruct bpf_programmemberstruct bpf_insn? All documentation and tutorials are welcome, for example what would be the struct bpf_insn if i want to filter for example dhcp, dns or ...?
Thanks for your help.
|
This tutorial uses struct bpf_program to create a filter program, not sure if that helps much but it's worth a look. (scroll down to the tcp bit).
http://www.enderunix.org/docs/en/rawipspoof/
|
I'm learning C . I want to list an array's values.
In PHP :
```
$arr = array("laguna", "megane", "clio");
foreach($arr as $no => $name)
{
echo $no." ) ".$name;
}
/*
Output :
0) Laguna
1) Megane
2) Clio
*/
```
How can i do it in C?
|
In C
```
char* arr[] = {"laguna","megane","clio",NULL};
for( int i = 0; arr[i]; i++)
{
printf("%d) %s\n",i,arr[i]);
}
```
|
What is mnemonic for "W" i.e. what does "W" mean in the following macros:
```
int WIFEXITED (int status)
int WEXITSTATUS (int status)
int WIFSIGNALED (int status)
int WTERMSIG (int status)
int WCOREDUMP (int status)
int WIFSTOPPED (int status)
int WSTOPSIG (int status)
```
Also seeProcess Status Completion.
|
It is simply related toW-aiting functions like thewaitpidsyscall.
|
The code below is ok withreturn n <= 100 && (printf("%d\n", n), print(n+1)) || 0;but gives error forreturn n <= 1000 && (printf("%d\n", n), print(n+1)) || 0;
```
#include <stdio.h>
int print(int n)
{
return n <= 1000 && (printf("%d\n", n), print(n+1)) || 0;
}
int main(void)
{
print(1);
return 0;
}
```
Thi... |
Looks like a simple stack overflow caused by the recursion depth. Your options:
Don't worry about it, you'd never write this sort of code for real.Increase the stack size.Do your homework assignment without using recursion if that is permitted.
|
I am looking for a simple interface for prepared statements in c that follows the printf structure.
Something along the lines of:
```
sqlite3 *connection;
sqlite3_open("db", &connection);
char *id = "chacham15";
int count = 5;
ArrayList* results = sqlite3_preparef(connection, "SELECT * FROM Data WHERE id=%s AND coun... |
Just use snprintf() then sqlite3_prepare_v2(). If you want to write a wrapper function that does both, look up stdarg (to make a variadic function) and vsnprintf().
|
This question already has answers here:What is a good general approach for deciding return values in C?(8 answers)Closed9 years ago.
I was wondering whether there are any pre-agreed values, coming from the old days of C language, that reflect tha function execution threw exception/terminated abruptly/failed for any ... |
Functions that return pointers usually returnNULLto indicate failure (e.g.malloc).
Most POSIX functions return0on success, and non-zero on failure. If they need to return a non-zero value as part of normal operation, they often return a negative value on failure.
But this is all just convention.
|
I'm totally new to C. Here's the question:
Write the functionfzero(double f(double),double x1, double x2)as we did in class and use it to find all the solutions ofsin( pi*x / (1+x^2) ) = 0.25.
Now, I don't want you to solve the this. I'd missed this lecture and only want to understand what means
```
double f(double... |
In that context, it means thatfis afunction pointerto a function to that takes onedoubleargument, and returns adouble.
As an example:
```
void foo(double f(double))
{
double y = f(3.0); // Call function through function pointer
printf("Output = %f\n", y); // Prints "Output = 9.0000"
}
double square(doubl... |
We are studying the use of the canaries to avoid buffer overflow.
There is a question that is:
Why aren't canaries useful in this struct?
```
struct test {
char arra[64];
int myVar;
}
```
and I'm stuck on it. Any clue?
Pd. This is homework
|
I believe your professor means it will not protect (for sure) from overflow of thearraywithin your structure. The compiler places the canary value somewhere between your structure and the end of the stack. If you overflow your array by less than int bytes, the overflow corrupts the int element of your structure, not t... |
I want to write a test php extension, which will provide a test class. I want to extract class declaration into a separate C-File and call class registration from module init function of myext.c file. I have the following files:
```
testlib/
test_class.c
myext.c
php_myext.h
config.m4
...
```
Now conf... |
It's pretty straightforward:
```
PHP_NEW_EXTENSION(myext, myext.c testlib/test_class.c, $ext_shared)
```
|
I have a text file with hexadecimal values. Now I need to convert the hexadecimal value to binary and need to save it on another file.
But I don't know how to convert the hexadecimal value to a binary string!
Please help...
|
It's quite easy, really, because the translation goes digit-by-digit.
```
0 - 0000
1 - 0001
2 - 0010
3 - 0011
4 - 0100
5 - 0101
6 - 0110
7 - 0111
8 - 1000
9 - 1001
A - 1010
B - 1011
C - 1100
D - 1101
E - 1110
F - 1111
```
So, for example, the hex numberFE2F8will be11111110001011111000in binary
|
Is is possible to implement the password field which we see on webpages using C language???
|
This code can serve the purpose:-
```
#include <stdio.h>
#include <conio.h>
#define MAX 25
#define passfield 1
void main()
{
char password[MAX], passchar;
int i=0;
clrscr();
printf("Enter password: ");
while(passfield)
{
passchar=getch();
if(passchar==13)
break; // 13 is the ASCII value of ENTER
if(p... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
Silly questions call for silly answers.
```
printf("Yes, the number is even or odd\n");
```
|
Exercise 7-1.Write a program that converts upper case to lower or lower case to upper, depending on the name it is invoked with, as found in argv[0].
For those of you interested in writing the program, you can find sample solutions here:http://users.powernet.co.uk/eton/kandr2/krx701.html
My question, however, is exa... |
Can you just scan the string for the last/character and use all the characters from that point on?
|
In general ,as per C standard is it guaranteed that memset() with 0 will zero out the padding bits in a C structure?
What about gcc?
For example , something like:
```
struct MyStruct
{
unsigned char member1;
unsigned int member2;
char member3;
unsigned char member4;
float mem... |
Perhaps worth noting thatmemsetdoesn't know anything about your struct (or array, or primitive, or any chunk of memory whatsoever that you happen to unleash it on), so even if it wanted to leave the padding bits intact, it wouldn't even know where they are.
|
Is there an efficient way of finding thetask_structfor a specified PID, without iterating through thetask_structlist?
|
What's wrong with using one of the following?
```
extern struct task_struct *find_task_by_vpid(pid_t nr);
extern struct task_struct *find_task_by_pid_ns(pid_t nr,
struct pid_namespace *ns);
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
I just started in C programming and... |
There's a good summary of the specifiers available athttp://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders.
|
Suppose I write a block to a file descriptor without doing fsync and then read the same block from the same descriptor some time later. Is itguaranteedthat I will receive the same information?
The program is single-threaded and no other process will access the file at any time.
|
Yes, it is guaranteed by the operating system.
Even if the modifications have not made it to disk yet, the OS uses its buffer cache to reflect file modifications and guarantees atomicity level for reads and writes, to ALL processes. So not only your process, but any other process, would be able to see the changes.
A... |
I'd like to write an application (in C) that uses the terminal of a *nix OS as its GUI. I mean an application of the kinds of emacs, vi etc. that take up the whole terminal window and jump back to the input prompt after quitting.How would you go about doing that, preferably in C? Can someone point me to a tutorial cov... |
You need to use ncurses:
http://en.wikipedia.org/wiki/Ncurseshttp://tldp.org/HOWTO/NCURSES-Programming-HOWTO/
It is available on all major distros.
|
What's the difference betweenllvmc.exeandclang.exe? Which one do I use for compiling C or C++ code?
|
llvmcis a frontend for various programs in the LLVM toolchain, in particular thellvm-*ones, ie by default it will try to usellvm-gccandllvm-g++to compile C and C++ files.
You can pass-clangtollvmcif that's what you want to use, and it's probably possible to configurellvmcsoclangwill be used by default, but I have no ... |
I have this function takes more than one char parameters.how to print each of them and add a '\n' at the end of each char?
```
void printAndSave(char* msg,...)
{
//printing single one.
//printf("Log:%s\n",msg);
//saveToLog(msg);
//how to print all of them?
}
```
|
I think you will need to change the signature ofprintAndSave()to specify the number ofchar*arguments being passed. For example:
```
void printAndSave(const unsigned int arg_count, ...)
{
unsigned int i;
char* val;
va_list vl;
va_start(vl,arg_count);
for (i=0;i<arg_count;i++)
{
val=va_... |
I want to change the actual argument passed to a function and not a copy of it. For example:
```
char str[] = "This is a string";
```
I want to create a function after a call to which the value ofstris different. I tried to create a function acceptingchar**as the argument but I just couldn't get what I want.
|
I think you mean something like this:
```
void update_string(char ** ptr)
{
*ptr = strdup("This is a test");
return;
}
```
Then call the function like this:
```
char * str = strdup("hello world\n");
printf("%s\n", str);
update_string(&str);
printf("%s\n", str);
```
|
When I browsed the source code of unzip, I encoutered a main function as follows,
```
int MAIN(argc, argv) /* return PK-type error code (except under VMS) */
int argc;
char *argv[];
{
int r;
CONSTRUCTGLOBALS();
r = unzip(__G__ argc, argv);
DESTROYGLOBALS();
RETURN(r);
}
```
I think the... |
This is the old K&R style function declaration. So yes, it's valid C, abeitvery oldC.
I wouldn't recommend writing this type declaration since it's completely obsolete and will likely confuse anyone reading your code who isn't familiar with the syntax.
|
I am reading APUE, and when I came tolongjmp, the question came. Before optimization, both the auto variable and register variable store in memory, after optimization, they store in register, the book says. But when I useobjdump -S a.out, I found both of them became to immediate operand. So ?
|
Your book was just simplifying. Even before optimizing there is no guarantee that variables are realized in memory. The difference betweenautoandregisteris just that you are not allowed to take the address of aregistervariable. The C compiler can do anything that behaves the same as the abstract machine.
That your co... |
I havechar* myChar = "HELLO". I would like to switch the places of the E and the O. I tried doingmyChar[1] = myChar[4], but that doesn't work. Please help!
|
First off, that string literal is probably being stored in read-only memory. You can fix that by declaring the string as an array of characters:
```
char myChar[] = "HELLO";
```
To swap the characters, you'll have to use a temporary variable:
```
char c1 = myChar[1];
myChar[1] = myChar[4];
myChar[4] = c1;
```
|
I need to do a complete format on a USB stick (FAT16 or FAT32), put a file on the drive, then delete it and recover the file using a C program.
Could anyone give me a hint on what should I use to accomplish this?
I understand the layouts of the FAT16/32 filesystems, the problem is that I don't know how to access the... |
This is highly operating system specific.
For Linux, you would open the raw device/dev/sdxx. Note that there are privilege hoops to manage.
For Windows, you would use something like:
```
HANDLE h = CreateFile ("\\\\.\\PhysicalDriveX", GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
... |
It seems to me that MCU RAM holds linker values, globally scoped variables, heap, stack, and then some portion is unused.
As a result, do engineers tend to release firmware that leaves some chunk of MCU RAM unused as it is unneeded for the application to work?
|
It depends on the application. In some cases, you might design some unused RAM in order to allow for future patches and growth. In many cases, you would just take whatever is unused and use that to enlarge the heap or stack or some application specific buffers.
|
I'm totally new to C. Here's the question:
Write the functionfzero(double f(double),double x1, double x2)as we did in class and use it to find all the solutions ofsin( pi*x / (1+x^2) ) = 0.25.
Now, I don't want you to solve the this. I'd missed this lecture and only want to understand what means
```
double f(double... |
In that context, it means thatfis afunction pointerto a function to that takes onedoubleargument, and returns adouble.
As an example:
```
void foo(double f(double))
{
double y = f(3.0); // Call function through function pointer
printf("Output = %f\n", y); // Prints "Output = 9.0000"
}
double square(doubl... |
We are studying the use of the canaries to avoid buffer overflow.
There is a question that is:
Why aren't canaries useful in this struct?
```
struct test {
char arra[64];
int myVar;
}
```
and I'm stuck on it. Any clue?
Pd. This is homework
|
I believe your professor means it will not protect (for sure) from overflow of thearraywithin your structure. The compiler places the canary value somewhere between your structure and the end of the stack. If you overflow your array by less than int bytes, the overflow corrupts the int element of your structure, not t... |
I want to write a test php extension, which will provide a test class. I want to extract class declaration into a separate C-File and call class registration from module init function of myext.c file. I have the following files:
```
testlib/
test_class.c
myext.c
php_myext.h
config.m4
...
```
Now conf... |
It's pretty straightforward:
```
PHP_NEW_EXTENSION(myext, myext.c testlib/test_class.c, $ext_shared)
```
|
I have a text file with hexadecimal values. Now I need to convert the hexadecimal value to binary and need to save it on another file.
But I don't know how to convert the hexadecimal value to a binary string!
Please help...
|
It's quite easy, really, because the translation goes digit-by-digit.
```
0 - 0000
1 - 0001
2 - 0010
3 - 0011
4 - 0100
5 - 0101
6 - 0110
7 - 0111
8 - 1000
9 - 1001
A - 1010
B - 1011
C - 1100
D - 1101
E - 1110
F - 1111
```
So, for example, the hex numberFE2F8will be11111110001011111000in binary
|
Is is possible to implement the password field which we see on webpages using C language???
|
This code can serve the purpose:-
```
#include <stdio.h>
#include <conio.h>
#define MAX 25
#define passfield 1
void main()
{
char password[MAX], passchar;
int i=0;
clrscr();
printf("Enter password: ");
while(passfield)
{
passchar=getch();
if(passchar==13)
break; // 13 is the ASCII value of ENTER
if(p... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
Silly questions call for silly answers.
```
printf("Yes, the number is even or odd\n");
```
|
Exercise 7-1.Write a program that converts upper case to lower or lower case to upper, depending on the name it is invoked with, as found in argv[0].
For those of you interested in writing the program, you can find sample solutions here:http://users.powernet.co.uk/eton/kandr2/krx701.html
My question, however, is exa... |
Can you just scan the string for the last/character and use all the characters from that point on?
|
In general ,as per C standard is it guaranteed that memset() with 0 will zero out the padding bits in a C structure?
What about gcc?
For example , something like:
```
struct MyStruct
{
unsigned char member1;
unsigned int member2;
char member3;
unsigned char member4;
float mem... |
Perhaps worth noting thatmemsetdoesn't know anything about your struct (or array, or primitive, or any chunk of memory whatsoever that you happen to unleash it on), so even if it wanted to leave the padding bits intact, it wouldn't even know where they are.
|
Is there an efficient way of finding thetask_structfor a specified PID, without iterating through thetask_structlist?
|
What's wrong with using one of the following?
```
extern struct task_struct *find_task_by_vpid(pid_t nr);
extern struct task_struct *find_task_by_pid_ns(pid_t nr,
struct pid_namespace *ns);
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
I just started in C programming and... |
There's a good summary of the specifiers available athttp://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders.
|
Suppose I write a block to a file descriptor without doing fsync and then read the same block from the same descriptor some time later. Is itguaranteedthat I will receive the same information?
The program is single-threaded and no other process will access the file at any time.
|
Yes, it is guaranteed by the operating system.
Even if the modifications have not made it to disk yet, the OS uses its buffer cache to reflect file modifications and guarantees atomicity level for reads and writes, to ALL processes. So not only your process, but any other process, would be able to see the changes.
A... |
I'd like to write an application (in C) that uses the terminal of a *nix OS as its GUI. I mean an application of the kinds of emacs, vi etc. that take up the whole terminal window and jump back to the input prompt after quitting.How would you go about doing that, preferably in C? Can someone point me to a tutorial cov... |
You need to use ncurses:
http://en.wikipedia.org/wiki/Ncurseshttp://tldp.org/HOWTO/NCURSES-Programming-HOWTO/
It is available on all major distros.
|
What's the difference betweenllvmc.exeandclang.exe? Which one do I use for compiling C or C++ code?
|
llvmcis a frontend for various programs in the LLVM toolchain, in particular thellvm-*ones, ie by default it will try to usellvm-gccandllvm-g++to compile C and C++ files.
You can pass-clangtollvmcif that's what you want to use, and it's probably possible to configurellvmcsoclangwill be used by default, but I have no ... |
It seems to me that MCU RAM holds linker values, globally scoped variables, heap, stack, and then some portion is unused.
As a result, do engineers tend to release firmware that leaves some chunk of MCU RAM unused as it is unneeded for the application to work?
|
It depends on the application. In some cases, you might design some unused RAM in order to allow for future patches and growth. In many cases, you would just take whatever is unused and use that to enlarge the heap or stack or some application specific buffers.
|
This came up in a conversation with a friend of my nephew who is home from uni. Personally beside the most frequently used ones I never found it all that important and just use parenthesis. But I don't have to take his exam. Anything clever out there?
EditWell, a rare moment of near unanimity on SO! If only profe... |
I know this probably doesn't help you in the context of your exam, but I'll answer the question for anyone else who might stumble upon this:
Don't try to memorize operator precedence, beyond the "common cases" e.g. arithmetic. If your statement is unclear, either split it into multiple statements or toss in parenthe... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
How about file exchange?http://www.mathworks.com/matlabcentral/fileexchange/20350-16-bit-itu-t-crc
|
Is it possible to write a string on aIplImagewith Opencv 2.1 in C/C++?
Thank you.
|
Yes,cvPutText():
```
CvFont font;
double hScale=1.0;
double vScale=1.0;
int lineWidth=1;
cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth);
cvPutText (img,"My comment",cvPoint(200,400), &font, cvScalar(255,255,0));
```
|
I want to execute a binary within my C code. Which is better to execute with?popen()orsystem()
EDIT: I tried to usesystem, but the process executing seems to get stuck in the end and does not return to my code.
Any suggestions on what to do?
Thanks
|
popen()gives you control over the process's input or output file streams.system()doesn't. If you don't need to access the process's I/O, you can usesystem()for simplicity.
system()is in C89 and C99;popen()is Posix only (though the Windows API also has one).
Both functions invoke some form of ashellto execute the com... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
Which is the bestway to input witho... |
fgets, then remove the'\n'
```
char buf[SOME_VALUE];
size_t blen;
if (fgets(buf, sizeof buf, stdin) == NULL) /* deal with error */;
blen = strlen(buf);
if (blen == 0) /* your system is strange! */;
if (buf[blen - 1] == '\n') buf[--blen] = 0;
else /* fgets "returned" an incomplete line */;
```
|
I can't assign the result of query to variable (the program is written in C). Here is what I do
```
char buffer[100];
while ((row = mysql_fetch_row(res)) != NULL) {
buffer = row[0];
}
```
A get this error during compile process
```
error: incompatible types in assignment
```
What is wrong here ?
|
Assuming it's a string? C doesn't have strings it has arrays of characters. So you have copy the characters from one array to another.
so use a copy function like
```
strncpy(buffer, row[0], 100);
```
|
I try to execute mysql query passing variable. Here is my code
```
char str[100] = "My String";
mysql_query(conn, printf("INSERT INTO table VALUES %s"), str);
```
I get that warning during compile process
```
warning: passing argument 2 of ‘mysql_query’ makes pointer from integer without a cast
```
What I miss ?
|
Extending @ckruse's answer, you should take care to usemysql_real_escape_string()if your string comes from arbitrary sources.
```
int insert_data(MYSQL * mysql, char * str, int len)
{
if (len < 0) {
len = strlen(str);
}
char esc[2*len+1];
unsigned long esclen = mysql_real_escape_string(mysql,... |
I tried to write code usingstrrev(). I included<string.h>but still I'm getting an "undefined reference tostrrev" error.
I found thatstrrev()doesn't have man page at all. Why?
Doesn't Linux supportstrrev()?
|
Correct. Use one of thealternativeimplementations available:
```
#include <string.h>
char *strrev(char *str)
{
char *p1, *p2;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
{
*p1 ^= *p2;
*p2 ^= *p1;
... |
Using visual studio, is there a way to define all the function of the winapi to treat all the strings as UNICODE?
|
The MS libraries are organized by macros.
Use the name of the API methods without the appende "A" or "W".Wrap your string definitions in _T() macro.
By doing this way defining "_UNICODE" in Preprocessor will build unicode build.
```
CreateFile(_T("C:\out.txt"),GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMA... |
My first programming language learned was Actionscript, and I'm having a hard time understanding pointers and references.
What is the purpose of pointers when I can just use references? I read one use case for pointers is when giving a large variable to another function instead of copying it, but can't I just add a &... |
There is no difference in a pointer and the &-Construction. A pointer is a variable which stores the value of &...
```
int a;
int *b = &a;
```
|
I am trying to port tcmalloc to uclibc. Tcmalloc has a definition for sbrk function, which in turn calls the __sbrk from libc. Uclibc on the other hand does not have __sbrk function, but has sbrk.
Any ideas about how I can call uclibc sbrk from tcmalloc sbrk?
|
sbrkis a (old)system call, but most memory allocators are built abovemmap. See alsothis question
You should use the syscall, not emulate it. And I would prefer usingmmap, notsbrk
Doing a system call (usuallymmap) is the only way to get more memory from thelinux kernel.
From the application's (or library's) point of... |
ERRORS:
1) _counter already defined error
2) one or more multiply defined symbols found
structure.h:
```
extern int counter = 0;
```
List.c:
in one method i increment the counter.
```
++counter;
```
in another method i set the counter to a value within an object
llist->taskID = counter;
Messages.c:
use count... |
Your header filestructure.hshould only have a declaration (not a definition), like:
```
extern int counter;
```
One (only) of the implementation files, conventionally the*.cfile containingmain, should have a definition like
```
int counter = 0;
```
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
How to use decimal point covert t... |
Use printf with some good filters. Please see this example:
http://stahlforce.com/dev/index.php?tool=csc02
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Double Negation in C++ code
While reading one code I read:
```
flush = ! !(flags & GST_SEEK_FLAG_FLUSH);
```
I am not getting what does!!mean here .
what does this sentence do?
EDIT:
I got it its adouble-negative.trick to convert non-b... |
It's a double-negative. It's a way of converting an otherwise-non-bool expression (such asflags & GST_SEEK_FLAG_FLUSH) to abool. I personally prefer:
flush = (flags & GST_SEEK_FLAG_FLUSH) != 0;
|
I have link list whose node structure is given below
```
struct node
{
char *p;
struct node *next;
}*start;
```
Now we char *p is pointer to memory location which allocated by malloc call.Similarly the whole is also allocated using malloc. Now would like to free the space occupied by both the malloc call ,s... |
This is the right way but don't forget to assign pointers to NULL after using free otherwise the pointers will become dangling pointers.
Use them like this -
free(tmp->p);
tmp->p = NULL;
|
I have a function as such:
```
int foo(void *val){
(char *)val="Long String";
return 0;
}
```
This function is called like:
```
char str[25];
foo(str);
printf("%s",str);
```
I get nothing printed out for some reason. what is wrong here?
|
You are not actually copying the data around like you think you are. All you are doing is changing the parameter value to point at a different memory address. The parameter is being passed by value, so any change to it is not reflected in the calling code. For what you are attempting, you need to usestrcpy()orstrnc... |
Through GDB I have determined that the segfault is occuring somewhere in this block of code.
```
readInfo(fd)
int fd;
{
char str[200];
while(readInfo(fd,str))
printf("%s\n",str);
}
```
What this code is trying to accomplish is to read information sent to it by a server. I'm not quite sure what the problem... |
I have three tips:
Compile the program with debugging symbols. That way you can see the actual code that you are crashing on, as well as print variable values even after the crash.Write two functions - the non-recursive version and the recursive version. This isn't always necessary, but since you're adding a paramete... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.