question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
What is the difference between theSPIandI²Cprotocols, used to program a microcontroller?
... |
SPI and I²C are bus protocols, and each is well defined:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bushttp://en.wikipedia.org/wiki/I2c
They are very similar in how they work, but they aren't the same and the differences aren't minor.
Depending on the microcontroller, they may have either, both, multi... |
I have a variablesof typesize_tand a variablebufferof typeunsigned char. I wish to save this variable inbufferin network order as 4 bytes.
How can I do it?
|
```
char c8[8] = {0};
size_t s = 0x1233456789abcdef0, s_be = 0;
if (4 == sizeof(s))
{
s_be = htonl(s);
}
else if (8 == sizeof(s))
{
s_be = htobe64(s);
}
else
{
assert(0);
}
memcpy(c8, &s_be, sizeof(s_be));
```
Forhtobe64()have a look here:https://stackoverflow.com/a/4410728/694576
|
I have an active running process on Linux/FreeBSD. I have traced it, and found that one of the threads is blocked on the call to the functionwrite()- as an argument it has a TCP socket. It's may be hanging for hours.
What are the ways to examine the reasons behind the blockedwrite()? What are the potential problems?
... |
In my current case there was the following problem. The DNS resolution gave me some IP-address, that was far-far away, or even unreachable. Thewrite()was hanging because no TCP response was ever received from that host.
The problem is solved by setting timeout on send operations viasetsockoptandSO_SNDTIMEO.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I'm writing postgres backend extension in C. I would like to store configuration of my extension inside dat... |
Configuration for extensions is solved via custom configuration variables usually - good example is auto_explain extensions (inside PostgreSQL contrib). If you need a access to database storage, then you should to use a SPI API - Stored Procedure Interface.
https://github.com/postgres/postgres/tree/master/contrib/aut... |
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question
I do: open start menu, run, nameofserver, then I get this:
How to pass two strings (user... |
Maybe:
enumerate the windows on the systemfind the one with the text "Windows Security"find it's children's HWND and search for the text fieldsSetWindowText (HWND, etc ... )Send a message to the "Ok" button
Tell us if it works or not ...
|
This question already has answers here:strtok segmentation fault(8 answers)Closed9 years ago.
I get segmentation fault with the following code usingstrtok. Am I usingstrtokcorrectly?
```
int main()
{
dummy("90:90");
return 0;
}
int dummy(char *str)
{
char *mm, *hh;
int len = strlen(str), result;
... |
strtokmodified the content of its argument, so you can't pass a string literal. Change it to:
```
int main()
{
char str[] = "90:90";
dummy(str);
return 0;
}
```
|
Suppose I have a struct:
```
struct b {
unsigned short num;
unsigned short size;
unsigned char *a;
};
```
I then declare a pointer that points to astructofb:
```
struct b *foo=malloc(sizeof(struct b));
```
how do I allocate memory forfoo'saand assignato point to a character string?
|
It's not that different, e.g, to allocate the memory for the stringhello:
```
char *hello = "hello";
foo->a = malloc(strlen(hello) + 1);
strcpy(foo->a, hello);
```
|
If I have an instruction:
```
imull $eax, $ecx
```
so that it is multiplying what is stored in the two registers, where is the answer stored?
|
Different assemblers work differently. For the GNU Assembler the result will go in$ecx. This is the opposite convention from most windows assemblers.
|
This is my scenario.
```
struct X {
char A[10];
int foo;
};
struct X *x;
char B[10]; // some content in it.
x = malloc(sizeof(struct X));
```
To copy contents fromBtoA, why is the following syntax correct:
```
memcpy(x->A, B, sizeof(x->A));
```
Herex->Ais treated as a pointer, so we don't need&. But then we should... |
Ais NOT a pointer, it's an array. Sosizeof(x->A)is the correct syntax, it's the size of the whole array, i.e,10.
It's true that in many situations, an array name is converted to a pointer to the first element. Butsizeof(arrayname)is NOT one of them.
|
I came across these two statements in a SNS photo album, with the title "the most elegant way of output I ever met" or something.
Here are the two statements:
```
printf("%d%c", a, " \n"[i==n]);
puts("YES\0No"+condition * 4);
```
I've no idea what they are doing and how they work. Will someone explain to me? Thank ... |
" \n"[i==n]takes the expressioni==n, which evaluates to either 0 or 1, and uses it as an index into the array" \n", obtaining either' 'or'\n'.
"YES\0N0"+condition * 4takes the array"YES\0N0", which 'decays' to a pointer to its first element when used in most expressions, including this one, and addscondition * 4to th... |
This question already has answers here:Why whole structure can not be compared in C, yet it can be copied?(6 answers)Closed9 years ago.
Code 1:
```
struct demo
{
int a;
}d[2];
int main()
{
d[0].a=5;
d[1]=d[0];
return 0;
}
```
This code works fine
Code 2:
```
struct demo
{
int a;
}d[2];
int m... |
C has no support for struct comparison. You have to compare the struct yourself by comparing all members one by one.
How do you compare structs for equality in C?
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
I'm not aware of any C client for Cassandra. There is aC++ library that supports the new CQL3 binary protocol, but it doesn't look like it has C externs.
|
Is there a way in Visual Studio 2013 to outline (in red) undeclared C functions?
It seems that by default VS2013 considers that each unknown function is implicit.
Thanks
|
Microsoft Visual Studio is notoriously bad at the modern C standards, and is pretty much stuck at C89. The 2013 versionimproved on this a bit, but nothing much.
I believe it indeed still takes undeclared functions to implicitly returnint. The IDE just follows the compiler in this regard (which it should...).
What yo... |
xisint.
I thinkx==(int)(float)xis always true,but the book says it false whenxisTMax.
I've checked it whenx=TMax,it's still true. The book is wrong?
|
AssumingIEEE-754is used, the single precisionfloatcan represent integers accurately only within 224, butintis normally 32-bit in modern computer, the integers outside the range may not be cast back with(int)(float)x
Ifdoubleis used instead offloat,x == (int)(double)xis true for all 32-bit integers, becausedoublecan r... |
In C#, we learned that function overloading occurs when more than one function have the same identifier but different signature.
Although the concept of function overloading is specific to object-oriented languages, is it applicable to the C language as well on the basis of the following observation?
```
printf("%d"... |
No printf is not overloaded. There is no function overloading or any other object oriented goodness in C.
The way printf works is by using argument list. Take a look at this articlehttp://www.cprogramming.com/tutorial/c/lesson17.html
|
An existing code of mine makes use of some thread specific keys. I intend to scale this code now which requires creating more and more such keys. But pthread supports around 1024 keys per process due to which keys are not created after this limit which creates a problem for me. Any suggestions on how best same functio... |
UseThread-Local storage:
```
#define KEYS_MAXIMUM 2048
__thread void * keys[KEYS_MAXIMUM];
```
To allow destructors you might use:
```
typedef struct
{
void * p;
void (*f) (void *);
} Key
__thread Key * keys[KEYS_MAXIMUM];
```
All that is missing here is some wrappers mimicing thepthread_key*API.
|
How can one implement a means to supply unique ints to be used as a hash key for a hash table of structs without resorting to a global variable?
Note there may be several hash tables but each constituent struct must have a unique key acrossallhash tables as the tables can be merged together
maybe I should just use a... |
In some cases global variables are useful.
In this case, if you have multiple threads you may want to make itstatic(code file restricted) and access it through functions that do proper mutex locking.
|
I'm trying to insert int as value togtree, which comes fromglib. I don't how should I assign and insert it. Here you can see what I have tried:
```
void readFilec(GTree *tree)
{
FILE *fp = fopen("cfg/file.csv", "rb" );
char * line = NULL;
size_t len = 0;
ssize_t read;
if (fp == NULL)
exit(EXIT_FAILURE);
... |
Try to remove the * after gpointer, as it already is a void* and add '&' in front of p2 to get its adress.
```
g_tree_insert(tree, (gpointer) g_strdup(p1), (gpointer) &p2);
```
|
How can I compile it on a 32-bit system so it can run as backward compatible under a 64-bit system? I know it can be done because Adobe, Dropbox and other companies have such binaries. How should I link them, dynamically, statically? Static only some libraries and other dynamic?
I'm talking about a simple code like:
... |
Normally. Then install the 32-bit libraries on the 64-bit system.
|
I'm dealing with an char[] containing text which should represent a double number value OR a long number.I'm in a need to write a function that detects which of the above data-types is represented (if any).
I thought about using strtol() and check if it fails to parse the entire string, and if it fails, using strtod(... |
I thought about using strtol() and check if it fails to parse the entire string, and if it fails, using strtod().
I think that's a good idea and I don't think there is a better one. Implementing your own parsing routine is generally a bad idea.
I would trim the string from trailing whitespace before callingstrtolto ... |
I have a simple question if anyone can answer it. I'm currently starting off with Ubuntu and am learning the environment though I'm use to using Windows. On Windows if I wanted to create and write to a file I would do:
```
FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");
fclose(fp);
```
When usi... |
```
FILE *fp = NULL;
fp = fopen("c:\\test.txt", "w");
if( fp != NULL ){
fprintf(fp, "Testing...\n");
fclose(fp);
} else{
perror("Could not open the file");
}
```
Error checking should always be done and pointers should not be left uninitialized.
|
Hey guys I have been all over the internet and cannot seem to find a simple answer to this. What I want to do is let the user enter how many bytes they want to read (let's call it byteAmount). I want to open a file and read that many bytes from said file, then print it to console using printf. There has got to be an e... |
Seefreadhttp://www.cplusplus.com/reference/cstdio/fread/
This lets you request n bytes of size m from a file stream.
|
This question already has answers here:Why whole structure can not be compared in C, yet it can be copied?(6 answers)Closed9 years ago.
Code 1:
```
struct demo
{
int a;
}d[2];
int main()
{
d[0].a=5;
d[1]=d[0];
return 0;
}
```
This code works fine
Code 2:
```
struct demo
{
int a;
}d[2];
int m... |
C has no support for struct comparison. You have to compare the struct yourself by comparing all members one by one.
How do you compare structs for equality in C?
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
I'm not aware of any C client for Cassandra. There is aC++ library that supports the new CQL3 binary protocol, but it doesn't look like it has C externs.
|
Is there a way in Visual Studio 2013 to outline (in red) undeclared C functions?
It seems that by default VS2013 considers that each unknown function is implicit.
Thanks
|
Microsoft Visual Studio is notoriously bad at the modern C standards, and is pretty much stuck at C89. The 2013 versionimproved on this a bit, but nothing much.
I believe it indeed still takes undeclared functions to implicitly returnint. The IDE just follows the compiler in this regard (which it should...).
What yo... |
xisint.
I thinkx==(int)(float)xis always true,but the book says it false whenxisTMax.
I've checked it whenx=TMax,it's still true. The book is wrong?
|
AssumingIEEE-754is used, the single precisionfloatcan represent integers accurately only within 224, butintis normally 32-bit in modern computer, the integers outside the range may not be cast back with(int)(float)x
Ifdoubleis used instead offloat,x == (int)(double)xis true for all 32-bit integers, becausedoublecan r... |
In C#, we learned that function overloading occurs when more than one function have the same identifier but different signature.
Although the concept of function overloading is specific to object-oriented languages, is it applicable to the C language as well on the basis of the following observation?
```
printf("%d"... |
No printf is not overloaded. There is no function overloading or any other object oriented goodness in C.
The way printf works is by using argument list. Take a look at this articlehttp://www.cprogramming.com/tutorial/c/lesson17.html
|
An existing code of mine makes use of some thread specific keys. I intend to scale this code now which requires creating more and more such keys. But pthread supports around 1024 keys per process due to which keys are not created after this limit which creates a problem for me. Any suggestions on how best same functio... |
UseThread-Local storage:
```
#define KEYS_MAXIMUM 2048
__thread void * keys[KEYS_MAXIMUM];
```
To allow destructors you might use:
```
typedef struct
{
void * p;
void (*f) (void *);
} Key
__thread Key * keys[KEYS_MAXIMUM];
```
All that is missing here is some wrappers mimicing thepthread_key*API.
|
How can one implement a means to supply unique ints to be used as a hash key for a hash table of structs without resorting to a global variable?
Note there may be several hash tables but each constituent struct must have a unique key acrossallhash tables as the tables can be merged together
maybe I should just use a... |
In some cases global variables are useful.
In this case, if you have multiple threads you may want to make itstatic(code file restricted) and access it through functions that do proper mutex locking.
|
I'm trying to insert int as value togtree, which comes fromglib. I don't how should I assign and insert it. Here you can see what I have tried:
```
void readFilec(GTree *tree)
{
FILE *fp = fopen("cfg/file.csv", "rb" );
char * line = NULL;
size_t len = 0;
ssize_t read;
if (fp == NULL)
exit(EXIT_FAILURE);
... |
Try to remove the * after gpointer, as it already is a void* and add '&' in front of p2 to get its adress.
```
g_tree_insert(tree, (gpointer) g_strdup(p1), (gpointer) &p2);
```
|
How can I compile it on a 32-bit system so it can run as backward compatible under a 64-bit system? I know it can be done because Adobe, Dropbox and other companies have such binaries. How should I link them, dynamically, statically? Static only some libraries and other dynamic?
I'm talking about a simple code like:
... |
Normally. Then install the 32-bit libraries on the 64-bit system.
|
I wrote a code, everything ok, compiles and works without a problem, when I compile it with GCC 4.7.2 the switch-WallI get the following warning:
```
warning: variable ‘tables’ set but not used [-Wunused-but-set-variable]
```
I know is not a problem but why it appears? Look illogical:
```
const unsigned char *table... |
From the compiler perspective, there is no difference of behavior between:
```
const unsigned char *tables;
char *loc = setlocale(LC_ALL, 0);
setlocale(LC_ALL, loc);
tables = pcre_maketables();
```
and
```
char *loc = setlocale(LC_ALL, 0);
setlocale(LC_ALL, loc);
pcre_maketables();
```
The compiler will optimize o... |
I have a question about the following program:
It prints:
dst->val in f1=6dst.val in main=-528993792
I want to fix this program so it will print
dst.val in main=6
How can I do this?
```
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct my_struct myStruct;
struct my_struct
{
int val;
}... |
```
void f1(myStruct *dst){
myStruct *p = f2();
printf("**dst->val in f1=%d\n", p->val);
//dst is the address that was copied on the stack.
dst->val = p->val;//There is no meaning If you do not change the contents.
free(p);
}
```
|
I'm trying to code unicode string serialization to UTF-8 w/o BOM file. For some reason the code below gives wrong output.
```
static void MyWriteFile(HANDLE hFile, PTCHAR pszText, int cchLen, BOOL bAsUnicode)
{
DWORD dwBytes;
size_t utf8len = WideCharToMultiByte(CP_UTF8, 0, pszText, -1, NULL, 0, NULL, NULL);
PC... |
```
WideCharToMultiByte(CP_UTF8, 0, pszText, utf8len, pszConverted, utf8len, 0, 0);
```
The fourth parameter ofWideCharToMultiByte(cchWideChar) is the size of the input string. You should leave that to -1 as it is null terminated. Otherwise your output buffer is probably not large enough, and it will contain too much... |
I'm trying to convert the line below to C#. Dik and eint and ratio are variables. I'm unsure how to represent &a in c# and modf if I can get guidance please and thank you.
```
(void) modf (ratio * (dik / eint), &a);
```
|
I'm unsure how to represent &a in c# and modf if I can get guidance please and thank you.
You can useMath.Truncatein C#:
```
double a = Math.Truncate(ratio * dik / eint);
```
This will return "the integral part of a specified double-precision floating-point number", which is the same value returned inmodf'sintpartp... |
Code 1:
```
int size;
struct demo
{
int a;
};
int main()
{
scanf("%d",&size);
struct demo d[size];
return 0;
}
```
This code works fine.
Code 2:
```
int size;
struct demo
{
int a;
};
int main()
{
scanf("%d",&size);
return 0;
}
struct demo d[size];
```
This code shows an error:
``... |
In code 2, your array of structs resides in data segment which is by definition
A data segment is a portion of virtual address space of a program,
which contains the global variables and static variables that are
initialized by the programmer.The size of this segment is determined
by the values placed there by ... |
How to split the following string?
```
A.x IN (changeList),
```
changeList has the following value, so that it makes the clause like this:
```
A.x IN (HEXTORAW('1E2956B9266F11DDA85810000000C959'),HEXTORAW
('ADD834AD6A3911DF923C10000000C959'),HEX...........
```
The above IN has more than 1000 values... |
You must write a loop that executes the SQL in chunks with 1000 entries each.
Alternatively you can insert the values into a table and then do a subselect with theINclause, because with a subselect, the limitation of 1000 entries doesn't apply. This limit is only when you use an SQL with an hardcoded value string.
S... |
Why use function prototypes in C? It seems sort of redundant because we already declare the function name, argument types, and return type in the definition. Do the prototypes have to be declared before the function is defined or used for the optimizations?
|
Generally speaking, you don't need to explicitly declare functions because defining them also declares them. Here are two situations where you would need to:
The definition of the function is in an external module.For example, if the function is defined indefiner.c, but you want to call it fromuser.c, you will need t... |
If one has a character array such as
```
char bytes[256] = "10000011011110110010001101000011";
```
I want to unsigned value of this which would be :2205885251
I'm trying to do something along these lines
```
unsigned int arr[256];
for(int i = 0, k=0; i<256; i++, k++)
{
arr[k] = bytes[i]|bytes[i+1]<<8|bytes[i+2]<<... |
```
#include <stdio.h>
char bytes[256] = "10000011011110110010001101000011";
int main(void)
{
unsigned int out;
int i;
for (out = 0, i = 0; i < 32; ++i)
if (bytes[31 - i] == '1')
out |= (1u << i);
printf("%u\n", out);
return 0;
}
```
Output is:
2205885251
|
Code 1:
```
int size;
struct demo
{
int a;
};
int main()
{
scanf("%d",&size);
struct demo d[size];
return 0;
}
```
This code works fine.
Code 2:
```
int size;
struct demo
{
int a;
};
int main()
{
scanf("%d",&size);
return 0;
}
struct demo d[size];
```
This code shows an error:
``... |
In code 2, your array of structs resides in data segment which is by definition
A data segment is a portion of virtual address space of a program,
which contains the global variables and static variables that are
initialized by the programmer.The size of this segment is determined
by the values placed there by ... |
How to split the following string?
```
A.x IN (changeList),
```
changeList has the following value, so that it makes the clause like this:
```
A.x IN (HEXTORAW('1E2956B9266F11DDA85810000000C959'),HEXTORAW
('ADD834AD6A3911DF923C10000000C959'),HEX...........
```
The above IN has more than 1000 values... |
You must write a loop that executes the SQL in chunks with 1000 entries each.
Alternatively you can insert the values into a table and then do a subselect with theINclause, because with a subselect, the limitation of 1000 entries doesn't apply. This limit is only when you use an SQL with an hardcoded value string.
S... |
Why use function prototypes in C? It seems sort of redundant because we already declare the function name, argument types, and return type in the definition. Do the prototypes have to be declared before the function is defined or used for the optimizations?
|
Generally speaking, you don't need to explicitly declare functions because defining them also declares them. Here are two situations where you would need to:
The definition of the function is in an external module.For example, if the function is defined indefiner.c, but you want to call it fromuser.c, you will need t... |
If one has a character array such as
```
char bytes[256] = "10000011011110110010001101000011";
```
I want to unsigned value of this which would be :2205885251
I'm trying to do something along these lines
```
unsigned int arr[256];
for(int i = 0, k=0; i<256; i++, k++)
{
arr[k] = bytes[i]|bytes[i+1]<<8|bytes[i+2]<<... |
```
#include <stdio.h>
char bytes[256] = "10000011011110110010001101000011";
int main(void)
{
unsigned int out;
int i;
for (out = 0, i = 0; i < 32; ++i)
if (bytes[31 - i] == '1')
out |= (1u << i);
printf("%u\n", out);
return 0;
}
```
Output is:
2205885251
|
I have awhileloop that opens (and closes) files in each loop. After some loops I end up in the "Too many open files" problem – but I callcloseeach time after reading the file's content. Could anyone assist me with this?
```
for (;;)
{
dir = opendir( "/proc");
while ( (entry = readdir( dir)) != NULL)
{
... |
Your problem is that you are doing anopendirin the loop, but never doing aclosedir. That will leak an fd on each iteration of the outer loop.
|
This question already has answers here:What is "!!" in C? [duplicate](7 answers)Closed9 years ago.
What are some valid uses for negating twice in C? For example, something like:
```
if (!!my_cond) {
}
```
As I understand, the!!will guarantee that the!!my_condwill be 0 ifmy_condisfalseand 1 otherwise. When would yo... |
It can be used for turning something into a Boolean expression.
Iffoo = !!fooit givesfoo1 if it's not a zero, and leave it at 0 if it already is.
Your question is already answered here :Confused by use of double logical not (!!) operator
|
I have one solution and two projects(server, client) and I want to share wrapper.h/.c between these two.
How may I accomplish this?
I have tried dragging wrapper.h/.c to both projtects without any success.
Update 2
Did as Adrian said, no success yet.
Client and server are depended on wrapper.
Building order: Wra... |
Put the wrapper into its own project, and have the server and client projects depend on it.
|
I am writing a C program, that uses *NIX System calls. Now, when the user calls for deleting a particular file, I want to remove all the symbolic links created to the file, also to be removed. How can this be achieved?
|
You can't, unless you search the whole directory tree, or you have some other means of knowing where these symbolic links are. A file doesn't "know" which symlinks point to it. You have to locate each symlink on your own andunlink()it.
|
I am learning C and getting used to pointers. I was wondering for a simple linked list structure, is this the proper way to delete a list? I was told you have to take care of everything manually (I'm more of a Java guy, but trying to convert). What suggestions or constructive criticism is there for this? Thanks in adv... |
Yes, your code is fine. You might wantdelete_listto take a pointer to the root element as a variable, and you could have written it a little more concisely, e.g.
```
void
delete_list (node *list)
{
while (list)
{
node *tmp = list->next;
free (list);
list = tmp;
}
}
```
|
Is there a programmatically way to limit duration, memory usage and run as less privileged user of a Linux program execution in C/C++ or Ruby ?
since system or `` can't do this.
```
sprintf(cmd_str,"/tmp/pro-%d < /tmp/in.txt > /tmp-%d.txt",id,id);
system(cmd_str); // in C
`/tmp/pro-#{id} < /tmp/in.txt > /tmp/out-#{... |
Useseteuid(2)system call; sets the effective user ID of the calling process.
Following is Ruby example (SeeProcess::Sys.seteuid)
```
Process.uid # => 0
Process.euid # => 0
Process::Sys.seteuid(1000) # Etc::getpwnam('falsetru').uid == 1000
Process.uid # => 0
Process.euid # => 1000
```
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
I saw this code in the book and thought a lot about this.
```
typedef string *qstring;
const qstring cstr
... |
Wellqstringis a typedef ofstring *- a pointer tostring. Theconstinconst qstringapplies to the outermost type ofqstring, so it applies to the pointer, which makescstrhave typestring * const.
|
I have a macro that fetch's the J-th bit of an integer:
```
#define TWO_TO_THE(POWER) (1 << POWER)
#define JTH_BIT(BITS, J) ((TWO_TO_THE((J-1)) & BITS) != 0)
```
However, I can't use it from gdb by issuing the commandprint JTH_BIT(i,j), can macros in C even be used while debugging?
|
Macros are handled by the pre-processor. The compiler doesn't even know about them.
However, if lucky, GCC's option-g3would do the job and generate code allowinggdbto expand a macro.
From thegdb documentation(emphasis by me):
-glevel[...]
Level 3 includes extra information, such as all the macro definitions pr... |
I have awhileloop that opens (and closes) files in each loop. After some loops I end up in the "Too many open files" problem – but I callcloseeach time after reading the file's content. Could anyone assist me with this?
```
for (;;)
{
dir = opendir( "/proc");
while ( (entry = readdir( dir)) != NULL)
{
... |
Your problem is that you are doing anopendirin the loop, but never doing aclosedir. That will leak an fd on each iteration of the outer loop.
|
This question already has answers here:What is "!!" in C? [duplicate](7 answers)Closed9 years ago.
What are some valid uses for negating twice in C? For example, something like:
```
if (!!my_cond) {
}
```
As I understand, the!!will guarantee that the!!my_condwill be 0 ifmy_condisfalseand 1 otherwise. When would yo... |
It can be used for turning something into a Boolean expression.
Iffoo = !!fooit givesfoo1 if it's not a zero, and leave it at 0 if it already is.
Your question is already answered here :Confused by use of double logical not (!!) operator
|
I have one solution and two projects(server, client) and I want to share wrapper.h/.c between these two.
How may I accomplish this?
I have tried dragging wrapper.h/.c to both projtects without any success.
Update 2
Did as Adrian said, no success yet.
Client and server are depended on wrapper.
Building order: Wra... |
Put the wrapper into its own project, and have the server and client projects depend on it.
|
I am writing a C program, that uses *NIX System calls. Now, when the user calls for deleting a particular file, I want to remove all the symbolic links created to the file, also to be removed. How can this be achieved?
|
You can't, unless you search the whole directory tree, or you have some other means of knowing where these symbolic links are. A file doesn't "know" which symlinks point to it. You have to locate each symlink on your own andunlink()it.
|
I am learning C and getting used to pointers. I was wondering for a simple linked list structure, is this the proper way to delete a list? I was told you have to take care of everything manually (I'm more of a Java guy, but trying to convert). What suggestions or constructive criticism is there for this? Thanks in adv... |
Yes, your code is fine. You might wantdelete_listto take a pointer to the root element as a variable, and you could have written it a little more concisely, e.g.
```
void
delete_list (node *list)
{
while (list)
{
node *tmp = list->next;
free (list);
list = tmp;
}
}
```
|
Is there a programmatically way to limit duration, memory usage and run as less privileged user of a Linux program execution in C/C++ or Ruby ?
since system or `` can't do this.
```
sprintf(cmd_str,"/tmp/pro-%d < /tmp/in.txt > /tmp-%d.txt",id,id);
system(cmd_str); // in C
`/tmp/pro-#{id} < /tmp/in.txt > /tmp/out-#{... |
Useseteuid(2)system call; sets the effective user ID of the calling process.
Following is Ruby example (SeeProcess::Sys.seteuid)
```
Process.uid # => 0
Process.euid # => 0
Process::Sys.seteuid(1000) # Etc::getpwnam('falsetru').uid == 1000
Process.uid # => 0
Process.euid # => 1000
```
|
I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this
```
for(i=0; i < strlen(s1); i++) {
for(j = 0; j < strlen(s2); j++) {
if(s1[i] == s2[j]) {
count++;
s2[j] = '*';
break;
}
... |
This is very simple. Take twointarraysfreq1andfreq2. Initialize all its elements to0. Then read your strings and store the frequencies of the characters to these arrays. After that compare the arraysfreq1andfreq2to find the common characters.
|
Question asked in oracle interview.For example,if my input is 6, then
5+1=6 Ans:24+2=6 Ans:23+2+1=6 Ans:3
So, the final answer should be 3.(i.e 3,2,1 are needed to get sum 6)
Note:Repetition of number isn't allowed (i.e 1+1+1+1+1+1=6)
I solved it using recursion but interviewer wasn't satisfied. Is Dynamic Pro... |
The minimum sum of x numbers is
So just find x that satisfies the inequality:
Here's the code:
```
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int x = 1;
while ((x+1)*x/2 <= n) x++;
x--; // now (x+1)*x/2 > n , so x is too large
printf("%d\n", x);
return 0;
}
```
You can... |
```
char str2[13];
str2[13] = '\0';
```
Look at the above example, the maximum legal index ofstr2is 12, but in this example 13,str2[13] can also work.
Here's the code snippet:
```
#include<stdio.h>
int main(){
char *str1 = "we are happy!";
char str2[13];
str2[13] = '\0';
printf("Before: %s\n", str2);... |
Accessing an index out of bounds invokesundefined behavior. This means it may do anything including crashing your program ornotcrashing your program. Also it is possible that the code above crashes sometime and works other times. That is why it is calledundefined behavior. It isyourresponsibility never to invoke undef... |
I defined a macro to DbgPrint to prints message when the _DEBUG defined
```
#define MYDBGPRINT(X) #ifdef _DEBUG \
DbgPrint(X) \
#endif
```
but the output is differ from the DbgPrint for example
```
ULONG id=0;
MYDBGPRINT("the value of the id : %u ",id) //outputs garbage
DbgPrint("the value of the id : %u ",id)... |
You are trying to use the pre-processor to create pre-processor definitions. I've never tried that myself, but it seems like a bad idea that probably won't work. Instead try something like:
```
#ifdef _DEBUG
#define MYDBGPRINT(X) DbgPrint(X)
#else
#define MYDBGPRINT(X)
#endif
```
or in the case of having a variable ... |
Can I put#define MY_VAR 1in a file and#define MY_VAR 2in a different file without any problem?
In other words, is#definea local or a global definition?
|
The answer depends on what kind of file you are talking about:
If it is a header file, then your#define-d constant is visible in all files including the headerIf it is a .c/.m/.mm./.cpp file, then#defined constant is limited in scope to the file where it is defined.
|
When I use scanf() to read a string from the keyboard, and the string is declared as
```
char str[ 10 ];
```
, should I use%10sor%9sto properly limit the number of characters input? Thanks in advance.
|
should I use %10s or %9s to properly limit the number of characters input?
You can use but better to usefgetsto read string.
```
fgets(str, 10, stdin);
```
A terminating null character is automatically appended after 9 characters copied tostr.
7.21.7.2 Thefgetsfunction
Synopsis#include <stdio.h>
char *fgets(char ... |
I am working in embedded c, variable x is a sensor data which is an integer (lies between 1 and 100) and i need to output a variable y on lcd as a linear relation of x but after rounding it to closest integer, will this code work? If not then what are other ways of doing the same.
```
int x
float y
int z
x=4 /*say it... |
```
int z = ((x * 3.45) + 3.5) + 0.5; /* assuming x is non-negative */
```
Floating-point to integer is covered by implicit conversion, so you don't need to do it explicitly. But the conversion is a truncate so the extra+0.5gets you to the actual closest integer.
|
This question already has answers here:sprintf buffer sizes(3 answers)Closed9 years ago.
I'm having an issue with sprintf in C resetting the value of a counter variable when I run it. Here in a nutshell is what is happening:
```
int count = 0;
count++;
printf("%d\n", count); // count will equal 1
char title[7];
spri... |
titleis too small, sprintf is writing beyond the bounds oftitle, and writing intocount, corrupting its value.
Note thattitleneeds to be long at least 8 bytes: 3 for%.3d, 4 for.jpgand 1 for the terminator\0.
As Grijesh Chauhan points out, you can make sure that you never write beyond the allocated size of the string ... |
I mean this usage:
```
sprintf_with_start_pos(out_variable, 3, "format_str %s %i etc...", var1, var2);
```
and such function should withheld returning output until it arrives at position 3.
I know I can create this effect making my own buffer and then copy from that, but I wonder if is there in c a one liner for thi... |
test.c:
```
#include <stdio.h>
main() {
char* var1 = "1234567";
char buffer[50];
sprintf(buffer, "%s", &var1[2]);
printf("%s\n", buffer);
printf("%.3s\n", buffer);
}
```
Output:
```
$ gcc test.c
$ ./a.out
34567
345
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question
Is there any alternative for goto statement in c programming.
Actually i am planning to ... |
Separate yourmaininto functions. Instead of jumping to a location insidemain, execute an appropriate function. That might require passing some parameters to the functions but it surely worth it.
|
My program is a multi-thread program written in C, and runs on Solaris.
Now, a variable (malloced in heap) is sometimes changed from a valid value toNULL, so when accessing it, core dump occurs.
I have tried all the methods I know: using libumem, add logs, code walk-through, and nothing can be found.
So when I anal... |
Can I know which thread change the global variable (including malloced from heap)'s value from core dump file?
No.
A core dump records current state of the process memory at crash point, not the history of it. Just as looking at a photo of a spray-painted graffiti on the wall you can't tell who painted it, looking a... |
When I ran this program it gave an output of
1, 4, 4
Why does sizeof('A') gives 4 bytes? Is 'A' treated as integer? If so, then why?
```
#include<stdio.h>
int main()
{
char ch = 'A';
printf("%d, %d, %d", sizeof(ch), sizeof('A'), sizeof(3.14f));
return 0;
}
```
Moreover, when I replace
```
printf("%d, %d, %d", si... |
In C, the type of'A'isint, which explains whysizeof('A')is4(since evidently your platform has 32-bitint). For more information, seeSize of character ('a') in C/C++
When compiled as C++, the first program prints1 1 4.
"A"is a string literal consisting of the letter A followed by the NUL character. Since it's two char... |
How do I determine if there is a difference of 4 hours between two times, given in a 24-hours format?
I've tried this:
```
time_t timeP;
time(&timeP);
//....
time_t nowP;
time(&nowP);
if((nowP - timeP) % 4 == 0){
//...
}
```
Any better idea, please?
|
```
if ((nowP - timeP) % 4 == 0)
```
This code takes the time difference in seconds modulo 4 which probably doesn't have much value to you.
```
if ((nowP - timeP) >= 60*60*4)
```
This would tell you that 4 hours have elapsed between the two time points. You shouldn't use==for comparing times to avoid skipping the t... |
I wrote this simple code to calculate numbers from 1 to 1000 which are multiples of 3 and then store them in an array and then print the array.
```
#include <stdio.h>
void main(void){
int i,x,y;
int A[1000];
for(i=1;i<1000;i++){
x=i%3;
if(x==0){
A[i]=i;
printf("%d\n",A[i])... |
Since the only place you set the value of an array entry is at:
```
A[i]=i;
```
and i starts at 1 and is not set back in any way, the first entry to be set will of course beA[1].
|
Can I put#define MY_VAR 1in a file and#define MY_VAR 2in a different file without any problem?
In other words, is#definea local or a global definition?
|
The answer depends on what kind of file you are talking about:
If it is a header file, then your#define-d constant is visible in all files including the headerIf it is a .c/.m/.mm./.cpp file, then#defined constant is limited in scope to the file where it is defined.
|
When I use scanf() to read a string from the keyboard, and the string is declared as
```
char str[ 10 ];
```
, should I use%10sor%9sto properly limit the number of characters input? Thanks in advance.
|
should I use %10s or %9s to properly limit the number of characters input?
You can use but better to usefgetsto read string.
```
fgets(str, 10, stdin);
```
A terminating null character is automatically appended after 9 characters copied tostr.
7.21.7.2 Thefgetsfunction
Synopsis#include <stdio.h>
char *fgets(char ... |
I am working in embedded c, variable x is a sensor data which is an integer (lies between 1 and 100) and i need to output a variable y on lcd as a linear relation of x but after rounding it to closest integer, will this code work? If not then what are other ways of doing the same.
```
int x
float y
int z
x=4 /*say it... |
```
int z = ((x * 3.45) + 3.5) + 0.5; /* assuming x is non-negative */
```
Floating-point to integer is covered by implicit conversion, so you don't need to do it explicitly. But the conversion is a truncate so the extra+0.5gets you to the actual closest integer.
|
This question already has answers here:sprintf buffer sizes(3 answers)Closed9 years ago.
I'm having an issue with sprintf in C resetting the value of a counter variable when I run it. Here in a nutshell is what is happening:
```
int count = 0;
count++;
printf("%d\n", count); // count will equal 1
char title[7];
spri... |
titleis too small, sprintf is writing beyond the bounds oftitle, and writing intocount, corrupting its value.
Note thattitleneeds to be long at least 8 bytes: 3 for%.3d, 4 for.jpgand 1 for the terminator\0.
As Grijesh Chauhan points out, you can make sure that you never write beyond the allocated size of the string ... |
My compiler gives this warning:
inlinedata.h:9:6: note: expected ‘char *’ but argument is of type ‘const char *’
```
int inline_data_receive(char *data,int length);
```
I don't understand why it claims 'data' is a const pointer when it is not written as a const char*.
|
It's saying that theargument(the data that you are passing in) isconst. It might be a string literal, for example. So instead of doing this:
```
ret = inline_data_receive("hello", len);
```
do this
```
char str[] = "hello";
ret = inline_data_receive(str, len);
```
You need to do it this way since the function is n... |
I have a java Service and i am calling it from my C program . I generated stubs using GSOAP and when i call the service i get the error message as :
```
Error -21 in function "SOAPDataAdapter::getFieldValueFromXSDElement (XSD -> Dataset conversion)": Feature "12xsd__anyType" is not supported
N5vasco20InvalidDataExcep... |
I was able to view the SOAP message using WIreShark
|
According to Autosar_SWS the boolean must beunsigned char.
But I am having lots of MISRA violation in my compositions, like MISRA rule 10.1 (conversion violation), Rule 12.6 (effective boolean).
I would like to know if I redefine the BOOLEAN for my application like below:
```
#ifdefine BOOLEAN_T
#undefine BOOLEAN_T... |
If you use a 2 bit struct to represent a single bit quantity, a random bit flip has a 50% chance of changing the true/false value to a value that is neither true nor false.
Pleasespend some more time studying the C language before attempting to write safety critical software.
|
Can a child process generated byfork()ever have a process id lesser than its parent(without crossing the maximum limit)?
The PID is usually the next available value but anyhow can it possibly be less than the parent's PID?
|
Yes. PIDs are not guaranteed to be in any order. Some systems and some security extensions generate random PIDs to avoid attacks based on child PID prediction. Of course even systems that linearly generate PIDs need to wrap around at some point.
|
I have a java Service and i am calling it from my C program . I generated stubs using GSOAP and when i call the service i get the error message as :
```
Error -21 in function "SOAPDataAdapter::getFieldValueFromXSDElement (XSD -> Dataset conversion)": Feature "12xsd__anyType" is not supported
N5vasco20InvalidDataExcep... |
I was able to view the SOAP message using WIreShark
|
According to Autosar_SWS the boolean must beunsigned char.
But I am having lots of MISRA violation in my compositions, like MISRA rule 10.1 (conversion violation), Rule 12.6 (effective boolean).
I would like to know if I redefine the BOOLEAN for my application like below:
```
#ifdefine BOOLEAN_T
#undefine BOOLEAN_T... |
If you use a 2 bit struct to represent a single bit quantity, a random bit flip has a 50% chance of changing the true/false value to a value that is neither true nor false.
Pleasespend some more time studying the C language before attempting to write safety critical software.
|
Can a child process generated byfork()ever have a process id lesser than its parent(without crossing the maximum limit)?
The PID is usually the next available value but anyhow can it possibly be less than the parent's PID?
|
Yes. PIDs are not guaranteed to be in any order. Some systems and some security extensions generate random PIDs to avoid attacks based on child PID prediction. Of course even systems that linearly generate PIDs need to wrap around at some point.
|
when i'm tryin' to use malloc with string pointers to scan, it's givin' a segmentation fault
```
main(){
char *a;
a = (char)malloc(50);
printf("enter a string\t");
scanf("%s", a);
printf("%s\n", a);
}
```
|
```
a = (char)malloc(50);
```
Here, you meant to cast its type tochar *instead ofchar.
Note that it's better not to cast the return type ofmalloc. SeeDo I cast the result of malloc?
|
For example having string:
```
Hello World!
```
How to make strcopy function working from position 6 and copy onlyWorld!to another buffer ?
|
```
char source[] = "Hello World!";
char destination[7]; // 7 = strlen("World!") + 1
strcpy(destination, source + 6);
```
|
This for loop works even though the condition is given is as justt.
How is this possible when its not even a valid condition?
Are there many other exceptions like this ?
```
for (t=10; t; --t) {
printf("%d",t);
}
```
|
How is this possible when its not even a valid condition. Are there many other exceptions like this ?
This is possible and valid condition.The second sub-expressiontin the for loop is to check whethertis equal to0or not. It is equivalent to
```
for (t=10; t != 0 ; --t) {...}
```
|
I know basics of c/c++
recently, I have been through a rather strange looking assignment
```
int a=1,b=2,c=5;
int x = (a,b,c);
```
oddly enough, value of x is 5.honestly, i would have searched Google if only i knew what this assignment operation is called.any help ?
|
,in second statement is called comma operator. It evaluates from left to right and the value of the last operand (sub-expression) will become the value of the entire expression. In case
```
int x = (a,b,c);
```
ais evaluated first, its value is discarded thenbis evaluated and its value discarded then finallycis eval... |
Is there a way to grow an array in C, but only if the memory can be grown in place (That is, fail to grow if the pointer needs to be changed)?
|
In standard C there is no function capable of doing that.
|
I am writing a bit of C code in which I am presented with following things:
```
typedef uint8_t BYTE;
typedef int8_t SBYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;
typedef uint64_t QWORD;
```
I have a function having definition asQWORD exp_d(const DWORD *in).
And I have a pointer to a QWORD asQWORD* input. B... |
Use the numeric value, if the type of the input isQWORD:
```
(uint32_t) ((*input) & 0xffffffff)
```
|
What is the conversion code (%) in C-programming called?
I've been trying to find the actual name and not just "the percent sign/symbol."
Wish I could accept more than just one answer. Thanks again guys!
|
The character is called the “percent sign”.I do not believe it has another name, the way a slash does (“solidus”).
The C standard does not use any name for it; it uses the character to speak for itself:
C 2011 (N1570) 6.5.5 5 says “… the result of the%operator is the remainder.”
C 2011 (N1570) 7.21.6 4 says “Each c... |
I have to get name server IP of my system using C language.I am using Linux machine.
I have tried.
```
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/cdefs.h>
int main()
{
int res_init(void);
printf("_res.nscount ... |
You declared res_init() instead of calling it. Try:
```
Int main()
{
res_init();
/* ... */
```
However, nsaddr_list[0] isn't a string, so you won't be able to print it with printf("%s"). You'll have to use inet_ntoa() or similar to convert its sin_addr.s_addr value to a printable string.
|
I'm looking for a control structure to deal with potentially multiple blocks of code or aNONEblock.
The most basic case is when there are only two conditions,AandB:
```
+-------+-------+------------+
| A | B | Blocks Run |
+-------+-------+------------+
| false | false | C |
| false | true | B ... |
If it's all about minimising comparsions using a table is the only way to go.
```
switch ((B << 1) | A)
{
case 0:
// C
break;
case 0b01: // case 1:
// A
break;
case 0b10: // case 2:
// B
break;
case 0b11: // case 3:
// A
// B
break;
default:
// Shouldn't arrive he... |
I mean case like this (this is of course false code /idea only/ as I know it doesn't work like that):
```
int main() {
int my_int = 42;
#ifdef my_int
my_int = 43;
#else
int my_int = 43;
}
```
I know that c/c++ program cannot see the names of the variables and cannot tell if it was set or not but compil... |
No. The only thing that can happen when you have duplicate declarations, is a compiler error. It's always ill-formed. And because the pre-processor has no knowledge of variables, you can't use that either.
|
In thegetpagesize()man page, It 's written that "The function getpagesize() returns the number of bytes in a memory page, where "page" is a fixed-length block, the unit for memory allocation".
Does it mean that if wemalloc(10), malloc() allocates10 * getpagesize()?
Moreover, if I do a simple program thatmalloc(1)... |
No, the unit of allocation formallocis bytes. The page size is used for memory functions that want page aligned memory or work on units of pages.mmapis one such memory function that has "page" requirements for some of its uses.
|
I am trying to make the program print out "OK" for as long as i enter 'y' as a choice at the end, but it is not looping, it just prints out "OK" and ends the program even if i enter a 'y' at the end. Please help.
```
#include <stdio.h>
int main()
{
char c = 'y';
while (c == 'y')
{
printf_s("OK\n")... |
On first iteration when you pressEnterkey then a newline character\nis passed to the input along withy. On second iterationscanf_sreads\n.
Change
```
scanf_s("%c", &c);
```
to
```
scanf_s(" %c", &c);
^Notice the space before %c
```
A space before%cspecifier can consume any number of white-space characte... |
```
struct MixedData
{
char Data1;
short Data2;
short Data3;
double Data4;
int Data5;
double Data6;
};
```
The abovestructwill be automatically 'padded'. But I do not understand how 'padding' is beneficial.
|
Because most platforms suffer a performance penalty when reading unaligned data. For example, a 64 bit wide memory controller can read adoublein one "cycle" as long as it is aligned properly, if not, it will take 2 cycles to read it and load the MC unnecessarily. Some platforms cannot even read unaligned data. That is... |
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve... |
Your code is written in C but you are usingnew; a C++ operator. Usemallocinstead.
```
int *arr = malloc(sizeof(int)*N); // allocates memory for N itegers
```
|
Hey folks ive come across another problem.
Im trying to do a bubble sort and a selection sort ive got my selection sort working.
But im having trouble with my bubble sort.Here it is.
```
void sortBubble(int nRow, char sArr[5][10], char sArrTemp[10]) {
int nSwaps=0;
while(nSwaps==1) {
nSwaps=0;
... |
You never enter the loop because of
```
int nSwaps=0;
```
Also, you should consider using another algorithm for sorting.
I would recommendqsort
|
i am trying to develop a transpose function which can transpose from decimal to binary an up to 9digits number. I'm pretty new on coding and this is my first try. But it does not seem to be working, sorry if i am asking something obvious, but i need some help. Thanks in advance.
```
void transpose(int n)
{
int c, k;... |
Instead of using arithmetic operations, you could use bitwise operations and get the digit directly:
```
for (c = 31; c >= 0; --c)
{
printf("%d", (n >> c) & 1);
}
```
This shifts the value innright bycsteps, i.e. putting bit numbercin the rightmost (least-signigficant) bit. Then the mask with1will result in eith... |
This question already has answers here:Will C++ exceptions safely propagate through C code?(6 answers)What happens if exception gets thrown "through" c code? [duplicate](5 answers)Closed9 years ago.
I'm writing a shared library with a C API, but most code is written in C++.
In some places I want to throw exceptions, ... |
Not a good idea. You'll be sure to leak memory.
A sensible alternative is for you to have a catch site within your C++ library which populates a thread specific error information object and refactor each interface function to have a return status code to signify that an error has been generated. (Cf. Microsoft's Comp... |
I'm trying to use this function to remove a value from the front of a queue. It seems to work the first time (though I might be wrong about this) but when freeing a node the second time it triggers a breakpoint which crashes the program. How do I fix this?
```
printf("Value removed = %d\n", dequeue(myQueue));
int de... |
You updates a local variable, instead updatingheadin your queue structureq:
```
head = temp->next; // this is local variable
```
should be:
```
q->head = temp->next;
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.