question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
The MSDN page forWriteFileExsays that it can not be used in IOCP model because it has an argument to specify the completion routine. If the file handle has been associated with an I/O completion port, thenWriteFileExwill fail.
However,WSASendallows the caller to specify a completion routine as its last argument, whi... |
The only thing the documentation says is:
The completion routine follows the same rules as stipulated for Windows file I/O completion routines.
That might suggest that you cannot mix IOCP andlpCompletionRoutinetogether, like withWriteFileEx(). On the other hand, why would youwantto mix them together in the first pl... |
Suppose defined:int a[100]Typeprint athen gdb will automatically display it as an array:1, 2, 3, 4.... However, ifais passed to a function as a parameter, then gdb will treat it as a normal int pointer, typeprint awill display:(int *)0x7fffffffdaa0. What should I do if I want to viewaas an array?
|
Seehere.In short you should do:
```
p *array@len
```
|
With the code:
```
int nsize;
int * buffer;
char TargetBuffer[4096];
const SIZE_T buffersize = (320*240) * sizeof(int);
buffer = (int *) malloc(bufferSize);
// fill buffer with data
nsize = 0;
while(nsize < buffersize)
{
// HERE after some loops i get Access Violation
memcpy(TargetBuffer, buffer + nsize, 4... |
When you addbuffer + nsizeyou have to realize that you are actually addingbuffer + (nsize * (sizeof(int))since it's aint *when you are doing pointer arithmetic.
So it probably has something to do with it. Try incrementing nsize bynsize += 4096/sizeof(int)or something more clever.
|
How Can I change objects name by a loop?
I want create a light effect like knight-rider's one. With a PIC
I thought instead of turning on and off manually to use a loop for change RB line number.
I want to change the last number of this Port line name: like RB01 RB02 like this
my code is like this
```
for(int i =... |
AssumingRB01,RB02, etc are just convenient#defines for accessing the bits inPORTB, you can write the loop with bitwise arithmetic and not useRB0*at all.
```
for ( int i = 0; i != 6; ++ i ) {
PORTB = 1 << i; /* one light at a time */
/* or */
PORTB = ( 1 << i + 1 ) - 1; /* light all in sequence */
}
```
|
```
#include <mpi.h>
double f() {
double timer = MPI_Wtime();
return timer;
}
```
What I am searching for is some set of mock MPI functions, so I can#include <mpi_mocks.h>instead of mpi.h and get it compiled without linking to MPI library. It could also be something like#define MOCKwhich will trigger this beh... |
As far as I can see, there are no mocks you could just #include and be done. However, it should be no big deal to write the needed functions yourself and for whichever mocking framework you chose to use. Just start with an empty header and look which functions you compiler complains about.
|
I am trying to use a Haskell library in my C code. The Haskell function I am trying to use has the typeString -> IO [Reference]whereReferenceis a rather complex structure (seehere for details).
Based on reading various pieces of documentation it seems that I would have to make this type an instance ofStorableand also... |
It depends on you actual use case, but...
It could be easier to exportReferenceas opaque type (viaForeign.StablePtr), and export getter functions to access individual fields.
Please let me know if you need more details, and I'll expand the answer.
|
```
extern int a;
int a = 1;
int main(void)
{
return 0;
}
```
Is this UB? standard says in 6.2.2/7
If, within a translation unit, the same identifier appears with both internal and external
linkage, the behavior is undefined.
|
This is perfectly defined behavior. And this is what the compiler would get after pre-processing after an header is included.
Your confusion seems to come that:
```
int a = 1;
```
has not internal linkage. At file-scopeahas external linkage. It would have internal linkage if thestaticspecifier was added.
|
Recently, I am confused with this two expression -(type)valueandtype(value).
For example :size_t c = size_t(-1); size_t c = (size_t)-1;
what is the difference?
|
The former is C++, it's doingdirect initializationby calling a constructor.
The second is C (or C++), it's doing a cast.
So, there's a lot of difference from a C programmer's point of view.
Also, this is a pretty bad idea, sincesize_tis an unsigned type. This should be done usingssize_t, which is signed and removes... |
I struggle masking a uint64_t variable by N bytes. I do not know N but I know it is 8 or less. My current code looks like this:
```
// uint64_t n is given
uint64_t mask;
for( mask = 0x00; n; n--) {
mask = mask<<8 | 0xFF;
}
```
for building the mask. What am I doing wrong here?
Edit:The question was answered. An... |
It should work, according to the [operator precendence table1].
Still, it's more clear to write it as:
```
mask <<= 8;
mask |= 0xff;
```
or:
```
mask = (mask << 8) | 0xff;
```
You can also do it with a look-up table, of course.
|
I'm getting a clang warning from the following third party code in my project:
```
uLong x ;
int i;
int err;
err = unzlocal_getByte(pzlib_filefunc_def,filestream,&i); d
x = (uLong)i; // <- CLANG: Assigned value is garbage or undefined
```
So to get rid of this error I want to do change the initializing of i to:
``... |
I think you can change it toint i = 0;.
According to your code, initiallyivariable wasn't initialized, so it could contain arbitrary values, i.e. garbage.
I don't know, and even compiler also doesn't know, will functionunzlocal_getByteactually change value ofivariable, so it warns you about possible indeterminate st... |
This question already has answers here:How do I run a program with commandline arguments using GDB within a Bash script?(9 answers)Closed3 years ago.
I have to debug a program that has errors in it as part of my assignment. However, I must first pass command line arguments in order to solve this problem.
I do:
```
... |
Oncegdbstarts, you can run the program using "rargs".
So if you are running your code by:
```
$ executablefile arg1 arg2 arg3
```
Debug it ongdbby:
```
$ gdb executablefile
(gdb) r arg1 arg2 arg3
```
|
This is a n00b question and I've seen an answer that does not help me.
I'm running a simple c program (firsty.c) written in textmate:
```
#include <stdio.h>
int main()
{
printf("hi world.\n");
return 0;
}
```
I've entered the following into the terminal with the following results:
```
$ make firsty.c
make... |
make firsty.cisn't doing anything at all. Try insteadmake firsty, and then./firsty.
|
```
char words[wordCount][MAX_WORD_LENGTH];
```
I know i need to use malloc to be able to have a user defined length of an array but how would i do this with a 2d array?
```
char words[MAX_WORD_LENGTH];
words = (words *) malloc (wordCount)
```
Would something like that work?
Just started using c so im still getting... |
You have to do this first:
char *words = calloc(wordCount * MAX_WORD_LENGTH, sizeof(char));
and accesswords[i][j] as words[i*MAX_WORD_LENGTH + j]
|
In my C program, I create a child process and in it, it parses a string and created a pointer array (usingmalloc()) for the use of passing it inexecvp()command.
But the problem is, how do you free the memory that the child created?execvp()runs the new task and may or may not return. If it doesn't return, then it was ... |
You don't need to. Specifically, if you allocate memory in a process before anexec()-type routine (e.g.,execvp()in your case) is called, all of the memory associated with the original executable is released. It's a similar situation to a process exiting (and having all its resources released), and a new process bein... |
Lets say I have this byte
```
uint8_t k[8]= {0,0,0,1,1,1,0,0};
```
Is there a way to get this to become a single integer or hex?
|
Ifkrepresents 8 bytes of the 64-bit integer, go through the array of 8-bit integers, and shift them into the result left-to-right:
```
uint64_t res = 0;
for (int i = 0 ; i != 8 ; i++) {
res <<= 8;
res |= k[i];
}
```
The direction of the loop depends on the order in which the bytes of the originalintare store... |
There must be some logic behind this calculation. But I am not able to get it. The normal mathematics does not result in such behavior. Can anyone help me out in explaining why
printf ("float %f \n", 2/7 * 100.0);results in printing 1.000000
Why so? I am not understanding the reason
|
Integer division.2/7 = 0as an integer,0 * 100.0 = 0.0as a float.
Do2.0/7 * 100.0to get the answer you're looking for.
|
Code:
```
#include<stdio.h>
#include<string.h>
int main (int argc, char *argv[]) {
char folderPath[1024];
int i = 0;
for (i; i < (strlen(argv[0]) - 7); i++) {
folderPath[i] = argv[0][i];
}
printf("Command: afplay %ssong.mp3\n", folderPath);
system("afplay %ssong.mp3", folderPath);
... |
system()does not use a format string. It takes the whole command as a literal string. Usesprintf()to format your command into a buffer and then send that buffer to system.
```
char buf[1024];
snprintf(buf, 1024, "afplay %ssong.mp3", folderPath);
system(buf);
```
or something along these lines.
|
I always forget to add the 'static' prefix to my variabeles and functions, and so the GCC marks them as extern. Is it possible to change this behaviour so that it marks everything static by default. And is there a performance difference between the two types at runtime, or is it more a formality?
|
Is it possible to change this behaviour so that it marks everything static by default.
Not to my knowledge.
And is there a performance difference between the two types at runtime, or is it more a formality?
Yes,gccis able to perform further optimizations when objects or functions arestaticspecified. For example,gcc... |
My question is related to the solution provided inthis answer.
When I update the slider position, the video always starts from frame zero, whereas, slider continues from the moved position on-wards. How can I correct this?
|
Make sure you understand all the parameters used tocreate a trackbar. One of them is namedcount, and it defines the maximal position of the slider (the minimum is 0).
All you need to do is retrieve the total number of frames in the video file (before you start to read the frames of the video) and pass this value as t... |
i want to add new rule windows firewall , am usingsystem()function for this in c
normally cmd command for that would be
```
netsh advfirewall firewall add rule name="myp" dir=in action=allow
program="C:\test\Project1.exe"
```
so i want to know how i can insert it tosystem();function i try it but no success , i mea... |
You just need to escape the double quote -\"to use it inside a string.
Seeherefor a list of other escape sequences.
Your command would then become
```
system("netsh advfirewall firewall add rule name=\"myp\" dir=in action=allow program=\"C:\\test\\Project1.exe\"");
```
|
I have this piece of code; it works when you directly write the arguments tosystem(), and doesn't work if you pass the arguments to it. Any help please?
```
char dest[100];
char file[50];
char dir[100];
printf("Enter source path: ");
scanf("%s", dir);
printf("Enter filename: ");
scanf("%s", file);
printf("Enter de... |
You can try this
```
char dest[100];
char file[50];
char dir[100];
char command[300];
printf("Enter source path: ");
scanf("%s", dir);
printf("Enter filename: ");
scanf("%s", file);
printf("Enter destination path: ");
scanf("%s", dest);
sprintf(command,"move %s%s %s", dir,file,dest);
system(command);
```
|
I know that the ellipses operator is used to implement variable arguments in function interface. I was wondering however if the 3 ellipses are some sort of macro or a builtin C construct. I was looking through the Mingw headers and can't seem to find any definition for this macro. I don't seem to have stdvar.h and var... |
Its not a macro. Its a part of the language itself, so a "builtin C construct".
Cant find a good reference, butgoogle resultsalternate between calling themoperatorandspecifier
|
I was just curious by default does Microsoft's C/C++ Optimizing Compiler compile down to machine language or byte code?
|
It compiles down to machine language (microprocessor opcodes) by default, orCIL, using the/clrswitch.
For comparison, C# and Visual Basic compile toCIL, and Visual Basic 6 can compile to either P-code (a form of byte code) or native code (machine language).
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
Have you already trieddoxygenin combination with the graphviz package?
|
I need help on code that print out a middle word of string.
First Example:
Input: My name is AlexOutput: either name or is <-- is the middle
Second Example:
Input: Hello. I Need help on my coding.Output: Help <-- middle word
Hopefully someone can help me out. I will try to follow up.
|
Here's an idea:
Split string into wordsNow that you know how many words there are, decide how to handle the even casePrint the decided words
You can usestrtok()for the splitting, and perhaps assume that a "typical" sentence has not more than 50 words, each being no longer than 16 characters. Just to simplify the cod... |
My question is related to the solution provided inthis answer.
When I update the slider position, the video always starts from frame zero, whereas, slider continues from the moved position on-wards. How can I correct this?
|
Make sure you understand all the parameters used tocreate a trackbar. One of them is namedcount, and it defines the maximal position of the slider (the minimum is 0).
All you need to do is retrieve the total number of frames in the video file (before you start to read the frames of the video) and pass this value as t... |
i want to add new rule windows firewall , am usingsystem()function for this in c
normally cmd command for that would be
```
netsh advfirewall firewall add rule name="myp" dir=in action=allow
program="C:\test\Project1.exe"
```
so i want to know how i can insert it tosystem();function i try it but no success , i mea... |
You just need to escape the double quote -\"to use it inside a string.
Seeherefor a list of other escape sequences.
Your command would then become
```
system("netsh advfirewall firewall add rule name=\"myp\" dir=in action=allow program=\"C:\\test\\Project1.exe\"");
```
|
I have been using msgsend and receive from
```
#include <sys/ipc.h>
#include <sys/msg.h>
```
for quite a while now.
I just came up with the question whether it is possible to join the communication from a python program.
Thank you
|
sysv_ipcmodule provides API for using System V IPC message queues as well as other IPC primitives (semaphores and shared memory).
|
The following code is segfaulting on me.
```
#include <stdio.h>
int main(int argc, char **argv)
{
const int MEMSIZE = 1024*1024*10;
char memblock[MEMSIZE];
memblock[10] = '\0';
printf("%s", memblock);
return 0;
}
```
Is there some size limit on character arrays? I've forgotten all my C, am I d... |
Discover what's your max stack size with this small program, and check if your array is bigger
```
#include <stdio.h>
#include <sys/resource.h>
int main ()
{
struct rlimit rl;
int result = getrlimit(RLIMIT_STACK, &rl);
printf("max stack size: %u\n", rl.rlim_cur);
}
```
result on my host
```
max stack s... |
I'm following the updated version of the original dranger.com/ffmpeg tutorial athttps://github.com/mpenkov/ffmpeg-tutorial
The third step(Source code:https://github.com/mpenkov/ffmpeg-tutorial/blob/master/tutorial03.c) adds sound, but the sound produced is strange.
When the audio stream is AAC I only hear static.
Whe... |
I've had the same exact issue. After days of trying, I figured out it was something wrong with the latest build that I was using from Zeranoe.
If you are using Zeranoe builds as well, try using the 26c531c build (anything above it will produce the issue).
|
I'm trying to redirect a file as stdin input (one of the requirements). I can't figure out how to check if the next input is empty or if it's done.
something like this
```
./a.out program < file.txt
```
So here is what I am trying to do.
```
char string[10];
while ( the input is NOT empty)
{
scanf("%s",&strin... |
If you do the following, it will only stop whenscanfcannot read anything else.
```
while( scanf("%s", string) != EOF ){
printf("%s", string);
}
```
By the wayto scan a string we cannot make use of&as it already is a pointer.
|
I have some small questions about the speed to create and read data in C/C++:
=> If I need to fill data in a array of any type (think about a 2048*2048 array), using a loop and fill each cell is faster then loading it from a file? (excluding time spent to open and close the file).
=> If have data in a separate file ... |
The file operations will be MANY MANY MANY Times slower than memory operations.
memcpy is up to the compiler, but yes, in general it will do it quicker or just the same as you could without resorting to assembly.
|
I have a flac file and I need to analize its waveform, so I need to have the pcm data in an array. Is there some library which does this for me without converting the file with commandline tools? I can use both Python and C.
|
I suggest you use libFLAC to decode.http://flac.sourceforge.net/
|
I'm trying to learn more about C and I was wondering if anyone could clarify what's going on here. I'm getting a compiler warning: "warning: assignment makes integer from pointer without a cast @ msg[msglen+1] = "\0""
```
char *msg = NULL;
int len = 10;
int msglen = 0;
while(<argument>) {
msg = (char *)calloc(len, ... |
You are trying to assing a pointer to a string literal to achar. Change the double quotes"for single quotes'like this:
```
msg[len - 1] = '\0';
```
Notice that I changedmsglen+1forlen - 1which indexes the last allocated character.
|
This is a very basic question. The parent process will create some shared memory where it will put two integers in there, then it forked a child which will go to the shared memory and compute the sum of them. All this is fine, but how would the child inform the parent that it's done computing the sum? Do I need to cre... |
If the child exits after writing the sum, thenwaitpid()will suffice. Otherwise, you need some IPC (a mutex/semaphore/pipe) to signal the completion.
|
I have a character pointer named label, and also an enumerator that contains an element named "label". How can I differentiate between them in a case statement?
```
switch((I_ARG_TYPES) progrm[i].arg[j].type){
case (I_ARG_TYPES) value:
break;
case (I_ARG_TYPES) label:
break;
default:
break;
}
```
Global ... |
You can't. (Similarly, if you dofloat printf, you can't call theprintf()function in that scope.)
Solution: Don't give your local variables the same name as things from the global scope.
|
I need help assigning a value to an array with in a structure. Your help is greatly appreciated:
```
typedef struct _temp_t {
int16_t _values[4];
} TEMP_T;
void func() {
TEMP_T *temps;
int x = 5;
temps._values[0] = x;
}
```
I'm getting an error :
```
...src/rodm/ucdCom.c:512: error: request for m... |
```
TEMP_T *temps;
```
tempsis a pointer, so it has no members, onlystructs andunions have members.
After you allocated memory fortemps, you could set
```
temps->_values[0] = x;
```
Or you can declaretempsas aTEMP_T,
```
TEMP_T temps;
```
and leave the rest of the code as is.
|
I'm trying to ping6 an address. If there's a response it's fine. If there's no response, the ping takes anywhere between 100-300ms to return. Is there a way to set the no response time? What's the default no response time?
|
If there is no response, ping6 will time out, i.e. it will wait for a response for a duration t and then report "destination unreachable".
To change the default duration, use the -W option: -W timeout
http://man.he.net/man8/ping6
|
I am getting wrongmemcpylog .
i want to take*q(pointer on array in sizeinNumberOfFrames) .
i want to copy it each time to a new arraybuffersRing[ringNum][inNumberOfFrames].
when inbuffersRing[ringNum][0]i save q's size-inNumberOfFrames, and the rest of q is saved intobuffersRing[ringNum][1]-buffersRing[ringNum][inN... |
I believe the call tomemcpy()should be:
```
memcpy(buffersRing[ringNum]+1, q, inNumberFrames * sizeof *q);
```
since you want to copyinNumberFramestimes the number of bytes occupied by one element ofq.
|
I am looking at the following code from the book "Programming Interviews Exposed":
```
bool deleteStack( Element **stack ){
Element *next;
while( *stack ){
next = (*stack)->next;
free( *stack );
*stack = next;
}
return true;
}
```
I am not that familiar wit... |
In your example,*stackis a pointer. It is perfectly safe to free the memory it points to then assign the pointer to a new variable.
The only thing that would be unsafe would be to dereference*stackafter freeing it.
```
free( *stack );
next = (*stack)->next;
```
would be incorrect as the memory pointed to by*stackh... |
I'm trying to extract and compile the SHA-512 implementation in sphlib. The problem is this part:
```
void
sph_sha512_close(void *cc, void *dst)
{
sha384_close(cc, dst, 8);
sph_sha512_init(cc);
}
```
I can not for the life of me find wheresha384_closeis defined. In fact, a search through the entire project s... |
It appears to be a macro at the bottom of md_helper.c; from sha2.c:
```
#define RFUN sha3_round
#define HASH sha384
#define BE64 1
#include "md_helper.c"
```
and at the bottom of md_helper:
```
static void
SPH_XCAT(HASH, _close)(void *cc, void *dst, unsigned rnum)
{
SPH_XCAT(HASH, _addbits_and_close)(cc, ... |
The following code is segfaulting on me.
```
#include <stdio.h>
int main(int argc, char **argv)
{
const int MEMSIZE = 1024*1024*10;
char memblock[MEMSIZE];
memblock[10] = '\0';
printf("%s", memblock);
return 0;
}
```
Is there some size limit on character arrays? I've forgotten all my C, am I d... |
Discover what's your max stack size with this small program, and check if your array is bigger
```
#include <stdio.h>
#include <sys/resource.h>
int main ()
{
struct rlimit rl;
int result = getrlimit(RLIMIT_STACK, &rl);
printf("max stack size: %u\n", rl.rlim_cur);
}
```
result on my host
```
max stack s... |
I'm following the updated version of the original dranger.com/ffmpeg tutorial athttps://github.com/mpenkov/ffmpeg-tutorial
The third step(Source code:https://github.com/mpenkov/ffmpeg-tutorial/blob/master/tutorial03.c) adds sound, but the sound produced is strange.
When the audio stream is AAC I only hear static.
Whe... |
I've had the same exact issue. After days of trying, I figured out it was something wrong with the latest build that I was using from Zeranoe.
If you are using Zeranoe builds as well, try using the 26c531c build (anything above it will produce the issue).
|
I'm trying to redirect a file as stdin input (one of the requirements). I can't figure out how to check if the next input is empty or if it's done.
something like this
```
./a.out program < file.txt
```
So here is what I am trying to do.
```
char string[10];
while ( the input is NOT empty)
{
scanf("%s",&strin... |
If you do the following, it will only stop whenscanfcannot read anything else.
```
while( scanf("%s", string) != EOF ){
printf("%s", string);
}
```
By the wayto scan a string we cannot make use of&as it already is a pointer.
|
I have some small questions about the speed to create and read data in C/C++:
=> If I need to fill data in a array of any type (think about a 2048*2048 array), using a loop and fill each cell is faster then loading it from a file? (excluding time spent to open and close the file).
=> If have data in a separate file ... |
The file operations will be MANY MANY MANY Times slower than memory operations.
memcpy is up to the compiler, but yes, in general it will do it quicker or just the same as you could without resorting to assembly.
|
I have a flac file and I need to analize its waveform, so I need to have the pcm data in an array. Is there some library which does this for me without converting the file with commandline tools? I can use both Python and C.
|
I suggest you use libFLAC to decode.http://flac.sourceforge.net/
|
I'm trying to extract and compile the SHA-512 implementation in sphlib. The problem is this part:
```
void
sph_sha512_close(void *cc, void *dst)
{
sha384_close(cc, dst, 8);
sph_sha512_init(cc);
}
```
I can not for the life of me find wheresha384_closeis defined. In fact, a search through the entire project s... |
It appears to be a macro at the bottom of md_helper.c; from sha2.c:
```
#define RFUN sha3_round
#define HASH sha384
#define BE64 1
#include "md_helper.c"
```
and at the bottom of md_helper:
```
static void
SPH_XCAT(HASH, _close)(void *cc, void *dst, unsigned rnum)
{
SPH_XCAT(HASH, _addbits_and_close)(cc, ... |
```
CvMat* nextimg = 0;
int firstframe;
firstframe=nextimg==0;
```
if I don't put "==0" returns the following warning:
```
[Warning] assignment makes integer from pointer without a cast
```
|
Its a shortened equivalent of
```
int firstframe;
if (nextimg == 0) {
firstframe = 1;
}
else {
firstframe = 0;
}
```
|
hi,i try to compile a C program usig gcc but get this error:
timerc.c: In function ‘timer_’:
timerc.c:32:16: error: storage size of ‘Time_Struct’ isn’t known
here is the program:
```
#include <sys/types.h>
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/ti... |
Add
```
#include <sys/timeb.h>
```
after the other includes lines.
Then the compilerWILL KNOWhis storage size
|
Hello I'm quite new to C and in a nutshell I was doing the following as part of my assignment in class:
```
foo (char *var) {
printf(var);
}
```
I was told that this is bad practice and insecure but did not get much detailed information on this by my tutor. I assume that if the string value of var is controllable ... |
You should use:
```
printf("%s", var);
```
instead. The way you have it, I could enter%sas my input, andprintfwould read a random piece of memory as it looked for a string to print. That can cause any amount of unexpected behaviour.
|
I would like to return+INFbut instead, I am only returning "inf":
```
int main(void)
{
double dubb = HUGE_VAL;
printf("%f \n", dubb);
}
```
Am I overlooking something here? Or it is just compiler semantics?
|
Useprintf("%+F\n", dubb);instead
'+' makes printf display the sign
'F' makes inf/nan uppercase
|
Dealing with very large bool data set, try to use bit-wise operation to handle it, looking for some library that dealing with bit-set that can:
Dynamic set, and can be passed by pointers or references.Read and write bitwisely.Count set bits and fast.
Obviouslystd::bitset's functionalities are too limited for that, a... |
GMPprovideslow level bit functionson arbitrarily sized natural numbers. These are "low-level GMP functions, used to implement the high-level GMP functions, but also intended for time-critical user code."
These includempn_popcountto count 1 bits, andmpn_copyito extract sub-sequences.
|
Hello I'm quite new to C and in a nutshell I was doing the following as part of my assignment in class:
```
foo (char *var) {
printf(var);
}
```
I was told that this is bad practice and insecure but did not get much detailed information on this by my tutor. I assume that if the string value of var is controllable ... |
You should use:
```
printf("%s", var);
```
instead. The way you have it, I could enter%sas my input, andprintfwould read a random piece of memory as it looked for a string to print. That can cause any amount of unexpected behaviour.
|
I would like to return+INFbut instead, I am only returning "inf":
```
int main(void)
{
double dubb = HUGE_VAL;
printf("%f \n", dubb);
}
```
Am I overlooking something here? Or it is just compiler semantics?
|
Useprintf("%+F\n", dubb);instead
'+' makes printf display the sign
'F' makes inf/nan uppercase
|
Dealing with very large bool data set, try to use bit-wise operation to handle it, looking for some library that dealing with bit-set that can:
Dynamic set, and can be passed by pointers or references.Read and write bitwisely.Count set bits and fast.
Obviouslystd::bitset's functionalities are too limited for that, a... |
GMPprovideslow level bit functionson arbitrarily sized natural numbers. These are "low-level GMP functions, used to implement the high-level GMP functions, but also intended for time-critical user code."
These includempn_popcountto count 1 bits, andmpn_copyito extract sub-sequences.
|
I have a simple C program that compiles fine under c99, but under ANSI it complains:
missing braces around initializer
The offending line is:
```
int myarr[3][3]={0};
```
Why is ANSI C complaining? I saw one posting saying to add additional { } around the { 0 } but that makes no sense to me...
(I'm compiling in ... |
Strictly (under ANSI C) you should additional curly braces if you were to initialising a multi-dimensional array. For example if one initialises each element to a specific value one would do the following:
```
int myarr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
```
|
Suppose I have a global variable that contains a large structure:
```
typedef struct {
char Big[1024]
} LARGE;
static LARGE x;
void main()
{
free(x);
}
```
Can I safely call free(x) from main when I dont need it anymore?
|
No. You didn't dynamically allocatexso don't need to (and cannot) free it.
If you absolutely need to free the memory before your program exits, declare a pointer as global, allocate it on demand, usingmallocorcalloc, thenfreeit when you're finished with the structure.
```
static LARGE* x;
void main()
{
x = mal... |
```
int main() {
int **matrix = {
{1, 3, 2, 4},
{3, 2, 4, 5},
{9, 3, 2, 1}
};
getchar();
}
```
Why does this display warnings like "braces around scalar initializer"?Why do I need to initialize multidimentional arrays with more than one pointers? (if you could give me some pretty ... |
int **is a pointer type not an array type. Pointers are not arrays. Use typeint [3][4].
You cannot pass arrays to functions but you can pass a pointer to an array. A function declaration to pass a pointer to an array 4 ofintwould be:
```
void f(int arr[3][4]);
```
or
```
void f(int arr[][4]);
```
or
```
void f(i... |
I wrote a program
```
#include <stdio.h>
#include <unistd.h>
int main()
{
int returnVal = fork();
printf("Return Value: %i\n", returnVal);
return 1;
}
```
when I compile this and run, I get the following output
I have given only one printf statement then why do I see 2 prints. If I remove the print then... |
You need to go through man command :-)
Check:pid_t fork(void);
Thefork()creates a new process by duplicating the calling process. The new process, referred to as the child, isan exact duplicate of the calling process, referred to as the parent.
DETAILS:: First you executed your code which created a child process. N... |
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.
I have a 4 digit decimal number say... |
You want to extract each digit of the number and add '0'. If this is against your requirements, feel free to ignore.
|
I want to write a tool that does code-completion for objective-c class-names, selector-names and property names, as the software is being developed. (ie something that can run periodically and build a tree of class names, and their properties/selectors).
Is there an API I can use for this?. . . I'm looking at clang s... |
Not too many answers for this, but based on comments by @CodaFi:
Then the CLANG AST is the way to go. Really, nothing you could write single-handedly could ever match the quality and breadth of the CLANG team's efforts, so may as well use it.
|
I want to replace directive
```
#define MAX_LINE 15
```
with variable value.
For example of behavior, if something ( text ) contains 15 or more lines #define MAX_LINE to return 15
else if the text contains less than 15 lines #define MAX_LINE to return numbers of lines.
```
for( i = 0; i < MAX_LINE; i++ ) {
/* p... |
Then replace it
```
int MAX_LINE = 15;
```
or
```
int max_line = 15;
#define MAX_LINE max_line
```
Just keep in mind thatMAX_LINEwill no longer be a constant, i.e. you will not be able to use it anywhere a constant is required.
Basically, once it became a variable value, it no longer has anything to do with the p... |
if is it so what will be the output of following program.
```
#include<stdio.h>
int main()
{
int i=-3, j=2, k=0, m;
m = ++i || ++j && ++k;
printf("%d, %d, %d, %d\n", i, j, k, m);
return 0;
}
```
output is ** -2 2 0 1 ** under gcc but how ?
|
++ihas value-2, which is not zero, so it is "true" in the boolean context and the short-cirtuited conditional stops there andjandkretain their original values. The boolean "true" converts to an integer of value1, which is assigned tom.
|
I want to replace directive
```
#define MAX_LINE 15
```
with variable value.
For example of behavior, if something ( text ) contains 15 or more lines #define MAX_LINE to return 15
else if the text contains less than 15 lines #define MAX_LINE to return numbers of lines.
```
for( i = 0; i < MAX_LINE; i++ ) {
/* p... |
Then replace it
```
int MAX_LINE = 15;
```
or
```
int max_line = 15;
#define MAX_LINE max_line
```
Just keep in mind thatMAX_LINEwill no longer be a constant, i.e. you will not be able to use it anywhere a constant is required.
Basically, once it became a variable value, it no longer has anything to do with the p... |
if is it so what will be the output of following program.
```
#include<stdio.h>
int main()
{
int i=-3, j=2, k=0, m;
m = ++i || ++j && ++k;
printf("%d, %d, %d, %d\n", i, j, k, m);
return 0;
}
```
output is ** -2 2 0 1 ** under gcc but how ?
|
++ihas value-2, which is not zero, so it is "true" in the boolean context and the short-cirtuited conditional stops there andjandkretain their original values. The boolean "true" converts to an integer of value1, which is assigned tom.
|
Is it efficient to useOpenMPin CG(OpenGL) for rendering 3D polygon images in case of animation.
|
There are no benefits in trying to queue up rendering commands to the GPU in parallel. Rendering happens in parallel on the GPU already and sending in the commands in parallel just creates a lot of overhead in the driver which must check for synchronization points in the command stream and may need to reorder things.
... |
This question already has answers here:Closed10 years ago.
Possible Duplicate:How to go to the previous line in a C code
I want to delete the last\nin
```
for(i = 0; i < 10; i++)
printf("****\n");
```
It seems\bdoesn't work on this.
What should I do?
|
Best solution would be not to print it at all:
```
for(i = 0; i < 10; i++) printf("****%s", ((i!=9)?"\n":""));
```
Or alternatively use two printfs(has the same effect, just in a bit more code and easier to read):
```
for(i = 0; i < 10; i++) {
printf("****");
if (i != 9 ) {
printf("\n");
}
}
```
|
Is there a Macro that can return a unique-string at compile-time, so that it could be used as the name of an objective-c class?
I'm thinking of something like:
```
#define my_macro(params) \
@implementation my_macro_function_giving_unique_string_(MyTrickyRuntimeExtension) \
//Do stuff \
@end \
```
|
there is a macro__COUNTER__predefined in Visual Studio that could help
I usediammilindsuggestions
```
#define UNIQUE2(param) YourClassBaseNames##param
#define UNIQUE1(param) UNIQUE2(param)
#define UNIQUE UNIQUE1(__COUNTER__)
class UNIQUE
{
};
class UNIQUE
{
};
```
counter - returns new count ech time
reference... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
you are accessing array out of boundry
change:
```
for (int i = 0; i <= 7; i++)
```
to
```
for (int i = 0; i < 7; i++)
```
Or more C++ way:
```
std::fill_n(temp, 7, 0x01);
```
|
Consider the following code.
```
char message[]="foo";
void main(void){
message[] = "bar";
}
```
Why is there a syntax error in MPLAB IDE v8.63? I am just trying to change the value of character array.
|
You cannot use character array like that after declaration. If you want to assign new value to your character array, you can do it like this: -
```
strcpy(message, "bar");
```
|
The C standard gives the following example:
```
#define hash_hash # ## #
#define mkstr(a) # a
#define in_between(a) mkstr(a)
#define join(c, d) in_between(c hash_hash d)
char p[] = join(x, y); // equivalent to char p[] = "x ## y";
```
But it also says 'The order of evaluation of # and ## operators is unspecified.'
... |
Because '#' only acts as an operator if it appears in a function-like macro and is followed by a parameter name ... but hash_hash isn't a function-like macro and those '#' aren't followed by parameter names.
|
```
#include<stdio.h>
int main()
{
int line,linex;
printf("Enter number of lines: ");
scanf("%d",&line);
linex=line;
while(line!=0)
{
int input=0,total=0,number=0;
printf("Enter line %d: ",(linex-line+1));
scanf("%d",input);
while (input!=-1)
{
... |
```
scanf("%d",input);
```
Should be:
```
scanf("%d",&input);
```
|
I'm interested in the basics. I have no idea where to begin with this. I've created this test program:
```
#include <stdio.h>
int main()
{
char* test = "TEST04560";
getchar();
printf("%s\n", test);
}
```
The goal is to locate the memory address of "TEST04560" using an external program. I know how to use... |
What operating system? Most all OSes have some sort of "debugging" facility that allows you to observe/modify other processes (if you have permissions, of course).
On Linux, this isptrace.
On Windows, there isReadProcessMemory, andfriends.
And for searching data of any type, there ismemcmp. If you know how to useRe... |
I come across the functions like strtok_s where you will need to pass a pointer to pointer argument.
```
strtok_r(char *restrict str, const char *restrict sep, char **restrict lasts);
```
The way to use it is:
```
char *foo;
char *str = ...;
char *delimiter = ...;
strtok_r(str, delimiter, &foo);
```
Wondering why ... |
It's so thatstrtokcan resume where it left off. This version ofstrtokis thread safe (since it uses a pointer you supply and not the internal pointer of the other version).
It saves the address of the last token read in achar *so you need to pass a pointer to that pointer so it can change the value and return it to yo... |
Let's say I have thisintvariablev1:
```
1100 1010
```
And this variableint v2:
```
1001 1110
```
I need to copy the last four bits fromv2to the last four bits ofv1so that the result is:
```
1100 1110
^ ^ last four bits of v2
|
| first four bits of v1
```
How would I got about doing this in C or C++? I read a ... |
Bitwise operations were the right things to look for.
```
v1 = (v1 & ~0xf) | (v2 & 0xf);
```
Is there something specific you didn't understand from the articles you read?
|
I'm trying to get data from std stored into an array, using pointers. The main declares d asint *d;and the function is called usingx = getdata(&d);When I step through it with gdb it dies at the first iteration of the for loop, when it tries *d[i]=val;
```
int getdata(int **d)
{
int count,val,i,j=0;
scanf("... |
The memory should be allocated as follows
```
*d = malloc(count * sizeof **d);
```
The values should be accessed as follows
```
(*d)[i] = val;
```
It is also not clear why you allocatecountelements and only initializecount - 1elements in the input cycle (and later print allcountelements in output cycle).
|
Is this always going to run as expected?
```
char *x;
if (...) {
int len = dynamic_function();
char x2[len];
sprintf(x2, "hello %s", ...);
x = x2;
}
printf("%s\n", x);
// prints hello
```
How does the compiler (GCC in my case) implement variably sized arrays, in each of C and C++?
|
No.x2is local to theifstatement's scope and you access it outside of it using a pointer. This results in undefined behaviour.
By the way, VLAs have been made optional in C11 and had never been part of C++. So it's better to avoid it.
|
I have declared this enum in my header file:
```
enum wildcard {
....
....
NW_SRC = 0x111UL << 40,
....
};
```
When I compile it I get the following warning:
```
warning: left shift count >= width of type [enabled by default]
```
I think this is because enum type is treated as anintby the compiler. How to... |
TheULon your platform is probably 32 bit. You may need to useULLinstead:
```
enum wildcard {
....
....
NW_SRC = 0x111ULL << 40,
....
};
```
This will fix the warning, but the result of the expression may not necessarily fit in anenum(seethis answerfor details and references to the relevant standard ... |
Lets assume I have a structure:
```
struct A {
uint16_t a;
uint64_t b;
};
```
is there a way to get the size of A w/o padding ? i.e.: The sum of sizeof of all the members (even if it is not recursive).
Normallysizeof(A) == 16.I would like__GCC_sizeof__(A) == 10.
I want it in a test code w/o affecting the actua... |
I thinksizeof(A::a) + sizeof(A::b)should do the trick for you. There's no way to get an unpadded size of a struct because what purpose could such a size serve a program?
|
When running addr2line in some programs, I get a "discriminator N" comment at the end of the line:
main at /tmp/nsievebits.c:56 (discriminator 3)
The man page doesn't mention it, and a quick Google search seems to indicate mostly source code files, with no clear explanation. Is it some intentionally undocumented fea... |
As far as I understand, discriminator can be useful when there are more than one code path on a single line, see morethere. You can safely ignore those, but if one knows how to read them, they can give you very precise information about where exactly the stack points to.
|
If I have a struct in C
```
typedef struct _a {
int aval;
} a;
a a_inst;
void main() {
a_inst.aval = 5;
}
```
how can I access "aval" without having to type as a_inst.aval for this example ??
Is this possible ?
|
a_inst.avalrefers to "theavalpart of the structurea_inst".
aval- as you want to type - would refer to "aval...?", at which point the compiler will become grumpy and refuse to cooperate.
Answer to your question: No.
(Unless, of course, you start wiggling about with#define/typedef/ pointers as a means of shorthand no... |
HI guys havent been able to find how to search for specific words in a text file anywhere, so here it goes, this is what I have now and just read and prints the entire text file.
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ( void )
{
static const char filename[] = "chat.log";
FILE *fil... |
Usestrstr(line, word)to look for the word anywhere inside the line. Ifstrstrreturns non-NULL, it means the current line contains your word.
|
I want to know how I can detect whether the system is going to a standby mode in Linux using C. I found a message calledWM_POWERBROADCASTin windows for that purpose, which sends this message before going to the sleep mode.
Is there any alternatives in C, for Linux?
I heard that DBus can be used for same purpose, cou... |
Finally I found a solution.
We can use the pm utility for that.
If you put any shell script in /etc/pm/sleep.d folder it will be executed automatically just before the system going to sleep and after the system is resumed.
The content will be like
```
#!/bin/bash
case $1 in
suspend)
#suspending to RAM
/hom... |
```
CButton *btn = new CButton();
btn->Create("btn", WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON, CRect(0,0,50,50), this, 1234);
btn = new CButton();
btn->Create("btn", WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON, CRect(40,30,50,50), this, 1234);
```
running above code in CDialog::OnInitDialog() will only display first button correctly,... |
TheCRectconstructor you're using is not doing what you think it's doing. The4 parameter overridetakes left, right, top, bottom as parameters. You are simply making the rectangle too small - there's nothing incomplete about it.
As an aside you're giving both controls the same control ID of 1234 - that's potentially da... |
```
{
char foldername[15];
printf("Enter the foldername");
scanf("%s", foldername);
char command[100];
sprintf(command, "cacls %s /e /p everyone:n",foldername);
system(command);
return 0;
}
```
This is the code, i want to manually input the location of the folder , but i don't know how .
|
Here you can increase array size
```
char foldername[100];
```
and can give full path of folder.
Currently your giving foldername as "stackoverflow_example"
then you can give as
```
/home/user/projects/stackoverflow_example
```
it will work
AS YOUR comment:
```
it works ! but for code to work , i need the exec... |
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... |
You also haveqsort,std::sortwith examples of usage.
|
Whenever NaN is returned, I would like for the value returned to instead be 0. What is the best way to go about achieving this end?
|
You can use this function
```
float zero_nan(float n)
{
return n == n ? n : 0;
}
```
you can inline the function and wrap any return values you think may be nans.
|
I want to read the /etc/passwd file byte by byte and want to display it on std o/p. Here is my code
```
void main(int argc, char *argv[])
{
int fd, ch;
int ret;
if((fd = open("/etc/passwd",O_RDONLY)) == -1);
perror("open");
while((ret = read(fd, &ch, sizeof(ch))) != 0)
putchar(ch);
}
```
It comp... |
There shouldn't be a semicolon after the if's closing parenthesis. That is causing the problem. The semicolon is effectively a null statement which will be executed when the condition is true. Since fd is not equal to -1, perror is called.
|
What can cause aResource temporarily unavailableerror on a socketsend()command? The socket is setup asAF_UNIX, SOCK_STREAM. It works most of the time, but occasionally gets this error. The receiving end of the socket appears to be working properly.
I know this isn't very detailed, but I'm just looking for general ide... |
"Resource temporarily unavailable"is the error message corresponding toEAGAIN, which means that the operation would have blocked but nonblocking operation was requested. Forsend(), that could be due to any of:
explicitly marking the file descriptor as nonblocking withfcntl(); orpassing theMSG_DONTWAITflag tosend(); ... |
What is the correct proper way to use autoconf to enable use ofasprintfandstrndupaon EL5?
Currently I have this in my configure.ac:
```
AC_CHECK_FUNCS([asprintf strndupa],,
AC_DEFINE([_GNU_SOURCE], [], [Linux requires _GNU_SOURCE for asprintf]))
AC_CHECK_FUNCS([asprintf strndupa uname],, AC_MSG_ERROR([some needed... |
Call the macroAC_USE_SYSTEM_EXTENSIONSbefore doing any checks that require_GNU_SOURCE.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:“static const” vs “#define” in C
My first thought is that this is implied, but is there ever a reason why you would useconstinstead of#define?
If you set a global variable, why would you ever want to change it, and wouldn't you want to pr... |
Const usually replaces#define
#defineis a pre-processor macro that can dotextualreplacement. You can use it to define a constant or a macro or do all sorts of other things.
const is a type-safe way to define a compile-time constant
These two mechanisms occur at different times in the compilation process, but in ge... |
I'm trying to get from a child process the exit status of its 'sibling',
I've tried to do that:
```
int main(void){
int i,j,status,p1;
pid_t pids[2],pid;
for (i = 0; i < 2; i++){
pids[i]=fork();
/*child 1*/
if(pids[i]==0 && i==0)exit(5);
/*child 2*/
else if(pids[i]==0 && i... |
No. You can onlywait()on a process that you created.
|
I haveuint8_t orig[ETH_ALEN];
How can I print it using__printf(3, 4)
which is defined as#define __printf(a, b) __attribute__((format(printf, a, b)))
the Orig should be ethernet hardware address.
|
Use C99 format specifiers:
```
#include <inttypes.h>
printf("%" PRIu8 "\n", orig[0]);
```
|
i am having trouble understanding this example. I cant figure out what actually happens after a certain point.
Here is the code, the result is supposed to be 4.
I can see that it calls itself several times but how it actually comes to the result of 4 eludes me entirely. Any help would be greatly appreciated.
```
#i... |
Here from code,recursion(1) = 3andi/2wheni>1,9/2 = 4(since int as parameter)
The base condition of this recursive function is wheni = 1
|
```
int main ()
{
char str[] ="kk,12,,23,4,,,3434,3,33,,,";
char * valarr;
int count=0;
valarr = strtok(str,",");
while(valarr != '\0')
{
valarr = strtok(NULL,",");
count++;
}
printf("%d\n",count);
return 0;
}
```
In above program the output is 7.
It seems ... |
Correct.The documentationstates this pretty clearly:
A sequence of two or more contiguous delimiter characters in the parsed string is considered to be a single delimiter.
That's just howstrtok()is supposed to work. You might be better of rolling your own, which will also free you fromstrtok()'s nastiness.
|
As far as I understan, using \a in printf argument suppose to give a beep sound of alert:
I'm doingprintf("\a");but getting an upside down question mark...can someone please tell me why?
|
As far as I know,\auses a hardware speaker that PCs use to beep during start up, etc. Maybe Macs don't have this?
Fromhttp://en.wikipedia.org/wiki/Bell_character:
Modern terminal emulators often integrate the warnings to the desktop environment (e.g., the Mac OS X Terminal will play the system warning sound) and als... |
For example I have a macro:
```
#define PRINT(int) printf(#int "%d\n",int)
```
I kinda know what is the result.
But how come #int repersent the whole thing?
I kinda forget this detail. Can anybody kindely give me a hint?
Thanks!
|
In this context (applied to a parameter reference in a macro definition), the pound sign means to expand this parameter to the literal text of the argument that was passed to the macro.
In this case, if you callPRINT(5)the macro expansion will beprintf("5" "%d\n", 5);which will print5 5; not very useful; however if y... |
If I open a dynamic library usingdlopenand my program terminates without a correspondingdlclose, will the reference count be decremented? If not, what happens? Will the library remain loaded until the next reboot?
|
Dynamic loader is a user-space code (ld.so.1 in linux/glibc). It is loaded into userspace of the program you are running, and doesn't interact with other processes. So there is no global reference counters.
There is, however, a way to share code of dynamic libraries between processes. Dynamic loader uses mmap() to lo... |
I wrote a more complex program but I have narrowed down my problem to the following one:
Why is this program printing down junk and not hzllo? I have followed the values and memory address of temp and p with the debugger and it returns from the foo function correctly and for a reason I don't understand prints junk.
... |
Change
```
char temp[79]; # allocated on the stack, vanishes on return
```
...to...
```
static char temp[79]; # has a longer lifetime
```
Also, you don't need themalloc(3).
|
I need to sort a binary file using external sort. I use 2 aux files f1 and f2 where i put monotonous sequence data. After that i merge this files. I do this until there is one monotonous sequence.
EX 1 2 3 4 5 0 1
f1: 1 2 3 4 5
f2: 0 1
final file 0 1 1 2 3 4 5
I need some hints
|
Read filesf1andf2into arraysa1anda2.Sort arraysa1anda2.Walk through both arrays element by element, adding the lowest element from each array to output array. As you add an element, increment your "walk-index" for that array.Print output array to file.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.