question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:Is main() really start of a C++ program?(12 answers)Closed10 years ago.
i have a question for you.
I need find out if i can use some function before or after main() function ended. I can't find some examples for C language.
Can you give me some advice or examples. Thanks a lot.... |
If you are using GCC, you can createconstrutors/destructorfunctions:
Theconstructorattribute causes the function to be called automatically before execution entersmain(). Similarly, thedestructorattribute causes the function to be called automatically aftermain()completes orexit()is called. Functions with these attri... |
I am trying to write an application for capturing stereo audio. My audio input has two channels(Stereo). I am writing this audio data into a wav file. Some times these audio channels are exchanging i.e, Left becomes right and right becomes left. This is happening only if i open and close the device file or turn off th... |
stereo PCM stored in a wav file is in an LR format. 'L' stands for left channel sample and 'R' for right channel sample. I guess you have a bug in retrieving or storing the PCM. Maybe sometimes you start with the right (correct) position in buffer and sometimes you start with the second sample. It's hard to tell witho... |
This question already has answers here:Are there any platforms where pointers to different types have different sizes?(7 answers)Closed10 years ago.
In C and C++, do I have the guarantee that all pointers have the same size in bytes, or in other words :
```
sizeof(void*) = sizeof(char*) = sizeof(int*) = ...
```
or ... |
No. There is no guarantee in the standard.
There are some exception is some systems. Although it's fixed in many typical systems and depends on the architecture of that system. For example in 32-bit systems pointers are 4 bytes.
By the way,uintptr_tcan hold pointers (Maybe we can assume it has the maximum size of a ... |
I'm making a wrapper for a C library. There is a method that changes 2 ints by the user giving 2 int pointers to the method. So if I havevoid changenums(int* a, int* b)what is a safe way to access this method in c#?
|
Declare the p/invoke like this:
```
[DllImport(@"mydll.dll")]
static extern void changenums(ref int a, ref int b);
```
And call it like this:
```
int a = 0;
int b = 0;
changenums(ref a, ref b);
```
|
what is the difference between this calls toimreadin openCV?On my local machine both of them work.
```
1) cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR);
2) cv::imread(filename, CV_LOAD_IMAGE_COLOR);
```
In the first case we convert a std::string to C style string.
In the second case we just pass a std:... |
The calls have the same effect.cv::imreadtakes aconst std::string&as first argument, so the first version would result in the creation of a temporarystd::stringobject, constructed from theconst char*returned byfilename.c_str().
|
This question already has answers here:Is main() really start of a C++ program?(12 answers)Closed10 years ago.
i have a question for you.
I need find out if i can use some function before or after main() function ended. I can't find some examples for C language.
Can you give me some advice or examples. Thanks a lot.... |
If you are using GCC, you can createconstrutors/destructorfunctions:
Theconstructorattribute causes the function to be called automatically before execution entersmain(). Similarly, thedestructorattribute causes the function to be called automatically aftermain()completes orexit()is called. Functions with these attri... |
I am trying to write an application for capturing stereo audio. My audio input has two channels(Stereo). I am writing this audio data into a wav file. Some times these audio channels are exchanging i.e, Left becomes right and right becomes left. This is happening only if i open and close the device file or turn off th... |
stereo PCM stored in a wav file is in an LR format. 'L' stands for left channel sample and 'R' for right channel sample. I guess you have a bug in retrieving or storing the PCM. Maybe sometimes you start with the right (correct) position in buffer and sometimes you start with the second sample. It's hard to tell witho... |
This question already has answers here:Are there any platforms where pointers to different types have different sizes?(7 answers)Closed10 years ago.
In C and C++, do I have the guarantee that all pointers have the same size in bytes, or in other words :
```
sizeof(void*) = sizeof(char*) = sizeof(int*) = ...
```
or ... |
No. There is no guarantee in the standard.
There are some exception is some systems. Although it's fixed in many typical systems and depends on the architecture of that system. For example in 32-bit systems pointers are 4 bytes.
By the way,uintptr_tcan hold pointers (Maybe we can assume it has the maximum size of a ... |
I'm making a wrapper for a C library. There is a method that changes 2 ints by the user giving 2 int pointers to the method. So if I havevoid changenums(int* a, int* b)what is a safe way to access this method in c#?
|
Declare the p/invoke like this:
```
[DllImport(@"mydll.dll")]
static extern void changenums(ref int a, ref int b);
```
And call it like this:
```
int a = 0;
int b = 0;
changenums(ref a, ref b);
```
|
what is the difference between this calls toimreadin openCV?On my local machine both of them work.
```
1) cv::imread(filename.c_str(), CV_LOAD_IMAGE_COLOR);
2) cv::imread(filename, CV_LOAD_IMAGE_COLOR);
```
In the first case we convert a std::string to C style string.
In the second case we just pass a std:... |
The calls have the same effect.cv::imreadtakes aconst std::string&as first argument, so the first version would result in the creation of a temporarystd::stringobject, constructed from theconst char*returned byfilename.c_str().
|
Is there a nice way to send a SIGUSR to a grandchild directly?
E.g. I have some process tree:
```
0
/ \
1 2
\
3
```
and need to send a signal from0to3.
I know I could save child's pid after forking and the use it withkill()like
```
pid = fork();
if (pid == 0) {
pid = fork();
if (... |
There is no direct communication between parent and grandchildren. The usual approach here is having the grandchild to store its PID somewhere on the filesystem (say, in /var/lib/myapp/grandchild.pid) and reading it back in the parent.
You can also use process groups on Linux, but they offer a coarse-grained approach... |
I have an audio streamer based on ffplay. It works great using ffmpeg 0.11 but when I use ffmpeg 1.0 or the latest 1.2 release the audio seems to be decoded or played weirdly.
Essentially it sounds like chipmunks with mp3 streams and with aac streams I hear tons of static barely hearing the actual stream and the actu... |
pCodecCtx->request_sample_fmt = AV_SAMPLE_FMT_S16
doesn't change the behavior! I didn't find any better solution than using swr_convert to convert audio sample from AV_SAMPLE_FMT_FLT to AV_SAMPLE_FMT_S16.
|
I want to read one line of the text file, save it to a buffer, send the buffer over a udp socket and then go and read the second line and so on..
So far, since I knew the data type of the text to be read from the text file, I had been using
fscanf()
to read each line from the text file. But now I don't know the dat... |
Here is a handy code I found to read data as binary
```
FILE *fp;
fp=fopen("c:\\test.bin", "r");
char *x = new char[10];
//size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
```
|
I have an integer array
```
int number[] = {1,2,3,4};
```
What can I do to get int x = 1234?
I need to have a c version of it.
|
```
x = 1000*number[0] + 100*number[1] + 10*number[2] + number[3];
```
This is basically how decimal numbers work. A more general version (when you don't know how long 'number' is) would be:
```
int x = 0;
int base = 10;
for(int ii = 0; ii < sizeof(number); ii++) x = base*x + number[ii];
```
Note - ifbaseis somethi... |
I only need to send a hexadecimal like this to a remote serial for the device to accept it.
2 byte hexadecimal I need to send is:
```
181E
```
I can telnet to the remote serial and send that command:
```
telnet x.x.x.x port
181E
```
I get a response back which is okay.
How can I do this in linux c?
I want to u... |
You need to send ahexadecimal string. So,
```
const char cmd[] = "181E";
err = write(socket, cmd, strlen(cmd));
```
|
I'm just trying to load the demo code into my RX62N, but the code doesn't compile. I get a lot of errors exactly like this one.
Error[Pe125]: expected a "(" C:\FreeRTOSV7.4.2\FreeRTOS\Source\queue.c 263
Which links here
```
if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE )
{
portYIEL... |
I realize now that I left a lot of stuff out of the question, but I've solved it. The demo code I tried to load was for the RSK not the RDK(which I have). Also the IDE was too old to load the correct workspace.
Once I did those two things it loaded and compiled successfully.
|
I accidentally declared an array without a length by writingenum foo bar[];, and gcc gave me the warning "array 'bar' assumed to have one element".
Is there any way to make gcc turn this into an error, instead of just warning me and assuming I meantenum foo bar[1]? I can't think of any circumstances under which I'd p... |
http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
You can use -Werror to turn all warnings into errors. I couldn't find an option to turn only that one into an error.
|
Simple code, eg:
```
void* print_my_address() {
printf("%p\n", .../* get the execution address of print_my_address */)
}
```
Thanks!
PS: gcc v4.7
Can I get the address by compiler?
|
The same way you'd do it for any other regular variable:
```
void print_my_address()
{
printf("%p\n", &print_my_address);
}
```
|
char label[10] = "Me"works, and to change the value oflabel, I'd have to do something like:
```
char * temp = "Not Me";
strcpy(label,temp);
```
My question is why is this invalid?
```
char label[] = "Me";
label = "Not me";
```
|
Because arrays are not assignable. You can create them, you can change theircontent, but the array itself cannot be modified to refer to a new chunk of memory.
|
Why does this code:
```
strcmp(myfunction(0), "OK");
```
where myfunction is defined like this:
```
char *myfunction(int p)
{
if (p == 0)
{
return("OK");
}
}
```
give the following error:
```
warning: passing argument 1 of 'strcmp' makes pointer from integer without a cast
```
|
Because the compiler doesn't know the definition formyfunction()at the time it is called.
Then the compiler presumes it returns an int ... and gives that message.
Solution: provide a prototype for the function (or its definition, which serves as a prototype) before calling it.
|
I am running a C program using DEVC++ and CodeBlocks in Windows and the code is not updating.
I just added a single printf message and it is not shown in the output.
I tried clean,rebuild,recompile, everything.
Please tell me what's going wrong.
|
Try adding a newline to your printf. Sometimes (with certain compilers), the output isn't flushed to screen until a newline is printed.
```
printf( "\n" );
```
|
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... |
```
if ((a = b > c ? d : e) == e) a++;
```
equals to:
```
if (b > c)
a = d;
else
a = e;
if (a == e)
a++;
```
Also have a look at:What does '?' do in C++?
|
I was wondering if it would be possible to use SSE in parallel with x87. So consider the following pseudo code,
1: sse_insn
2: x87_insn
Would the pipeline execute 1 and 2 in parallel assuming they can be executed in parallel?
|
In all modern (and older) processors, the x87 and SSE instructions use the same execution units, so it's UNLIKELY that you will benefit much from this sort of code. There may be very special cases where you can trick the processor into running for example a x87 divide in parallel with an SSE add, or something like tha... |
All the examples I can find check the return value against a NULL pointer, and yet in our code we are receiving a valid pointer. We know an exception has occurred because we have written to a log file before and after the failing line.
When we look at the return value it says "NoneType":returnValue->ob_type->tp_name... |
The call returned the None object in that case, and not NULL, indicating that there is no exception as far as that call is concerned.
If whatever you called used atry:/excepthandler, then the exception has already been caught and cleared; that is the purpose of such a handler. If you need the exception to propagate f... |
I tried to read the following line of 3 words in a file:
fruit|apple|lemon
```
char *type, *type2, *type3;
```
using this:fscanf(file, "%[^|]|%[^|]|%s", type, type2, type3);
but I am getting seg fault. anyone can help?
|
You need to make sure to allocate some space for the results. It appears from your example that type, type2, and type3 are all null. You need to point them at some storage on the heap or stack, like:
char type[64];
however be wary of buffer overflow here. Seethis other questionfor advice on how to avoid that.
|
```
#include<stdio.h>
char *getname()
{
static char name[30];
scanf("%s",name);
return name;
}
void main()
{
char * name1,*name2;
name1 = getname();
name2 = getname();
printf("%s %s\n",name1,name2);
}
```
Input:Jack Jill
Output:Jill Jill
I thought it should be Jack Jack since it stores... |
name1andname2point to the same object: the first element ofname.
As both pointersname1andname2have the same value, it is normal when you print the array you get the same result.
The lifetime of a static object is the entire execution of the program and the address of a static object does not change during the execut... |
I'm writing a few functions for getting and storing a user password. It's all working OK but is there any way of replacing what is typed at the prompt with an asterisk, for example?
This is fairly standard behaviour in windowed applications I've had a good look through the C libraries but all of the fgets/getc type f... |
Assuming POSIX:
```
struct termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
```
Then no user input will be echoed. Set back theECHOflag if you want to undo this.
|
Im'm loading the color of a pixel and writes a one-byte variable. When I want to read this color (for red pixel) should get the result: 255 However, the value is: 4294967296. From this it follows that the value has been recorded in 32-byte variable. Why does this happen?
```
struct RGBpix{
char R;
char G;
char B;
... |
charappears to be a signed type on your machine. Useunsigned charto avoid the sign extension.
|
I am really curious as tohowPython's interpreter makes an attributexout of a methodxthroughx=property(x). If I could take a look at theCcode, I would feel much better.
|
The type is defined in thedescrobject.cfile.
You can locate Python types like these by first looking for the function name inbltinmodule.c; in this case the following line defines theproperty()function:
```
SETBUILTIN("property", &PyProperty_Type);
```
then grep for thePyProperty_Typedefinition in theO... |
Just trying to wrap my head around IPP right now. Does anyone have any working C/C++ code for doing a FFT convolution on an image?
|
Example from here:
```
/* Sample C-code snipet for Example 1 using Intel® Integrated Performance Primitives (Intel® IPP): */
/* allocate and initialize specification structures */
ippsFFTInitAlloc_C_32fc(&FFTspec1_p, order, IPP_FFT_DIV_FWD_BY_N, ippAlgHintFast);
ippsFFTGetBufSize_C_32fc(FFTspec1, &BufSize);
Buf1_p =... |
```
#include<stdio.h>
char *getname()
{
static char name[30];
scanf("%s",name);
return name;
}
void main()
{
char * name1,*name2;
name1 = getname();
name2 = getname();
printf("%s %s\n",name1,name2);
}
```
Input:Jack Jill
Output:Jill Jill
I thought it should be Jack Jack since it stores... |
name1andname2point to the same object: the first element ofname.
As both pointersname1andname2have the same value, it is normal when you print the array you get the same result.
The lifetime of a static object is the entire execution of the program and the address of a static object does not change during the execut... |
I'm writing a few functions for getting and storing a user password. It's all working OK but is there any way of replacing what is typed at the prompt with an asterisk, for example?
This is fairly standard behaviour in windowed applications I've had a good look through the C libraries but all of the fgets/getc type f... |
Assuming POSIX:
```
struct termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);
```
Then no user input will be echoed. Set back theECHOflag if you want to undo this.
|
Im'm loading the color of a pixel and writes a one-byte variable. When I want to read this color (for red pixel) should get the result: 255 However, the value is: 4294967296. From this it follows that the value has been recorded in 32-byte variable. Why does this happen?
```
struct RGBpix{
char R;
char G;
char B;
... |
charappears to be a signed type on your machine. Useunsigned charto avoid the sign extension.
|
I am really curious as tohowPython's interpreter makes an attributexout of a methodxthroughx=property(x). If I could take a look at theCcode, I would feel much better.
|
The type is defined in thedescrobject.cfile.
You can locate Python types like these by first looking for the function name inbltinmodule.c; in this case the following line defines theproperty()function:
```
SETBUILTIN("property", &PyProperty_Type);
```
then grep for thePyProperty_Typedefinition in theO... |
Just trying to wrap my head around IPP right now. Does anyone have any working C/C++ code for doing a FFT convolution on an image?
|
Example from here:
```
/* Sample C-code snipet for Example 1 using Intel® Integrated Performance Primitives (Intel® IPP): */
/* allocate and initialize specification structures */
ippsFFTInitAlloc_C_32fc(&FFTspec1_p, order, IPP_FFT_DIV_FWD_BY_N, ippAlgHintFast);
ippsFFTGetBufSize_C_32fc(FFTspec1, &BufSize);
Buf1_p =... |
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... |
My company use Qt framework.
Adobe Photoshop (AFAIK) and other popular Windows programs are using it.
Qt is modern, well documented and tested. Just try it and enjoy :)
|
Usingftw()function, I have a list of paths I want to write on a file.
I need only paths starting from a specified folder, like:
```
source folder: /Users/me
subfolder1: /Users/me/school
subfolder2: /Users/me/school/english
result I need: /school
/school/english
```
Is there a way to "subtrac... |
If you are sure that the prefix is there, just skip it:
```
char *result = subfolder + strlen(source);
```
|
I have a C program that outputs some information to the console and then goes to infinite loop. I need to run the program on the background and redirect the output to a log file. The redirection works if the program does not have the infinite loop, what nothing is written if the program have the infinite loop.
for ex... |
Welcome to the world of buffered input/output.
Use either non-buffered syscalls (open,read,write) or flush the stream.
Edit: Also, it might be a filesystem issue. Do asyncon the file system.
|
This is a small part of my code, where I'm printing the duplicates found in an array. The problem is that it prints each duplicate occurrence more than once. Ex. the array {1,2,3,4,5,6,7,8,9,0,2,2) prints
value 2 at position 1 is also at position 10
value 2 at position 1 is also at position 11
value 2 at position 10 ... |
If you're allowed to modify your array, consider removing a value from the array once you have identified it as a duplicate (e.g., set it to -1 or some other value outside your normal range of inputs).
|
i am getting errors while compiling a simple C program.
```
#include<stdio.h>
void main()
{
int i=5;
printf("I value is %d",i);
}
```
The Errors are ..
```
/usr/local/bin/ld: this linker was not configured to use sysroots
collect2: error: ld returned 1 exit status
```
my gcc version is..
```
gcc (Ubuntu/Lin... |
Following the tutorial below, the suggested to insert the path /usr/bin to the environment variable in the following way.
```
export PATH="/usr/bin:$PATH".
```
https://askubuntu.com/questions/347466/configure-error-c-compiler-cannot-create-executables
this worked for me.
|
I have 2D arrays in header files, for which I declared the sizes of both:
```
int numPaths = 2;
int pathLength = 11;
double x[numPaths][pathLength] = {{62, 114, 0, 73, 55, 21, -28, -93, 0, 0, 0},{-90, 208, 0, 4, 7, 10, 12, 13, 11, -198, -147}};
double y[numPaths][pathLength] = {{55, 88, 0, -42, 12, 45, 54... |
numPathsandpathLengtharen't constants, just like the error message says. You need:
```
#define numPaths 2
#define pathLength 11
```
Some compilers will let you get away with:
```
const int numPaths = 2;
const int pathLength = 11;
```
As an extension.
|
Is there an easy(ish) way to replace all non alpha characters from a character array with a space such as you might do with the bash command below?
sed 's/[^a-zA-Z]/ /g'
The only thing I can think of is to loop through the char array & do a compare & replace on a character by character basis. I don't know if there ... |
As far as I know, there isn't a way to do this that is better than O(n) anyways. Even if there was such a function or even a regex engine, it will probably less efficient than the simple linear complexity solution. You can just loop through the array and anything less than 'A' or greater than 'z' gets set to ' '.
``... |
In linux code,
I remember hearing there is a full memory barrier around mutex_lock().
I want to make sure whether it is around sem_xxx also.
|
The authoritative answer is here:
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
Applications shall ensure that access to any memory location by more than one thread of control (threads or processes) is restricted such that no thread of control can read or modify a memory location ... |
i am getting errors while compiling a simple C program.
```
#include<stdio.h>
void main()
{
int i=5;
printf("I value is %d",i);
}
```
The Errors are ..
```
/usr/local/bin/ld: this linker was not configured to use sysroots
collect2: error: ld returned 1 exit status
```
my gcc version is..
```
gcc (Ubuntu/Lin... |
Following the tutorial below, the suggested to insert the path /usr/bin to the environment variable in the following way.
```
export PATH="/usr/bin:$PATH".
```
https://askubuntu.com/questions/347466/configure-error-c-compiler-cannot-create-executables
this worked for me.
|
I have 2D arrays in header files, for which I declared the sizes of both:
```
int numPaths = 2;
int pathLength = 11;
double x[numPaths][pathLength] = {{62, 114, 0, 73, 55, 21, -28, -93, 0, 0, 0},{-90, 208, 0, 4, 7, 10, 12, 13, 11, -198, -147}};
double y[numPaths][pathLength] = {{55, 88, 0, -42, 12, 45, 54... |
numPathsandpathLengtharen't constants, just like the error message says. You need:
```
#define numPaths 2
#define pathLength 11
```
Some compilers will let you get away with:
```
const int numPaths = 2;
const int pathLength = 11;
```
As an extension.
|
Is there an easy(ish) way to replace all non alpha characters from a character array with a space such as you might do with the bash command below?
sed 's/[^a-zA-Z]/ /g'
The only thing I can think of is to loop through the char array & do a compare & replace on a character by character basis. I don't know if there ... |
As far as I know, there isn't a way to do this that is better than O(n) anyways. Even if there was such a function or even a regex engine, it will probably less efficient than the simple linear complexity solution. You can just loop through the array and anything less than 'A' or greater than 'z' gets set to ' '.
``... |
In linux code,
I remember hearing there is a full memory barrier around mutex_lock().
I want to make sure whether it is around sem_xxx also.
|
The authoritative answer is here:
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11
Applications shall ensure that access to any memory location by more than one thread of control (threads or processes) is restricted such that no thread of control can read or modify a memory location ... |
I write a program to swap 2 variables using XOR.
```
var1 = var1 ^ var2;
var2 = var2 ^ var1;
var1 = var1 ^ var2;
```
I Compile it to get the Assembly Output along with others
```
$ gcc Q1.c -save-temps -o Q1
```
I Get this Output in the Assembly form...
```
movl 24(%esp), %edx
movl 28(%esp), %eax
xorl %e... |
%espis the stack pointer.24(%esp)reads the value at address%esp+ 24.
|
It is well defined C++ to pass std::vector to C APIs that expect an output array like so because std::vector is contiguous:
```
std::vector<char> myArray(arraySize);
cStyleAPI(&myArray[0], arraySize);
```
Is it safe to pass std::string in the same manner to C APIs? Is there any guarantee in standard C++03 that std::... |
If the C API function requires read-only access to the contents of thestd::stringthen use thestd::string::c_str()member function to pass the string. This is guaranteed to be a null terminated string.
If you intend to use thestd::stringas anoutparameter, C++03 doesn't guarantee that the stored string is contiguous in ... |
I am just starting out with Objective-C,and with C in general,so I suppose this is a C question as well.It's more of awhyquestion rather than ahowquestion.
I noticed that while dividing two integers ,the decimal part is rounded down to0even though the result is a float.The sources I followed suggest the following app... |
By promoting the numerator to float, you require the denominator to be promoted, as well. However, when you place the two in parens, then you are telling the compiler to do the work as integersthencast to float.
|
I have a C code that uses OpenMP and 128-bit integers. For the 128-bit integers, I'm using the __int128_t and __uint128_t extensions provided by GCC. I'm looking foranyother compiler that can also compile this kind of code.
Clang supports __uint128_t, but not OpenMP. ICC supports OpenMP, but not 128-bit integers(at l... |
ICC didn't support __int128_t with version 12 (when this question was posted), but supported was added with versions 13 onwards, see:128-bit integers supporting +, -, *, /, and % in the Intel C Compiler?
|
In accordance tothisWiki page, it is possible to write the following structure:
```
typedef struct my_struct {
int integer;
} my_struct_t instance;
```
K&R do not mention this in "C Proglamming Language".
Compiler also returns error during the compilation:
error: expected=,,,;,asm, or__attribute__beforeinstance... |
You misunderstand the page. You caneithermake atypedef,ordefine an instance of the structure, but not both.
It might be clearer if you read the whole page and not only syntax block at the top.
|
Some one told me that the char comparisonif(c>='a' && c<='z')is not portable.
example
```
int main() {
char c;
scanf("%c", &c);
if(c>='a' && c<='z')
printf("lower case\n");
}
```
Any proof that the char comparisonif(c>='a' && c<='z')is not portable?
|
The C standard does not guarantee that only lower case letters appear between'a'and'z'in the execution character set.
In the EBCDIC encoding, there are other characters between'a'and'z', and some C implementations use EBCDIC.
The C standard does guarantee that the digits are consecutive, so'0' <= d && d <= '9'does t... |
Here are the few definitions I read about lvalues
Expressions which can be used with & operator. i.e if &(expression) is not an error, then the expression is an lvalueExpression which results in objects that are not temporarylvalue expressions can be used on both RHS and LHS of = operatorrvalue expressions can be us... |
Neither++inori++are lvalues.
You might be thinking about*x++and*++xwhich are both lvalues (if x has a pointer type).
|
Consider this piece of code:
```
#define MAX 4
............
............
int** ptr = (int**)malloc(sizeof(int*)*MAX);
*ptr = (int*)malloc(sizeof(int)*MAX);
// Assigned values to the pointer successfully
```
Howfoo()can be invoked withptras parameter ?foo()'s prototype has been declared as below:
```
void foo(int a... |
You can't passptras parameter to thatfoofunction.
The memory layout of a 2-dimensional array (array of arrays) is quite different from that of an array of pointers to arrays.
Either change the function signature to accept aint**(and probably also size information), or defineptrto be a 2-dimensional array of the appr... |
i have a struct
```
struct BookInfo
{
char title[50];
int numAuthors;
char authors[50][50];
int year;
int checkedout;
};
```
i can sorted by years but i cannot get it to sort by titles for the life of me all my code does is print out the names in the order they are in the file or i get "incompat... |
You are sortingBookInfoinstances, so yourtempvariable should be of the same type instead of char:
```
int j,i;
BookInfo temp;
```
|
I am trying to make a simple objective-C height converter. The input is a (float) variable of feet, and I want to convert to (int) feet and (float) inches:
```
float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = (totalHeight % 12)*12; //should return 0.1222ft, which becom... |
Even modulo works for float, use :
fmod()
You can use this way too...
```
float totalHeight = 5.122222;
float myFeet = (int) totalHeight; //returns 5 feet
float myInches = fmodf(totalHeight, myFeet);
NSLog(@"%f",myInches);
```
|
Just for kicks and giggles, would it be possible to put a 'for' loop inside a ternary operation?
Here's code for finding if a number is prime:
```
int isPrime(int number){
int i, root = sqrt(number)+1;
if(number==1||!(number)||!(number&1)) return 0;
if(number==2) return 1;
f... |
No, because the format of a ternary operator is:
condition ? first_expression : second_expression;
While a for loop is not an expression - it is a statement (as in, it does not evaluate to a result)
|
This question already has answers here:getting a windows message name [duplicate](3 answers)Closed10 years ago.
I need to translate a value to its corresponding message macro, such as 0x100 to WM_KEYDOWN.
Is there any exists open source implementation of this?
|
Unless your API vendor provides a way to do it, you're out of luck, and you're going to have to do it yourself. The#stringification operator will help you type less:
```
struct macromap
{
int macro,
char *name;
};
#define MAP_ENTRY(macro) { macro, #macro }
struct macromap map[] =
{
MAP_ENTRY(WM_KEYDOWN... |
This question already has answers here:Iterator invalidation rules for C++ containers(6 answers)Closed9 years ago.
For instance:
```
thrust::device_vector<float> vec(...);
thrust::device_vector<float>::iterator i = vec.begin();
vec.resize(...); // vec may get reallocated and moved in memory here
```
Now, hasvec.... |
Upon resizing, if the vector originally did not have enough space, your iterator will be invalidated, so you'd have to recallvec.begin()to get a new, valid iterator.
|
I need to make a function using just~and|,
such that functionf(6, 5)will return4as the answer.
|
By De Morgan's law,~(a | b)equals~a & ~b. By the same law,a & bequals~(~a | ~b).
|
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 need to Write a function in C lan... |
```
int f(int x, int X){
return (x + (X-1))/X;
}
```
|
I wonder if it's possible to make Intel C++ compiler (or other compilers such as gcc or clang) display some messages from optimizer. I would like to know what exactly optimizer did with my code. By default compiler prints only very basic things like unused variable. very simple example - I want to know that expression... |
For icc and icpc, you can use the-opt-report -opt-report-level maxset of flags.
You can also specify an opt-report file. Seeherefor more details
|
I calc -15 mod 18 and here are results:C:-15 % 18 = -15(http://codepad.org/DhzkZYHk)Google:-15 mod 18 = 3(Type-15 mod 18into google's search box)
and results of -9 mod 5:C:-9 % 5 = -4Google:-9 mod 5 =1
Why these are differents? And how google calculate their mod?
|
Google's calculator does -15 mod 18 as
```
-15 = 18*(-1) + 3
```
giving a remainder of 3,
whereas C evaluates it as
```
-15 = 18*(0) - 15
```
and hence the expression becomes -15.
In general,
```
a = (a/b)*b + a%b
```
holds.
|
Using atmel studio to write some beginner C for an atmega64 micro controller. To start off I wanted to read values from PINA, one's complement the values, write them out on PORTC.
Started off with
```
#include <avr/io.h>
int main(void)
{
DDRA = 0x00; //set PORTA to inputs
DDRC = 0xFF; //set PORTC to outputs
while(1... |
Assignment operator (just like you would do with any other port):
```
PORTC = ~PINA;
```
|
This question already has answers here:Iterator invalidation rules for C++ containers(6 answers)Closed9 years ago.
For instance:
```
thrust::device_vector<float> vec(...);
thrust::device_vector<float>::iterator i = vec.begin();
vec.resize(...); // vec may get reallocated and moved in memory here
```
Now, hasvec.... |
Upon resizing, if the vector originally did not have enough space, your iterator will be invalidated, so you'd have to recallvec.begin()to get a new, valid iterator.
|
I need to make a function using just~and|,
such that functionf(6, 5)will return4as the answer.
|
By De Morgan's law,~(a | b)equals~a & ~b. By the same law,a & bequals~(~a | ~b).
|
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 need to Write a function in C lan... |
```
int f(int x, int X){
return (x + (X-1))/X;
}
```
|
I wonder if it's possible to make Intel C++ compiler (or other compilers such as gcc or clang) display some messages from optimizer. I would like to know what exactly optimizer did with my code. By default compiler prints only very basic things like unused variable. very simple example - I want to know that expression... |
For icc and icpc, you can use the-opt-report -opt-report-level maxset of flags.
You can also specify an opt-report file. Seeherefor more details
|
I calc -15 mod 18 and here are results:C:-15 % 18 = -15(http://codepad.org/DhzkZYHk)Google:-15 mod 18 = 3(Type-15 mod 18into google's search box)
and results of -9 mod 5:C:-9 % 5 = -4Google:-9 mod 5 =1
Why these are differents? And how google calculate their mod?
|
Google's calculator does -15 mod 18 as
```
-15 = 18*(-1) + 3
```
giving a remainder of 3,
whereas C evaluates it as
```
-15 = 18*(0) - 15
```
and hence the expression becomes -15.
In general,
```
a = (a/b)*b + a%b
```
holds.
|
I have a simple Opengl programm where I draw triangles by calling glVertex3f and the mode GL_LINE_LOOP
here's what I get:
You can see in the square that apparently some triangles that are at the base of my model (in blue) are drawn above what is in the foreground.
Do you know what is causing it? Is there a way to... |
gluPerspective(60., Width/Height,0,1000);
The near-z cannot be 0 or less. It must be a positive number greater than zero.
|
```
#include
char option[64],line[256];
main()
{
printf(">>")
(fgets(line, sizeof(line), stdin)) {
if (1 == sscanf(line, "%s", option)) {
}
}
print(option)
}
```
will only get the first word, for example
/>>hello world
would output
/>>hello
|
```
#include <stdio.h>
int main(){
char option[64],line[256];
printf(">>");
if(fgets(line, sizeof(line), stdin)) {
if (1 == sscanf(line, "%[^\n]%*c", option)) {//[^\n] isn't newline chars
printf("%s\n", option);
}
}
return 0;
}
```
|
For a matrixA, thedocumentationonly states that the corresponding leading dimension parameterldarefers to the:
leading dimension of two-dimensional array used to store the matrix A
Thus I presume this is just the number of rows ofAgiven CUBLAS' column major storage format.However, when we considerOp(A), what does th... |
Nothing changes. The leading dimensionalwaysrefers to the length of the first dimension of the array. The data order flags (normal, transpose, conjugate) only indicate to BLAS how the data within the array is stored. They have no effect on the array itself, which is always column major ordered and requires an LDA valu... |
I want to wrap a C function that takes achar*pointing to (the first element of) a non-empty buffer of bytes. I'm trying to wrap that in a Go function using CGo so that I can pass it a[]byte, but I don't know how to do the conversion. A simplified version of the C function's signature is
```
void foo(char const *buf, ... |
Ok, that turned out to be much easier than I thought:
```
(*C.char)(unsafe.Pointer(&b[0]))
```
does the trick. (Found this atgolang-nuts.)
|
I have found the following code which is capable of converting an int64_t to network byte order. Now I need the opposite code, such that network byte order is converted back to my little endian machine.
The code is this.
```
int64_t decode(void* value){
int64_t vv = *((int64_t*) value);
int num = 42;
if(... |
The code for yourhtonll
```
#define htonll(x) ((((uint64_t)htonl(x)) << 32) + htonl((x) >> 32))
```
flips the bytes end to end. If you apply it twice, it restores the value to its original state. So the same function can be used forntohll.
|
I am trying to write a program which can display the contents of the file then append the content dynamically by user to a text file in C.
Below is the code, but somehow it is working for single line input and not for multi-line input even in the loop.
```
fobj=fopen("test3.txt","a");
if (fobj==NULL)
{
printf("Er... |
You are facing the typical stdin issue. You can usefflush(stdin);before gets, should work.
|
Suppose we have a function pointerfunc_ptrof typevoid (*func_ptr)().Then we know that using this we can invoke the function using this pointer both as :
```
(*func_ptr)();
func_ptr();
```
But again, suppose we have a pointer to an integer arrayint (*arr_ptr)[5], then why can't we refer to the array asarr_ptr[], ... |
The type ofarr_ptr[0]isint [5]; the type of(*arr_ptr)[0]isint. If you wanted to, you could usearr_ptr[0][0].
```
#include <stdio.h>
int main(void) {
int (*arr_ptr)[5];
int a[2][5] = {{1, 2, 3, 4, 5}, {11, 12, 13, 14, 15}};
arr_ptr = a;
printf("%d %d\n", (*arr_ptr)[2], arr_ptr[1][2]);
return 0;
}
```
You c... |
Just got a question regards, when you read lines of text from a text file how would you separate the words and store them into an array.
For example if I have two lines of text in my text file that looks like this:
1005; AndyCool; Andy; Anderson; 23; LA
1006; JohnCool; John; Anderson; 23; LA
How would you split the... |
Use thestrsepfunction:
```
char* token;
char* line;
/* I assume the line as loaded from file */;
if( line != NULL ) {
while ((token = strsep(&line, ";")) != NULL)
{
/*
token points to the current extracted string,
use it to fill your array
*/
}
}
```
|
Why does herewcwidthreturn "-1" (not a printable wide character) width "Ԥ" (0x0524)?
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int wcwidth(wchar_t wc);
int main()
{
setlocale(LC_CTYPE, "");
wchar_t wc1 = L'合'; // 0x5408
int width1 = wcwidth(wc1);
printf("%lc - print width: %i\n"... |
Most likely U+0524 was not a valid character when your libc character database was created. It was added in Unicode 5.2. Your font may include the character already, butwcwidthdoes not look at which font is used.
|
I want to know that how to print the complete integer value with zero also in C only.
And i am in kernel space ,want to print some values in kernel module.
Like ifais a 32 bit integer then
int a = 14
then output will be like this
value of a = 0x0000000e
in hexa-decimal.
Thanks in advance.
|
Put a0in the format:
```
printf("value of a = 0x%08x", a);
```
From theprintf(3)man page:
'0'(zero)Zero padding. For all conversions exceptn, the converted value is padded on the left with zeros rather
than blanks. If a precision is given with a numeric
conversion (... |
Suppose we have a function pointerfunc_ptrof typevoid (*func_ptr)().Then we know that using this we can invoke the function using this pointer both as :
```
(*func_ptr)();
func_ptr();
```
But again, suppose we have a pointer to an integer arrayint (*arr_ptr)[5], then why can't we refer to the array asarr_ptr[], ... |
The type ofarr_ptr[0]isint [5]; the type of(*arr_ptr)[0]isint. If you wanted to, you could usearr_ptr[0][0].
```
#include <stdio.h>
int main(void) {
int (*arr_ptr)[5];
int a[2][5] = {{1, 2, 3, 4, 5}, {11, 12, 13, 14, 15}};
arr_ptr = a;
printf("%d %d\n", (*arr_ptr)[2], arr_ptr[1][2]);
return 0;
}
```
You c... |
Just got a question regards, when you read lines of text from a text file how would you separate the words and store them into an array.
For example if I have two lines of text in my text file that looks like this:
1005; AndyCool; Andy; Anderson; 23; LA
1006; JohnCool; John; Anderson; 23; LA
How would you split the... |
Use thestrsepfunction:
```
char* token;
char* line;
/* I assume the line as loaded from file */;
if( line != NULL ) {
while ((token = strsep(&line, ";")) != NULL)
{
/*
token points to the current extracted string,
use it to fill your array
*/
}
}
```
|
Why does herewcwidthreturn "-1" (not a printable wide character) width "Ԥ" (0x0524)?
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int wcwidth(wchar_t wc);
int main()
{
setlocale(LC_CTYPE, "");
wchar_t wc1 = L'合'; // 0x5408
int width1 = wcwidth(wc1);
printf("%lc - print width: %i\n"... |
Most likely U+0524 was not a valid character when your libc character database was created. It was added in Unicode 5.2. Your font may include the character already, butwcwidthdoes not look at which font is used.
|
I want to know that how to print the complete integer value with zero also in C only.
And i am in kernel space ,want to print some values in kernel module.
Like ifais a 32 bit integer then
int a = 14
then output will be like this
value of a = 0x0000000e
in hexa-decimal.
Thanks in advance.
|
Put a0in the format:
```
printf("value of a = 0x%08x", a);
```
From theprintf(3)man page:
'0'(zero)Zero padding. For all conversions exceptn, the converted value is padded on the left with zeros rather
than blanks. If a precision is given with a numeric
conversion (... |
I'm looking for a more efficient way to write these kinds of if-conditionals:
```
a = huge_term >= b ? huge_term : c
```
or
```
(a = huge_term) >= b ? a : a = c
```
The second one is quite shorter but the variableaappears 3 times.
I need the result to be stored in a variable.
How would you write it?
|
I recommend using intermediate variables and breaking up the logic into its own function. Generally, whenever I find conditional logic like this, it shows up again and again in my project, so refactoring it saves time in the long run.
```
Type processInput(const Type input)
{
auto result = input;
if ( input < b )... |
I need to open and close a file using shell script.
myshell.sh
```
vi adc.c
```
when i execute myshell.sh, it opens a file.
I need to close that file using shell script.
what command should i include in myshell.sh
|
Instead of using vi, try using touch ?
```
touch /opt/adc.c
```
Touch is an easiest way to create new and empty files. It is also used to Update the time-stamp. Then update the file contents.
```
echo "Your File contents" > /opt/adc.c
```
In this case, you will not need to "Close" your file.
|
While debugging panic issue realted to spinlock, I came across this definition of spinlock in
include/linux/spinlock.h
. It is rather hard for me to understand this definition. Why is__acquires(lock)used after thedo_raw_spin_lockfunction? What is the signification of such declaration?
```
static inline void do_raw_... |
It is used for static analysis.
http://en.wikipedia.org/wiki/Sparse
|
I am working with eclipse, jni, c, CentOS6.
I really want to see some logs from C code, but in eclipse console, it does not show printf Message which happens in C.
Is there any way to print C logs in eclipse console?
|
@Ozan Deniz Thanks for sharing your knowledges. to summarize that link, eclipse has C console problem itself. so if someone print C msg in eclipse console, has to use fprintf(stderr, "")... Thanks again.
|
This question already has answers here:How does free know how much to free?(11 answers)Closed10 years ago.
we allocate memory dynamically in C using malloc() and we receive a pointer to a location in the heap.
now we use free() to deallocate the memory, passing the same pointer value as its argumnet.
the Question no... |
A typical implementation will store information just before the address returned by malloc. That information will include the information that realloc or free needs to know to do their work, but the details of what exactly is stored there depends on the implementation.
|
I recently tried to expand my knowledge of the C language and I came across a program that used emit, to possiblyemita byte.
```
__declspec(naked) void marker_begin() {
__asm {
_emit 0x51;
_emit 0x21;
_emit 0x1A;
_emit 0x14;
_emit 0x2C;
_emit 0x5B;
}
```
}
What could this be used for?
Thanks... |
Your C program is executing inline assembly code by using the_asmkeyword. _asm is a Microsoft specific keyword used inMSDN. The__asmkeyword invokes the inline assembler. It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at least, an empty pair of braces.
The_emitpseudo in... |
While debugging panic issue realted to spinlock, I came across this definition of spinlock in
include/linux/spinlock.h
. It is rather hard for me to understand this definition. Why is__acquires(lock)used after thedo_raw_spin_lockfunction? What is the signification of such declaration?
```
static inline void do_raw_... |
It is used for static analysis.
http://en.wikipedia.org/wiki/Sparse
|
I am working with eclipse, jni, c, CentOS6.
I really want to see some logs from C code, but in eclipse console, it does not show printf Message which happens in C.
Is there any way to print C logs in eclipse console?
|
@Ozan Deniz Thanks for sharing your knowledges. to summarize that link, eclipse has C console problem itself. so if someone print C msg in eclipse console, has to use fprintf(stderr, "")... Thanks again.
|
This question already has answers here:How does free know how much to free?(11 answers)Closed10 years ago.
we allocate memory dynamically in C using malloc() and we receive a pointer to a location in the heap.
now we use free() to deallocate the memory, passing the same pointer value as its argumnet.
the Question no... |
A typical implementation will store information just before the address returned by malloc. That information will include the information that realloc or free needs to know to do their work, but the details of what exactly is stored there depends on the implementation.
|
I recently tried to expand my knowledge of the C language and I came across a program that used emit, to possiblyemita byte.
```
__declspec(naked) void marker_begin() {
__asm {
_emit 0x51;
_emit 0x21;
_emit 0x1A;
_emit 0x14;
_emit 0x2C;
_emit 0x5B;
}
```
}
What could this be used for?
Thanks... |
Your C program is executing inline assembly code by using the_asmkeyword. _asm is a Microsoft specific keyword used inMSDN. The__asmkeyword invokes the inline assembler. It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at least, an empty pair of braces.
The_emitpseudo in... |
I am working on a program and learning about parent/child processes.
Currently my childprocess does
```
exit(variable);
```
in my main() I have:
```
signal(SIGCHLD, chldHandler);
```
outside my main() I have:
```
void chldHandler(int sig) {
}
```
How do I access the variable from my chldHandler?
|
You usewait()inside your signal handler, passing in a non-NULL pointer to get the status.
```
int status;
wait(&status);
```
To decode the status, check to see that it exited normally, then use theWEXITSTATUS()macro:
```
if (WIFEXITED(status)) {
int variable = WEXITSTATUS(status);
/*...*/
}
```
|
How do I do this in constant time (I do not want to brute for iterate from a to b)?
```
// return number of multiples of c in [a,b]
long count_multiples(int a, int b, int c) {
assert(b >= a && c != 0);
// todo
return -1;
}
```
This question looks deceptively simple but is harder than it looks because it has... |
```
long count_multiples(int a, int b, int c) {
if (b < a) return 0;
if (c < 0) c = -c;
long al = a, bl = b, cl = c;
if (c == 1) return bl - al + 1;
return ((bl + (b < 0 ? 1 : 0)) / cl) -
((al - (a > 0 ? 1 : 0)) / cl) +
((a <= 0 && b >= 0) ? 1 : 0);
}
```
|
I have not been able to find any information with a web-search. Where should I be looking?
|
```
char myString[256]; // Input string
char dest[256]; // Destination string
strncpy(dest, myString, 10);
dest[10] = 0; // null terminate destination
```
|
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... |
```
allvalues = d[3] + 10 * ( d[2] + 10 * ( d[1] + 10 * d[0]));
```
|
I build a simple application using c that usedrecvmmsg(), and the fifth parameter passed is timeout oftype struct timespec. I set timeout to 5 seconds, but it's not working, it gets blocking infinity.
The code is as the following:
```
struct timespec timeout;
timeout.tv_sec = 5;
timeout.tv_nsec = 0;
result = recv... |
As an alternative, you could usesetsockoptwithSO_RCVTIMEOoption to set a timeout on the socket. This will affect all read operations performed on it.
|
I need to determine the length of UTF-8 string in bytes in C. How to do it correctly? As I know, in UTF-8 terminal symbol has 1-byte size. Can I usestrlenfunction for this?
|
Can I use strlen function for this?
Yes,strlengives you the number of bytes before the first'\0'character, so
```
strlen(utf8) + 1
```
is the number of bytes inutf8including the 0-terminator, since no character other than'\0'contains a 0 byte in UTF-8.
Of course, that only works ifutf8is actually UTF-8 encoded, ot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.