question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I have a dynamically allocated array of structs.
I want to cast it to an array type so my debugger will show the whole array.
Is it possible?
I know that this cast is not a good idea, but it's only a cast for expression evaluation of the debugger. –
|
I want to cast it to an array type so my debugger will show the whole
array. Is it possible?
Yes. For example, if you allocated array of 100 elements of typet_my_structthen cast pointer tot_my_struct=> pointer to array of 100 elements of typet_my_struct:
```
t_my_struct * Dynamic = ( t_my_struct * )calloc( 100, size... |
I have the following code:
```
int number;
char temp[32] = "";
number = snprintf(temp, sizeof(char), "%c", 'A');
```
I made this variablenumberbecausesnprintfhas a return value, number can remove the warning of"ignore of return value of snprintf", then it gets another lint warning:Warning 550: Symbol 'number' not ... |
In this case number receives the bytes printed bysnprintfand lint is warning about a non used variable, you can skip this lint warning with
number = snprintf(temp, sizeof(char), "%c", 'A'); /* lint -save -e550 */
or as others says
```
(void)snprintf(temp, sizeof(char), "%c", 'A');
```
|
There is a task to build some sort of a dictionary for
list of suffixes, for an instance:
```
[., .com., a.com., a.b.com., org., some.org., ...]
```
and for each incoming string, for an instance "test.some.org." find the longest suffix in the built dictionary. There are some memory limitations. What is the most pro... |
For an immutable set of string, thecompressed trieworks very well. The main idea is to represent a single branch in the trie as one node. There are many useful descriptions/papers of this method in the web.
|
I was wondering what the most suitable tool is for extracting c (and eventually c++) function names, arguments and their types from source code. I would like to use a tool that can be automated as much as possible.
I want to extract the signature types then have the output read by another program written in Erlang. M... |
Surely there is something better, but if you don't find it:
```
gcc -aux-info output demo.c
sed '/include/d' output
```
Extracts functions form source code skipping standard functions
|
I need to create user timer and thread in windows kernel program. Anyone please give a clue that if the regular threading headers are applicable in this mode?
|
You need to look into KMDF or WDM if you are using some old drivers.
For timers see this:
http://msdn.microsoft.com/en-us/library/windows/hardware/ff550050(v=vs.85).aspx
And here are threads or work items:
http://msdn.microsoft.com/en-us/library/windows/hardware/ff551203(v=vs.85).aspx
|
This question already has answers here:Use sed to replace all backslashes with forward slashes(9 answers)Closed10 years ago.
I am porting my C programs from Windows to Linux. The problem is that Linux (Unix-like) does not recognize\as directory separator, sayshere. So I have to substitute\to/in all my#includestatemen... |
Try this command invim:
```
:g/#include/s@\\@/@g
```
You can also usesed:
```
$ sed -i '/#include/s@\\@/@g' code.c
```
If you want to substitute multiple files:
```
$ vim *.c
:argdo your_command | update
```
Or
```
$ sed -i your_command *.c
```
Or
```
$ find . -name '*.c' -exec sed -i your_command {} \;
```... |
How can I resize the Windows console window in C?
|
Alright, after much deliberation, I got the code working.
Using this include:
```
#include <windows.h>
```
This struct:
```
struct SMALL_RECT {
SHORT Left;
SHORT Top;
SHORT Right;
SHORT Bottom;
};
```
And this function:
```
void adjustWindowSize()
{
struct SMALL_RECT test;
HANDLE hStdou... |
How do you block until the request response finished in libcurl? I need to block becauseCURLOPT_WRITEFUNCTIONasynchronously writesto the C-String; so I need to be sure that I can get the full output from a request before I act on the data.
|
I fixed this by making the callback function returnreturn nmemb*size;
See here for more info:http://curl.haxx.se/mail/lib-2002-12/0065.html
```
char *array;
int arraySize = 0;
size_t storeContent(char *ptr, size_t size, size_t nmemb, void *userdata) {
int thisSize = nmemb * size;
arraySize += thisSize;
array... |
How to do transpose for tptrs in blas?
I want to solve:
```
XA = B
```
But it seems that tptrs only lets me solve:
```
AX = B
```
Or, using the 'transpose' flag, in tptrs:
```
A'X = B
```
which, rearranging is:
```
(A'X)' = B'
X'A = B'
```
So, I can use it to solve XA = B, but I have to first transpose B manu... |
TPTRS isn't a BLAS routine; it's an LAPACK routine.
If A is relatively small compared to B and X, then a good option to unpack it into a "normal" triangular matrix and use the BLAS routine TRSM which takes a "side" argument allowing you to specify XA = B. If A is mxm and B is nxm, the unpacking adds m^2 operations wh... |
This question already has answers here:Since I can't return a local variable, what's the best way to return a string from a C or C++ function?(8 answers)Closed10 years ago.
I have a main function that has to receive a string.
```
main()
{
char *c = fun();
}
char* fun()
{
char a[] = "hello";
return a;
}
... |
You return a pointer to a local variable. The variable is stack-allocated, and it is destroyed when the function exits. Using such pointer is undefined behaviour.
|
I have to save how many letters, numbers, whitespaces and lines there are in a string:
```
char string[2048];
...
string = "aaa 111\nsas 23 d\nds";
for(i = 0; i < strlen(string); i++){
if (isdigit(string[i]) != 0){
numbers++;
} else if (isascii(string[i]) != 0){
letters++;
} ...
}
```
It ... |
Try,
```
char string[2048];
strcpy(string,"aaa 111\nsas 23 d\nds");
```
or
```
char string[2048] = "aaa 111\nsas 23 d\nds";
```
Instead of
```
char string[2048];
string = "aaa 111\nsas 23 d\nds";
```
|
I have a text file in UTF-8 that I need to navigate in C. I need to split this file into seperate smaller files (i.e. cut it in half). When this happens, it sometimes splits the multi-byte characters into two different files. When a dumb text editor goes to read the file containing the second half of text, it reads th... |
```
if ((*s & 0xc0) == 0x80) /* You are in the middle of */;
```
|
Is it possible to configure clang to read the compiler flags from a file. Is there any flag like:
```
clang++ test.cpp -flags=flags-file
```
Such thatclangreads the compiler flags fromflags-file.
|
Apparently there is support for reading commands from a file in clang as well as in gcc. The usage is something like:
```
clang++ test.cpp @file
```
The compiler will read the command line flags fromfile.
I could find a link for gcc.https://developer.apple.com/library/mac/documentation/darwin/reference/manpages/man... |
```
int* func(int *ptr)
{
static int a = 5;
ptr = &a;
return ptr;
}
```
Someone asked me this question in an interview. Now the point is, the variable 'a' is static, so, unlike ordinary variables which are declared, which loses it's value (popped from stack) once the function returns, this variable retains it's... |
There is no point in havingptras a parameter. The passed value is not used. You could change this to
```
int* func()
{
static int a = 5;
return &a;
}
```
|
Consider the following C code:
```
typedef char * MYCHAR;
MYCHAR x;
```
My understanding is that the result would be that x is a pointer of type "char". However, if the declaration of x were to occur far away from the typedef command, a human reader of the code would not immediately know that x is a pointer. Alter... |
If the pointer is never meant to be dereferenced or otherwise manipulated directly -- IOW, you only pass it as an argument to an API -- then it's okay to hide the pointer behind a typedef.
Otherwise, it's better to make the "pointerness" of the type explicit.
|
When I am giving an input as 'x' the compVal is giving the value as -1. I am expecting 0 since both the values are same. Please someone explain the reason.
```
char ch = getchar();
int compVal = strcmp("x", &ch);
```
|
You have to give to strcmp two strings. A string is an array ofcharwith the last value being\0.
In your example, the second value you are passing it is just the address of acharand there is no string terminator so the function goes blindly ahead until it finds a0( same thing as\0).
You should either usestrcmpwith ac... |
In the following program, I get the output
1
0
0
2130567168
11
2686668
7
2686916
whereas according to me the output must be
1
2
3
4
5
6
7
8
because the array elements are stored in contiguous memory locations and I am accessing those elements in a contiguous fashion.
```
#include<stdio.h>
#include<stdlib.h>
int ... |
The arrayahas automatic storage duration, which ends when the functionfun3()returns. This means it's not legal to access it after this point - doing so has undefined behaviour, which means anything can happen.
|
Going through the book "Cracking the coding interview" by Gayle Laakmann McDowell, in bit manipulation chapter, it posts a question:
Find the value of (assuming numbers are represented by 4 bits):
```
1011 & (~0 << 2)
```
Now, ~0 = 1 and shifting it two times towards the left yields 100 ( = 0100 to complete the 4 b... |
~0is not 1 but1111(or0xf). The~operator is abitwiseNOT operator, and not alogicalone (which would be!).
So, when shifted by 2 places to the left, the last four bits are1100. And1100 & 1011is exaclty1000.
|
In the following program, suppose a is stored at address 1000 and an int takes up 4bytes of storage. Now, c will point to the base address ie, 1000 and incrementing it by 3 will make it point to address 1003. Now, printing the character pointed to by c must give me the character corresponding to ascii 65. But it print... |
You didn't take endianness into account. On a little-endian system, the'a'(or if the encoding isn't ASCII compatible, whatever65is) will be in the first byte, and the other bytes are 0. Passing a 0 byte toprintf("%c\n",_);prints out nothing but the newline.
|
Hello I want to read from and write to a directory just like reading from and writing to files. I always use theopen,read,writeandclosefunctions, which means I use descriptors. But doing this on a directory doesn't work, theopencall works, butreadreturns -1 anderrnois EISDIR. Am I forced to use streams to read a direc... |
Theread()andwrite()system calls cannot be used on directories. Instead, thegetdents()/getdents64()system calls are used to read a directory. Directories cannot be directly written at all.
Futhermore, glibc does not provide a wrapper for thegetdents()/getdents64()system calls - instead it provides the POSIX-conformi... |
Can somebody tell me how to find the table of 9 with using Bit wise operator.A detailed description will be greatly appreciated.
|
To multiply by 2 to the power of N (i.e. 2^N) shift the bits N times to the left
```
0000 0001 = 1
times 4 = (2^2 => N = 2) = 2 bit shift : 0000 0100 = 4
times 8 = (2^3 -> N = 3) = 3 bit shift : 0010 0000 = 32
```
etc..
visualize
Times 9 just add original value like this
```
0000 1001 // 9 original value
0... |
How I can make a file unexecutable in winapi ?Something like quarantine in anti-viruses .Is it possible or not ?Thanks a lot .
|
If you overwrite the first two bytes of the file with something other than MZ it won't be recognised as an executable file any more.
|
I wanted to create a Pam module. I am using Eclipse as my IDE, and making the pam module in C/C++.
When I tried to include the 2 pam modules needed
```
#include <security/pam_modules.h>
#include <security/pam_macros.h>
```
and build, I get an error saying "no such file or directory", I was looking around my system... |
You want to install thepam-develpackage (sudo yum install pam-devel) which contains the header files, under/usr/include/security.
Then (note the added underscore):
```
#include <security/pam_modules.h>
#include <security/_pam_macros.h>
```
|
In the following program, p is declared as a pointer(which is constant BUT string is not).But still the program does not work and stops abruptly saying "untitled2.exe has stopped working".
```
#include<stdio.h>
#include<stdlib.h>
int main(){
char * const p = "hello";
*p = 'm';
return 0;
}
```
Why this u... |
Albeitpitself is a pointer to a non-constobject, it is pointing to a string literal. A string literal is an object which, although notconst-qualified with regards to its type, is immutable.
In other words,pis pointing to an object which is notconst, but behaves as if it were.
Read more on ANSI/ISO 9899:1990 (C90), s... |
Notice the space in betweensome_nameandsome_function. I have seen this in a.cfile and was wondering what is going on here.
```
int some_name some_function{
}
```
Thanks
EDIT:
The code in question is:
```
int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
{
return avcodec_open... |
One part is most likely a macro that expands to nothing (but serves documentaton) or some special attribute, like __stdcall, __declspec(noreturn), __declspec(dllexport)...
EDIT to reflect new info:
definition of yours looks like this:
```
51 #ifndef attribute_align_arg
52 #if ARCH_X86_32 && AV_GCC_VERSION_AT_LEAST(... |
Hello yesterday I have one question it is here:Question
And now I have other problem, I have the code based on answer bysome guy
And now I have a problem I need for all children to see the pids of other child, how can i do that?? I try using global variables, but maybe in wrong way.
Please help I need a fast answer... |
Create a file with the parent process and write pids of all children. Read this file from the children after some delay. You can write out,N, the number of children first and thenNlines each line containing one pid.
|
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.Closed10 years ago.
How do you translate the following ... |
Directly apply the definition ofFibonacci series:
To get a 1:1 translation:
```
int f(int N) {
int fn = N; // Edit: init fn with N
int fn_1 = 1;
int fn_2 = 0;
while (N >= 2) {
fn = fn_1 + fn_2;
fn_2 = fn_1;
fn_1 = fn;
N--;
}
return fn;
}
```
|
```
#include <stdio.h>
union p
{
int x;
char y;
}
k = {.y = 97};
int main()
{
printf("%d\n", k.y);
return 0;
}
OUTPUT: 97
```
I came across this Question. As we know we can only initialize the first member of Union. But in this, at the time of initialization, theyvariable is initialized through some... |
K&R is a great book, but it is old. In C99 You can do this.
Using a designated initializer in the same example, the following
initializes the second union member age :
```
union {
char birthday[9];
int age;
float weight;
} people = { .age = 14 };
```
|
Consider the following C code:
```
typedef char * MYCHAR;
MYCHAR x;
```
My understanding is that the result would be that x is a pointer of type "char". However, if the declaration of x were to occur far away from the typedef command, a human reader of the code would not immediately know that x is a pointer. Alter... |
If the pointer is never meant to be dereferenced or otherwise manipulated directly -- IOW, you only pass it as an argument to an API -- then it's okay to hide the pointer behind a typedef.
Otherwise, it's better to make the "pointerness" of the type explicit.
|
When I am giving an input as 'x' the compVal is giving the value as -1. I am expecting 0 since both the values are same. Please someone explain the reason.
```
char ch = getchar();
int compVal = strcmp("x", &ch);
```
|
You have to give to strcmp two strings. A string is an array ofcharwith the last value being\0.
In your example, the second value you are passing it is just the address of acharand there is no string terminator so the function goes blindly ahead until it finds a0( same thing as\0).
You should either usestrcmpwith ac... |
In the following program, I get the output
1
0
0
2130567168
11
2686668
7
2686916
whereas according to me the output must be
1
2
3
4
5
6
7
8
because the array elements are stored in contiguous memory locations and I am accessing those elements in a contiguous fashion.
```
#include<stdio.h>
#include<stdlib.h>
int ... |
The arrayahas automatic storage duration, which ends when the functionfun3()returns. This means it's not legal to access it after this point - doing so has undefined behaviour, which means anything can happen.
|
Going through the book "Cracking the coding interview" by Gayle Laakmann McDowell, in bit manipulation chapter, it posts a question:
Find the value of (assuming numbers are represented by 4 bits):
```
1011 & (~0 << 2)
```
Now, ~0 = 1 and shifting it two times towards the left yields 100 ( = 0100 to complete the 4 b... |
~0is not 1 but1111(or0xf). The~operator is abitwiseNOT operator, and not alogicalone (which would be!).
So, when shifted by 2 places to the left, the last four bits are1100. And1100 & 1011is exaclty1000.
|
In the following program, suppose a is stored at address 1000 and an int takes up 4bytes of storage. Now, c will point to the base address ie, 1000 and incrementing it by 3 will make it point to address 1003. Now, printing the character pointed to by c must give me the character corresponding to ascii 65. But it print... |
You didn't take endianness into account. On a little-endian system, the'a'(or if the encoding isn't ASCII compatible, whatever65is) will be in the first byte, and the other bytes are 0. Passing a 0 byte toprintf("%c\n",_);prints out nothing but the newline.
|
Hello I want to read from and write to a directory just like reading from and writing to files. I always use theopen,read,writeandclosefunctions, which means I use descriptors. But doing this on a directory doesn't work, theopencall works, butreadreturns -1 anderrnois EISDIR. Am I forced to use streams to read a direc... |
Theread()andwrite()system calls cannot be used on directories. Instead, thegetdents()/getdents64()system calls are used to read a directory. Directories cannot be directly written at all.
Futhermore, glibc does not provide a wrapper for thegetdents()/getdents64()system calls - instead it provides the POSIX-conformi... |
Can somebody tell me how to find the table of 9 with using Bit wise operator.A detailed description will be greatly appreciated.
|
To multiply by 2 to the power of N (i.e. 2^N) shift the bits N times to the left
```
0000 0001 = 1
times 4 = (2^2 => N = 2) = 2 bit shift : 0000 0100 = 4
times 8 = (2^3 -> N = 3) = 3 bit shift : 0010 0000 = 32
```
etc..
visualize
Times 9 just add original value like this
```
0000 1001 // 9 original value
0... |
How I can make a file unexecutable in winapi ?Something like quarantine in anti-viruses .Is it possible or not ?Thanks a lot .
|
If you overwrite the first two bytes of the file with something other than MZ it won't be recognised as an executable file any more.
|
I have a large binary vector that I would like to enter hardcoded in a C-file, as an array of longs. My question is: what is the easiest way to do this? Is there something likeuint64_t b = 0xb01111111011100001011100001011011;to convert the 01111111011100001011100001011011 from 64 bits to 1 long containing them? Or how... |
I would recommend looking at this answer regarding entering binary into C and C++,Can I use a binary literal in C or C++?.
Depending on your compiler/platform, gcc supports this:http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html
```
i = 42;
i = 0x2a;
i = 052;
i = 0b101010;
```
All are equival... |
Standard C utility librarystdlib.hhas these function names:
(String as 'a'):
atofatoiitoa
(String as 'str'):
strtoulstrtolstrtod
Why is a string sometimes called an "a" and sometimes called an "str"?
|
astands forASCII, so in atoi it isASCIIto integer.See here. Theatofamily of functions have been deprecated bystrfunctions.
|
I want to create a program like gdb or gnuplot that has it's own command prompt. I'm looking for a library that will handle the parsing/input validation as well as provide a command history. So far googling for this topic is difficult because any search with the terms 'c' and 'shell' will only produce results for 'csh... |
History is usually managed byreadlineorlibedit. Parsing is usually done withflex/bison.
|
I'm new here , asking questions at least. Always have been able to find good answers here. Trying to get back into programming and relearning C but ran into weird issue.
```
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld \n", nc);
}
```
When I run it, aft... |
TypeCtrl-Din your terminal to sendEOF. You may want
```
while (getchar() != '\n')
```
instead if you want it to work with enter.
|
I was asked this question in an interview and still cannot figure out what it does. Can someone explain what it does and how it does it?
```
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; ... |
It is explained here:
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
Counting bits set, in parallel
A generalization of the best bit counting method to integers of bit-widths upto 128 (parameterized by type T) is this:
```
v = v - ((v >> 1) & (T)~(T)0/3); // temp... |
```
int func(int **a)
{
*a = NULL;
return 1234;
}
int main()
{
int x = 0, *ptr = &x;
*ptr = func(&ptr); // <-???
printf("%d\n", x); // print '1234'
printf("%p\n", ptr); // print 'nil'
return 0;
}
```
Is this an example of undefined behavior or has to do with sequence points?... |
Since there is no sequence point between evaluations of the left and right hand sides of the assignment operator, it is not specified whether*ptrorfunc(&ptr)is evaluated first. Thus it is not guaranteed that the evaluation of*ptris allowed, and the program has undefined behaviour.
|
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.Closed10 years ago.
Is it better to use a pointer to na... |
Any modern compiler should produce an equivalent assembly code for both methods.
|
I have the following code:
```
char temp[100] = "";
int a, b;
sprintf(temp, "%02c|", "A");
sprintf(tmp, "%02s|", ((b== a) ? ("??") : ("__")));
```
but when I lint it, it says Warning 566: Inconsistent or redundant format char 'c', what is the problem and how to fix it?
And I tried to:
1) changed "A" to 'A' and us... |
It's right about inconsistent:
```
sprintf(temp, "%02c|", "A");
```
That should be a character literal'A'to match%c, not a string literal"A". If you want to keep the"A", use%sinstead.
|
I have the following code:
```
int dst[5];
int src[100];
// assign value to array src
memcpy(&dst[0], &src[0], sizeof(int) * 100);
```
what will happen in this case? will only the first 5 elements is copied to arraydst?
or the program will crash?
|
This invokesundefined behaviour. Anything could happen.
In practice, what will probably happen is that memory outside ofdstwill be overwritten, trashing something else, and therefore corrupting the state of your program. The best-case scenario is that this causes your program to crash.
|
how to check whether a number is divisible by 5 or not without using % and / operator.I want a quickest algorithm for this problem.
|
A good starting point is to look into how division can be accomplished with multiplication and bit-shifts.This questionis one place to look.
In particular, you can follow the attached post to hit upon the following strategy. First, "divide by 5" using multiplication and bit-shifts:
```
int32_t div5(int32_t dividend)... |
came across this and was wondering what it does
```
LPCTSTR szmyLPCTSTR;
// doing _tcsncpy things with that string
//at the end then there is this line which i am not sure what it does
szmyLPCTSTR[122] = 0;
```
Thanks !!
|
LPCTSTR is simply a pointer to characters. It's adding a null terminator to the string.
|
I have a program which use libevent library
when compile the program, the compiling command is like:
```
gcc -o myprogram mysource.c mysource.h -levent
```
so it is dynamic linking.
now I want to run this program on a computer where there is no libevent,
I need static linking so that my program can be run on that ... |
You should havelibevent.a. Then you can justgcc -o myprogram mysource.c libevent.a.
Or trygcc -o myprogram -static mysource.c -levent.
(And you probably shouldn't specifymysource.hto gcc as it's most likely included into mysource.c with#include "mysource.h".)
|
I have the following code:
```
#define NUMBER_OF_ROOMS
if((unsigned int)(NUMBER_OF_ROOMS - 2) > 20)
{
// do something here
}
```
but I got a lint warning:Warning 506: Constant value Boolean, what does this mean and how to fix it?
|
It means that the value of the expression is constant, and thus theifis pointless since it's known at compile-time whether or not it will be true or not.
You could of course make it more dynamic, or use the preprocessor instead:
```
#if (NUMBER_OF_ROOMS - 2) > 20
// do something here
#endif
```
I assumed the cast t... |
I want to access the element of array of pointer to structure but i have no idea how to access it.
```
#include<stdio.h>
int main()
{
struct hash
{
int pages;
int price;
};
struct hash *h[5]={1,2,3,4,5};//array of pointer to structure
printf("value =%d\n",h->pages);
// want to access and also tell me how to data will... |
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct hash {
int pages;
int price;
};
struct hash *h[2];
h[0] = malloc(sizeof(struct hash));
h[0]->pages = 1;
h[0]->price = 2;
h[1] = malloc(sizeof(struct hash));
h[1]->pages = 3;
h[1]->price = 4;
printf("... |
This question already has answers here:How can I run an external program from C and parse its output?(8 answers)Closedlast year.
Is there a better way to do it?
```
int numOfCPU;
system("grep -c ^processor /proc/cpuinfo >> /tmp/cpuinfo");
FILE *fp = fopen("/tmp/cpuinfo", "r");
fscanf(fp, "%d", &numOfCPU);
fclose(fp)... |
Ok, I was confused in my other answer. In any case, the philosophy in this answer is the same. You can use directly thepopenfunction.
Then you have something like this:
```
int numOfCPU;
FILE *fp = popen("grep -c ^processor /proc/cpuinfo", "r");
fscanf(fp, "%d", &numOfCPU);
pclose(fp);
```
I hope it will be useful... |
I am working on UDP Server/Multiple Client Application.
There are multiple threads handling multiple clients.
There is one single thread which keeps on sending KEEPALIVE Messages to each active clients. Since this thread is inwhile(1)so CPU Usage reaches to 100%.
Since I want this functionality to go on, I have use... |
sleep- Suspends the execution of the current thread until the time-out interval elapses.
And gives processor to other threads which are ready to run.
source :http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx
So, justsleepdoes it all you need.
|
my program must have a struct with a string, like this
```
typedef struct _Node {
char file[MAX];
//other stuff...
} Node;
Node *myPointer;
```
So, in other function, I need to read a string from the user and pass to my "file" variable in the struct, something like this:
```
char input[MAX];
scanf("%s", input)... |
This is a C++ solution:
```
#include <string>
#include <iostream>
struct Node {
std:string file;
};
```
then
```
Node node;
std::getline(std::cin, node.file);
```
|
Assume I have afile.hand in it I have:
```
int arr[128];
(void)(*func_ptr)(int);
```
And I havecode1.c,code2.c,code3.cincludes it. Willarrandfunc_ptrwill be global scope allocated for each .c file ? i.e. each .c file will have his own instance ofarrandfunc_ptr? if so why is that ?
does usingstaticcan change the res... |
Will arr and func_ptr will be global scope allocated for each .c file ?
Yes it will, and you will end up with a linking error since you have defined the same variable names several places at global scope.
Header files you #include in your .c files are just inserted into your .c file, there's nothing special about th... |
I have a file that I open with fopen in a init function that I leave without closing because I want to fread() it in another function. In order to do this would I declare a global static file that all the functions can interact with?
|
No; you would pass the file pointer to the functions as a parameter.
For example:
```
FILE *init( char *fname )
{
FILE *fp = fopen( fname, "r" );
return fp;
}
void read( FILE *fp )
{
...
while ( fread( buffer, sizeof buffer, 1, fp ))
// do stuff
}
int main( void )
{
FILE *fp = NULL;
...
fp = init... |
I am trying to figure out how to use this. I'm way out of my element here, so thanks for bearing with me.
|
Libgit2 works primarily on repositories that you have disk access to, meaning you have to clone the repository before you can use libgit2 to work with it.
Once you've got that, you'll get a handle to your repository usinggit_repository_open, and create the branch usinggit_branch_create.
|
What's wrong in my function 'front'?
I want to pass the pointer to an specific line in my array to read/edit it.
```
struct queue
{
char itens[LN][CL];
int front,rear;
};
char *front(struct queue * pq)
{
return pq->itens[pq->front+1][0];
}
```
|
You're currently returning a singlechar, not a pointer to a row. Take off the[0]:
```
char *front(struct queue *pq)
{
return pq->itens[pq->front+1];
}
```
|
Looking through the Ruby code it has the following for proc_arity:
```
static VALUE
proc_arity(VALUE self)
{
int arity = rb_proc_arity(self);
return INT2FIX(arity);
}
```
More of a C coding style question really but why isstatic VALUEon a separate line instead of something like this:
```
static VALUE proc_a... |
It comes from the UNIX world, because it helps to easilygrepthe definition of a function:
```
$ grep -n '^proc_arity' *.c
```
or usingvim:
```
/^proc_arity
```
|
```
int (*(*q)(int (*)()))();
```
Ok, I start with: q is a pointer to a function, which takes... Not sure what should follow next, but perhaps it's ...a pointer to function, which takes nothing and returns int, and returns pointer to a function, which takes nothing and returns int.
|
The trick is thatqitself is a function pointer that returnsandtakes a function pointer.cdeclsays:
declare q as pointer to function (pointer to function returning int) returning pointer to function returning int
|
I want to know what is the difference between these two statements in C. Are they same? Any logical proof whether they are same or not.
```
if (!(b[i]&&c[i+1]&&c[i+2]&&d[i+3]))
```
and:
```
if (((b[i] == 0|| c[i+1] == 0)|| c[i+2] == 0)|| d[i+3] == 0)
```
|
Yes, they will both evaluate to the same result.
If either of those values is0than the expression will return true and enter the if-statement(barring the missing parens at the end)
as far as proofs go, that is more or less DeMorgan's law
http://www.seas.upenn.edu/~ese570/Boolean_Identities.pdf
|
Is there any danger in casting achar *type tosigned char *in C, where the char array is interpreted as a byte array.
I've read that in gcc, thechartype can be either unsigned or signed depending on the system. In the 'worst' case, thechar *would be aunsigned char *, but as the array is just interpreted as a series o... |
There shouldn't be any problem in the cast itself, especially if you are just interpreting the array as bytes. In this case though I would suggest that you consider using the C99 typesuint8_tandint8_tto convey your intentions better, if they are available to you.
|
Where can I find the implementation of if_nametoindex? It seems to be externed in net/if.h but searching through the source code I cannot find any hint on the implementation. A better question is, how would I find what library it is defined in etc...
|
You can try to search through all projects, not just apple sources:http://code.metager.de/source/s?&sort=relevancy&defs=if_nametoindex&reset=trueTake a look atfreebsd implementationfor example.
|
I want to hide the drive from user with Diskpart Command-Line Utility .I use remove letter command and the drive becomes hidden .But I want to use the data of that drive for example in my program written in C .How I can do this or is it possible ?I want to do this only for usb flash drives .If it is not possible pleas... |
You can use the volume GUID like this:
```
\\?\Volume{2a0b16cf-f76a-11df-9310-806e6f6e6963}\path\file.ext
```
Note that only the Unicode file functions will accept this sort of path, and the syntax has to be strictly correct. For example, you can't use forward slashes instead of backslashes.
I'm not sure how best ... |
Given a memory allocation:
```
struct typeA *p = malloc(sizeof(struct typeA));
```
and then somewhere, for example, in a function, there are 2 choices:
```
void func(void *q)
{
....
free(q);
}
void func(void *q)
{
....
struct typeA *pp = (struct typeA *)q;
free(pp);
}
```
Both of them are O... |
Both are ok.free()only cares about the address that is stored in the pointer and that does not change when casting.
|
I'm having what is follow:
```
QLabel* label_PM= new QLabel(this);
QPixmap PM ("C:/PM.jpg");
label_PM->setPixmap(PM);
```
I would like to insert to the PM a text like what is done in OpenCV cv::putText.
Nothing from research seems to resolve my problem,
Is there a way to do so?
|
Drawing to aQPixmapis done through aQPainter. For example:
```
QPixmap pix = ...;
QPainter painter( &pix );
painter.setFont( QFont("Arial") );
painter.drawText( QPoint(100, 100), "Hello" );
```
This is a very basic usage, look at theQPainterdocumentation for more information.
|
couldn't find an answer on google.
Is there an equivalent in C for PHPdate('YmdHis')output:
20130613153516
Thank you!
|
You can usestrftimefunction incto achive same functionality.
```
#include <stdio.h>
#include <time.h>
int main()
{
time_t x;
time(&x);
struct tm *tmptr = localtime(&x);
char buf[1000];
strftime(buf, sizeof(buf), "%Y%m%d%I%M%S", tmptr);
printf("%s\n", buf);
return 0;
}
```
Output is lik... |
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Accessing arrays by index[array] in C and C++(2 answers)Closed10 years ago.
v it's an array of ints and a it's an int:
```
#include <iostream>
using namespace std;
int main() {
int v[10], a;
cout << v[a] << endl;
cou... |
Because the indexer syntax means "the value in the address denoted bythe beginning of the array plus an offset". Or, to put it another way:
```
v[a] == *(v + a) == *(a + v) == a[v]
```
|
I have following C line of code where cfType is a normal C enum type:
```
int foo (double * parameters) {
...
cfType coefSelect = (cfType) *parameters; /* The double pointed by at parameters
* is cast to a cfType enum and result
* i... |
I think you have to cast into an integral type before to prevent this warning.
Something like:
```
cfType coefSelect = (cfType)(int) *parameters;
```
|
I have a shared memory used by multiple processes, these processes are created usingMPI.
Now I need a mechanism to control the access of this shared memory.
I know thatnamed semaphoreandflockmechanisms can be used to do this but just wanted to know if MPI provides any special locking mechanism for shared memory usag... |
MPI actually does provide support for shared memory now (as of version 3.0). You might try looking at the One-sided communication chapter (http://www.mpi-forum.org/docs/mpi-3.0/mpi30-report.pdf) starting with MPI_WIN_ALLOCATE_SHARED (11.2.3). To use this, you'll have to make sure you have an implementation that suppor... |
I am trying to compile a program in Cygwin and it requires shadow.h in one of the source files, which is missing in the /usr/include path. How do I add shadow support in Cygwin ? any packages to install ?
In CentOS, just installing gcc and glibc provided the shadow.h header file. what are the equivalent packages that... |
shadow.h is to define the type struct spwd, and it is a part of Gnulib.Your compilation is not getting support of this lib.
There should be a libshadow.a in /usr/lib and you need to include it during build as follows
```
gcc program.c -o program -lshadow
```
for better understanding you canlook here also.
```
Edit... |
I have two scripts which I want to run in synchrony. Each one runs in a different terminal and I want them to start only when I press a Keyboard key I choose. But as they are in different terminals I think That won't work. Any suggestions of a better way?
|
You could start both of them up and have them wait on a synchronization primitive such as a mutex. Then, reset that mutex from a script/program/whatever using your single keyboard press, to trigger both scripts.
|
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)What does the : do in a struct declaration after a member(1 answer)What does 'unsigned temp:3' in a struct or union mean? [duplicate](4 answers)Closed10 years ago.
```
typedef struct{
... |
These are bit fields:https://en.wikipedia.org/wiki/Bit_field. Here you just reserve 1 bit for 'flanke' and one for the 'lastState'. The type has to be unsigned int.
|
I am usingnamed semaphoreinCinLinuxto control the access of shared memory across multiple processes.
As of now I have not added any code tosem_closeandsem_unlinkthe semaphore.
So my question is :
Do named semaphore automatically get destroyed when all processes using it are finished?
If yes then, is it ok not to ca... |
http://linux.die.net/man/7/sem_overview
"POSIX named semaphores have kernel persistence: if not removed by sem_unlink(3), a semaphore will exist until the system is shut down."
|
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... |
Try adding a leading0to your format specifier -%04x
```
printf("the value is 0x%04x\n", a);
```
Just in case its omission from your question wasn't a typo, note that I've also added a%to make this a format specifier. As it stands, the code in your question would have just echoedthe value is 0x4x
|
I'm using packet_mmap to capture all packets in the system, but there doesn't seem to be any way to interfere with the rest of the OS getting them as well. I want to be able to have exclusive control over packets coming into userland and decide whether they get to go onto other applications in the system or if they ge... |
You can't do what you want withPACKETsockets - they're not designed for that purpose.
What you need to use instead islibnetfilter_queue, together with an iptables rule that directs all incoming packets to your queue.
|
A debugger gets a line number of an expression andtranslates it into an program address, what does the implementation look like? I want to implement this in a program I'm writing and the most promising library I've found to accomplish this islibbfd. All I would need is the address of the expression, and I can wait for... |
You should take a look at the DWARF2 format to try to understand how the mapping is done. Do consider how DWARF2 is vast and complex. It's not for everyone, but reading about it might satisfy your curiosity faster and more easily than reading the source for GCC/GDB.
|
I receive a port number as 2 bytes (least significant byte first) and I want to convert it into an integer so that I can work with it. I've made this:
```
char buf[2]; //Where the received bytes are
char port[2];
port[0]=buf[1];
port[1]=buf[0];
int number=0;
number = (*((int *)port));
```
However, there's some... |
I receive a port number as 2 bytes (least significant byte first)
You can then do this:
```
int number = buf[0] | buf[1] << 8;
```
|
i am trying to read integers from a file and fscanf doesn't work well with this code.
```
fp=fopen("record.dat","r");
if(fp==NULL)
{
printf("Another reading error");
}
else
{
printf("\nstarting to read\n");
i=0;
while(i<10)
{
if(fscanf(fp,"%d",&temp)>0)
printf("%d\n",temp);
... |
You are opening the file as a writable file instead of readable.
You must change"w+"to"r"
w+ The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
|
I have a C project with a structure as follows:
```
Project
- fileA.h
- fileA.c
+ subdirB
- fileD.h
```
There is a typedef enum of bool in fileD.h:
```
typedef enum bool {
false = 0, /**< false (0) */
true /**< true (1) */
} bool;
```
In fileA.c there are several functions that use bool as parame... |
Are you includingfileD.hinfileA.h? In order to declare a function that takes a bool, the compiler needs to know what a bool is.
|
In the below example when I define char array uninitialized and want to find the length, it's undefined behavior.
```
#include<stdio.h>
int main()
{
char a[250];
printf("length=%d\n",strlen(a));
}
```
I got "0". I don't know how? Explain it.
|
Luck. Whether it's good or bad luck is a matter of opinion. The contents of your array are whatever happened to already occupy that memory, and is not initialized. In your case, it happened the first byte was a'\0'.
This is, of course, undefined behavior and you can't depend on it happening this way.
|
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
How does the Erlang runtime implement a user-space multi-threaded mechanism on UNIX-like ... |
Each Erlang process is just a struct with a heap and a stack in it. So switching process is just a matter of using another struct in an queue. I thinkthispaper describes it nicely.
|
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.Closed10 years ago.
when using typedef for arrays, it i... |
typedeflooksexactlylike a normal vairable declaration, and that happens to be how an array declaration looks in C (and inherited into C++):
```
int foo[3]; // Array of three int
typedef int FooT[3]; // typedef for array of three int.
```
|
I declared my Video Buffers as follows in a source file:
```
/* Video buffers */
#pragma section ("DecoderBuf0", DM)
static VIDEO_BUF VideoBuf0;
#pragma section ("DecoderBuf1", DM)
static VIDEO_BUF VideoBuf1;
```
while I declared in the header file :
```
typedef struct VIDEO_BUF
{
uint8_t Data[VID... |
This is a linker error. Refer to your toolchain docs on how to solve this. In particular, the section titled Linker Symbol Resolution should make the causes of the problem clearer. Your linker file must be set up wrong.
|
I've got an application that at a high level performs SCSI READ10 and WRITE10 operations simultaneously. When they reach the lower-levels of my code they call write() followed by read() on /dev/sgXX. I'm getting very strange results on devices receiving my application's commands though, and they happen sporadically.... |
Read and write should be by definition safe but:
1) Reading and writing, does it happen on the same file descriptor. If not, the open file table in your system can have multiple offsets, resulting in data read and write in an inconsistent way.
2) If you have a block of data that has to be written to your disk, do yo... |
Suppose I have (on a 32 bit machine)
```
enum foo {
val1 = 0x7FFFFFFF, // originally '2^31 - 1'
val2,
val3 = 0xFFFFFFFF, // originally '2^32 - 1'
val4,
val5
};
```
what is the value of val2, val4 and val5? I know I could test it, but is the resultstandardized?
|
In C standard:
C11 (n1570), § 6.7.2.2 Enumeration specifiersEach enumerated type shall be compatible withchar, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, butshall be capable of representing the values of all the members of the enumeration.
If the underlying type... |
So I want to verify the hexadecimal representation of the number 1.0 in Language C, below are my codes:
```
int main(int argc, char **argv)
{
void showBytes(unsigned char * p,int size){
int i;
for (i=0;i<size;i++){
printf("%.2x",p[i]);
}
}
float f;
f=1.0;
showB... |
This is an endianness mis-match. You are displaying the value using one endianness convention, but your expected value uses the other convention.
Endianness is a well-known issue for integer data types, but it is perhaps less well known endianness also affects floating point representation.
|
Eclipse popped a new one on me this morning. See the circled icon in the image.
I have looked at lots of links from similar posts on SO (though didnt find any for thsi exact icon) and none of the links have mentioned this.
FYI this is in Texas Instruments Code Composer Eclipse "package", or however it's termed, but s... |
It means this folder is in a workspace path.
|
I want to store pointers to file's line numbers in an array and later I want to retrieve the specified line from disk. I can not store pointer to line number directly as when I read the file back the memory locations would have changed. So, I am storing the offset from the beginning of the file instead. For storing th... |
On POSIX systems,off_tis the standard type for file offsets. It's probably a 64-bit type, though, just likeuint64_t, as those can hold values on the order of 2e11 without trouble.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
There are ways, one of them is CppCMS, a C++ web framework:
http://cppcms.com/wikipp/en/page/main/
https://en.wikipedia.org/wiki/CppCMS
|
So i'm learning structures and am trying inputting a string with dynamic memory allocation.
Here is what I have so far:
```
typedef struct{
char foo[81];
} TYPE;
void function(TYPE get[]){
char a[81];
scanf("%s", a);
get->foo = malloc(strlen(a)+1*sizeof(char)); //this line produces an error that ... |
foois an array object and not a pointer so you can not use the operation
get->foo = (char*)calloc(strlen(a)+1,sizeof(char));
you are trying to assign a(void *)to typechar[81], which is totally incompatible. Lvalue should be pointer in this case.
|
I want to disassemble a simple .c file:
```
#define UPPER 15
const int lower = 12;
int sum = 0;
int main(void) {
int i;
for(i = lower; i < UPPER; i++)
{
sum += i;
}
return sum;
}
```
To get the assemblercode for ARM CPUs on my Mac Mini 10.8.3. There fore i am stuck at:
How do i create the ARM execu... |
To compile(assuming the target is iOS 6.0):
```
xcrun -sdk iphoneos c++ -arch armv7 -marm -march=armv7-a -miphoneos-version-min=6.0 -g -O3 <any other options ...>
```
To disassemble:
```
otool -tdv <your binary>
```
|
Code:
```
char menu_list[] = {'Boiled egg', 'Corn flakes', 'Gobi 65', 'Chicken 65', 'Basandi'};
```
Am a new to c programming i just wanted to make an array of string, but am getting an waring as below. can anyone please tell me why its happening. Its a c program.
```
main_menu.c:226: warning: large integer implici... |
You should use double quotes for string lliteral, and you are wrongly declaring the array.
Perhaps you are looking for thiss.
```
char *menu_list[] = {"Boiled egg", "Corn flakes", "Gobi 65", "Chicken 65", "Basandi"};
```
|
This question already has an answer here:Most complete c++ facebook library [closed](1 answer)Closed10 years ago.
I'm looking to create a desktop app in C/C++, most likely with Qt, that has the ability to connect (read/post) to Facebook. Which got me thinking, how exactly would you go about doing such a task? I know ... |
If you can get a C++ json interpreter you can use the Graph API.https://developers.facebook.com/docs/getting-started/graphapi/. You make queries over HTTPs and get a response in JSON that you can use however you want.
|
If i have a text file with each line of different length, how does the following code work??
```
FILE *ptr;
char str[100];
ptr=fopen("hi.txt","r");
while(fgets(str,100,ptr)!=NULL)
{
........
........
}
```
In this code the 'str' will hold 100 characters which includes some of the characters from 2nd line of text fil... |
fgets will read up to a single line OR the value passed in as the second parameter.
fgets man page
As long as none of your lines are longer than 99 characters (saving one for the NUL terminator, your code will work as expected.
If you call fgets on a line that is longer than N-1, your next read will continue where ... |
Is there a way to to something like:
```
char* a = "Hello";
char* b = NULL;
char* c = a | b;
Result should be c = "Hello";
```
Seems like it does not work with Char*, but is there a way to do something like that?
|
This is nonsense not only because bitwise operators on pointers would have very... interesting... results, but mainly becauseNULL is not guaranteed to be represented by 0.
|
I am looking for a function/system call that can be used in C to manage network interfaces of the Linux machine. E.g., I would like to doip link set wlan0 down(or up) orifconfig wlan0 down, what function can be used for it, apart fromsystem()?
|
To access the functionality provided by the iproute2 tools from software, you can use theLinux rtnetlink API. To make it easier for you, use libraries likelibnl.
In case you encounter trouble, there is already a tag callednetlink
|
I want to write a specific number of bytes to a socket,
```
n=write(sock_fd, buf, len);
```
ifn<len, I would rather no bytes are written into the socket,
is it possible or not?
thanks!
|
If you're using blocking mode, the condition can never arise: send() will block until all the data has been sent. This is not the way the documentation reads, but it's how all known implementations behave.If you're talking about TCP, it doesn't make any difference anyway: it's a byte-steam protocol, not a datagram pro... |
I want to store pointers to file's line numbers in an array and later I want to retrieve the specified line from disk. I can not store pointer to line number directly as when I read the file back the memory locations would have changed. So, I am storing the offset from the beginning of the file instead. For storing th... |
On POSIX systems,off_tis the standard type for file offsets. It's probably a 64-bit type, though, just likeuint64_t, as those can hold values on the order of 2e11 without trouble.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
There are ways, one of them is CppCMS, a C++ web framework:
http://cppcms.com/wikipp/en/page/main/
https://en.wikipedia.org/wiki/CppCMS
|
So i'm learning structures and am trying inputting a string with dynamic memory allocation.
Here is what I have so far:
```
typedef struct{
char foo[81];
} TYPE;
void function(TYPE get[]){
char a[81];
scanf("%s", a);
get->foo = malloc(strlen(a)+1*sizeof(char)); //this line produces an error that ... |
foois an array object and not a pointer so you can not use the operation
get->foo = (char*)calloc(strlen(a)+1,sizeof(char));
you are trying to assign a(void *)to typechar[81], which is totally incompatible. Lvalue should be pointer in this case.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.