question
stringlengths 24
425
| answer
stringlengths 5
405
|
---|---|
I need to know if there is 3 d array say :
```
int a[2][3][2]={{{1,2},{9,8},{3,7}},{{2,2},{1,4},{5,4}}};
```
How And what does the expression a[1]-a[0] calculate?
| what does the expression a[1]-a[0] calculate?
It calculates the difference between the pointers to whicha[1]anda[0]decay if use as operators to the arithemtic operator-.
|
I have some arrays that are declared like this:
```
static double covalent_radius[256] = {
[ 0 ] = 0.85,
[ 1 ] = 0.37,
...
};
```
C++ doesn't allow this kind of declaration. Is there any way to achieve this?
| ```
static double covalent_radius[256] = {
0.85, /* ?, Unknown */
0.37, /* H, Hydrogen */
...
};
```
It's C89, not C99 so I suppose it should work.
|
I have some arrays that are declared like this:
```
static double covalent_radius[256] = {
[ 0 ] = 0.85,
[ 1 ] = 0.37,
...
};
```
C++ doesn't allow this kind of declaration. Is there any way to achieve this?
| ```
static double covalent_radius[256] = {
0.85, /* ?, Unknown */
0.37, /* H, Hydrogen */
...
};
```
It's C89, not C99 so I suppose it should work.
|
Can someone explain why this expression produces 1 as result?
```
i = 1 && 2 + 3 | 4;
```
What is exactly the order of the operations here?
| ```
i = (1 && ((2 + 3) | 4)))
```
Boolean expression in C always evaluates to 0 or 1. Anything that's not 0 is considered true.
1 != 02 + 3 == 55 | 4 == 5 (| is the bitwise or operator)5 != 01 && 5 == 1
|
I was wondering if it's possible to use a regex.replace in flex BEFORE the parsing starts.
Is there a predefined variable representing the whole input string?
| No, there is no variable representing the whole input string.
Think about it, this would not be possible for a generic scanner as Flex which must be able to handle very large file sizes, and can be used for a virtually infinite input in an interactive command parser.
|
I'm compiling a C program for an embedded application using eclipse, but I need the code to know (at runtime) where exactly it ends in flash. What is the simplest way of doing this?
Thanks
| You will need to go into the linker command file and create some labels that mark the start and end of the .text section in memory then in the code take the difference.
|
I'd like to fork and exec and program as a non root user while the parent retains root permissions.
pseudo code:
```
pid = fork();
if (pid == 0) {
if (RunAsUser(ConvertStringToUserId("John")) == false) {
stop();
}
if (RunAsUser(ConvertStringToUserId("admin")) == true) {
stop();
}
CreateProcess();
}
```
| If you want to drop privileges in C code, use the functionsetuid.
|
I was wondering if it's possible to use a regex.replace in flex BEFORE the parsing starts.
Is there a predefined variable representing the whole input string?
| No, there is no variable representing the whole input string.
Think about it, this would not be possible for a generic scanner as Flex which must be able to handle very large file sizes, and can be used for a virtually infinite input in an interactive command parser.
|
I am writing a C code which reads from a file and generates an intermediate.cfile.
To do so I usefprintf()to print into that intermediate file.
How can I print"?
| You can use escape symbol\"For example
```
puts( "\"This is a sentence in quotes\"" );
```
or
```
printf( "Here is a quote %c", '\"' );
```
or
```
printf( "Here is a quote %c", '"' );
```
|
Suppose I have a number liken = 1462. When I performi = n%10, the value ofi = 2. After this operation, I want the value ofn = 146, i.e., remove the2from the number. How do I do this in C? Sorry I am very new to C programming. Thanks guys!
| Afteri=n%10usen=n/10. then you will getn=146
```
i = n%10;
n = n/10; // Solution
```
|
I was taking a look at some code for a microcontroller when I came across this cast:(void (*) (void))ROM_FPUTABLE[8]I was wondering what it actually does. Any ideas?
| void (*) (void)specifies a pointer to a function, which returns nothing, and takes no arguments.
Therefore(void (*) (void))casts something to a pointer to a function, which returns nothing, and takes no arguments.
|
I was taking a look at some code for a microcontroller when I came across this cast:(void (*) (void))ROM_FPUTABLE[8]I was wondering what it actually does. Any ideas?
| void (*) (void)specifies a pointer to a function, which returns nothing, and takes no arguments.
Therefore(void (*) (void))casts something to a pointer to a function, which returns nothing, and takes no arguments.
|
I'm writing program, that can send emails through SMTP, on C/C++ using cURL library.
I have got problem - I can't start new line in email.
I tried using'\0'and'\n'symbols.
| It should be\r\nnot/n.
Same goes to\0
|
In C, I have a header filefile1_0.hwhich is included by onlyfile1.handfile1.c.
file1.his included by many other files say,file2.c,file3.candfile4.c
If I make any change infile1_0.hI know that I need to re-compilefile1.cbut do I also need to recompilefile2.c,file3.candfile4.c?
| Yes.
All your other files depend onfile1_0.hsincefile1.hdepends on it and all the others depend onfile1.h. So you need to recompile "to be safe".
|
How does~operator work in c?
can anyone explain the following code?
```
main()
{
printf("%d",~5);
}
```
output is-6
| 5is (probably) a 32-bit signed integer with bit representation0x00000005, or in binary:
```
0b00000000000000000000000000001010
```
~5is the bitwise NOT of5, which will be0xFFFFFFFA, or in binary:
```
0b11111111111111111111111111110101
```
Usingtwo's complement, that is-6.
|
I was solving C programming Questions and I came across this
```
#include<stdio.h>
int main()
{
int x=100,y=200,z=300;
printf("%d..%d..%d");
}
```
I expected an error but the output was300..200..100
Can anyone explain this output?
| %dinprintfexpectsinttype argument. You are passing no arguments. Its a constraint violation and ultimately your program invokesundefined behavior.
|
I was solving C programming Questions and I came across this
```
#include<stdio.h>
int main()
{
int x=100,y=200,z=300;
printf("%d..%d..%d");
}
```
I expected an error but the output was300..200..100
Can anyone explain this output?
| %dinprintfexpectsinttype argument. You are passing no arguments. Its a constraint violation and ultimately your program invokesundefined behavior.
|
Is there any C or C++ function which can produce the same output of this python code (SHA512 with salt)?
```
import crypt;
crypt.crypt('test', '$6$Salte2Ck$')
```
| Hereare some explanations to Python'scryptfunction.So I think what you are looking for is the C functioncryptfromunistd.h.
|
Currently, I have an application that does:
execlp(java_exec, java_args, etc, etc);
to launch a jar file.
Is there a way to also have it prependLD_PRELOAD="mylib.so"?
I couldn't find a way to tellexeclpto do:LD_PRELOAD="mylib.so" java -jar foo.jar
Any ideas how I can achieve this in C or C++ on Linux?
| You should probably addLD_PRELOAD=mylib.soto*envp,execlpe()'s fourth arg.
|
I was wondering if there is a ALSA function that can tell which sample frequencies are supported by the recording using ALSA?
| That would be thesnd_pcm_hw_params_get_rate_maxfunction.
For an example, seehw_params.c.
|
I was wondering if there is a ALSA function that can tell which sample frequencies are supported by the recording using ALSA?
| That would be thesnd_pcm_hw_params_get_rate_maxfunction.
For an example, seehw_params.c.
|
Is there a function to return a keysym from a string representation of the key?
for example,SDL_GetKeySym("d") == SDLK_d
I need this to read a keysym from a config file, and of course I'm usingSDL_GetKeyNameto get a string representation of the key and then saving it to the config file.
| SDL2 adds theSDL_GetKeyFromNamefunction, which does the inverse ofSDL_GetKeyName.
|
How do you store a 16 bit binary in an array in C? What data type would I have to make the array? long int, float, char?
ex. data = {'1001111101110010', '1001101011010101','1000000011010010'}
| Withinstdint.his the followingtypedef:
uint16_t
This integer type is exactly 16 bits in width. You can use it for your needs like this:
```
#include <stdint.h>
uint16_t arr[NUM_ELEMENTS] = {...};
```
|
the output of the function would be 4, but i am unable to understand why is this so. Its much appreciated if you can reason to what happens when for x%y, when y > x
```
int main()
{
int x=4%5;
printf("x=%d\n",x);
return 0;
}
```
| 4 / 5 = 0and0 * 5 + 4 = 4, so the remainder is4.
C defines%, the remainder operator, as (in c11, 6.5.5p6):
```
(a/b)*b + a%b shall equal a.
```
|
I have code written in C but I need to see the Assembly file so I can optimize the code and figure out how long certain functions will take. Does anyone know of a quick way to pull up the Assembly code?
| I also had the same problem as you. Here is what worked for me.
Debug the main program, when finished, choose
```
" Window >> Debugging >> Disassembly ".
```
Then you would see the corresponding assembly code.
Hope it could help you out.
|
I am usinggtk_overlay_new ()to create an overlay in gtk, is there any way i can add some background color to it? so far i have not been successful in finding anything in the documentation.
| Use:void gtk_widget_override_background_color();https://developer.gnome.org/gtk3/unstable/GtkWidget.html#gtk-widget-override-background-color
|
I build Clang from sources to ensure I get the latest analysis tools and sanitizers. The tarballs I download are Clang Source Code, LLVM Source Code, Compiler-RT Source Code and LLDB Source Code. TheLLVM Download Pagealso lists aClang Tools Extradownload.
What is in Clang Tools Extra tarball?
| You can check it in the official documentation:extra clang tools documentation
|
I am usinggtk_overlay_new ()to create an overlay in gtk, is there any way i can add some background color to it? so far i have not been successful in finding anything in the documentation.
| Use:void gtk_widget_override_background_color();https://developer.gnome.org/gtk3/unstable/GtkWidget.html#gtk-widget-override-background-color
|
I build Clang from sources to ensure I get the latest analysis tools and sanitizers. The tarballs I download are Clang Source Code, LLVM Source Code, Compiler-RT Source Code and LLDB Source Code. TheLLVM Download Pagealso lists aClang Tools Extradownload.
What is in Clang Tools Extra tarball?
| You can check it in the official documentation:extra clang tools documentation
|
```
int t[ ] = { 0x0203, 0x4 };
char *p=t;
printf(" *p = %d; *(p+1) = %d ",*p,*(p+1));
```
Why does *(p+1) always return 2, regardless of the second element in t?
| You're running this program on alittle endiancomputer. This means your int array is stored in memory as bytes in the following order:
0x03 0x02 0x00 0x00 (first integer)
0x04 0x00 0x00 0x00 (second integer)
Try to print out*(p+i)for p between 0 and 7, it should verify this.
|
```
int t[ ] = { 0x0203, 0x4 };
char *p=t;
printf(" *p = %d; *(p+1) = %d ",*p,*(p+1));
```
Why does *(p+1) always return 2, regardless of the second element in t?
| You're running this program on alittle endiancomputer. This means your int array is stored in memory as bytes in the following order:
0x03 0x02 0x00 0x00 (first integer)
0x04 0x00 0x00 0x00 (second integer)
Try to print out*(p+i)for p between 0 and 7, it should verify this.
|
For the sake of readability, I like to write boolean conditions "in full" in C/C++, e.g.:
if (foo == true)instead ofif (foo)andif (foo == false)instead ofif (!foo).
Does this compromise performance?
| Assuming foo is a bool, it does not. It can be trivially optimized by the compiler.
However, this may not be the case if foo is a class, which can overload operators to do whatever it wants.
|
Is there a way to use asterisk AMI in c language? I want to get information about asterisk in its module using C language. I have configured manager.conf file.
| AMI is simple interface using tcp socket.
Sure you can use it from c.
You can get libs from this page:
http://www.voip-info.org/wiki/view/Asterisk+manager+Examples
|
Is there a way to use asterisk AMI in c language? I want to get information about asterisk in its module using C language. I have configured manager.conf file.
| AMI is simple interface using tcp socket.
Sure you can use it from c.
You can get libs from this page:
http://www.voip-info.org/wiki/view/Asterisk+manager+Examples
|
For example:
```
if(mvwinch(win,y,x=(oldx-1))=='X')
```
Is the value of the variable 'x' now changed?
| Before comparison, both expressions will be evaluated and any side effect could take place during the evaluation. So, yesxwould be modified.
|
For example:
```
if(mvwinch(win,y,x=(oldx-1))=='X')
```
Is the value of the variable 'x' now changed?
| Before comparison, both expressions will be evaluated and any side effect could take place during the evaluation. So, yesxwould be modified.
|
If I typeint xis it usingsizeof(int)bytes of memory now? Is it not until x has a value?
What ifx = b + 6...is x given a spot in memory before b is?
| Yes, as soon as you declare a variable like:
```
int x;
```
memory is, generally, allocated on the stack. That being said, the compiler is very smart. If it notices you never use that variable, it mayoptimize it away.
|
Are the following twostaticvariable declarations equivalent?
1.
```
static int var1;
static int var2;
static int var3;
```
2.
```
static int var1, var2, var3;
```
More specifically, in case 2, will all variables bestatic, or justvar1?
| They're equivalent.
In case 2, all the variables will be static.
The storage class specifierstaticapplies to all the declared variables in the declaration.
|
Literally, does(char *) 0mean a pointer to some location that contains a zero? Does the system create such an address with value 0 for each such declaration?
| No, it's a cast of0to typechar *. That is, anull pointer. A0in any pointer context refers to thenull pointer constant.
Whatexactly it points to doesn't matter - dereferencing it would cause undefined behaviour.
For more, check out theC FAQ Part 5: Null Pointers.
|
Literally, does(char *) 0mean a pointer to some location that contains a zero? Does the system create such an address with value 0 for each such declaration?
| No, it's a cast of0to typechar *. That is, anull pointer. A0in any pointer context refers to thenull pointer constant.
Whatexactly it points to doesn't matter - dereferencing it would cause undefined behaviour.
For more, check out theC FAQ Part 5: Null Pointers.
|
What is this code doing exactly:
```
char* pointer=0;
*pointer=0;
```
Every time I run this code, the programme crashes!
| First line: You create apointervariable to a char, then you initialize it to address zero (NULL pointer).
Second line: you try to write a zero to the address wherepointeris pointing to.
Address zero is outside of your process' writable virtual memory area, so you get a segmentation fault.
|
What is this code doing exactly:
```
char* pointer=0;
*pointer=0;
```
Every time I run this code, the programme crashes!
| First line: You create apointervariable to a char, then you initialize it to address zero (NULL pointer).
Second line: you try to write a zero to the address wherepointeris pointing to.
Address zero is outside of your process' writable virtual memory area, so you get a segmentation fault.
|
How can I create a mutex in linux that will work with different processes and will have string name?
I want something similar toCreateMutexin Windows OS.
| Use a semaphore - seehttp://man7.org/linux/man-pages/man7/sem_overview.7.html.
This will give you the same as a mutex and you can name them
|
How can I create a mutex in linux that will work with different processes and will have string name?
I want something similar toCreateMutexin Windows OS.
| Use a semaphore - seehttp://man7.org/linux/man-pages/man7/sem_overview.7.html.
This will give you the same as a mutex and you can name them
|
My C++ multi threaded application hangs in pthread_spin_lock in valgrind versions 3.8.0 and latest. But it is not happening in 3.6.0, 3.6.1 and 3.7.0. Anyone knows any workaround for this?
| This is cause the internal problems of thread managing in valgrind. I had same problem and it was fixed in 3.10 version of valgrind.
|
is control-d a default stop sign for stdin?
In our homework, it says command-d will be stop inputting.
Is it a default ?
| Ctrl-Don Linux terminal with default settings is an end-of-file marker for stdin.
See alsothe tty demystifiedand thestty(1)command (andtermios(3)...). Use e.g.feof(3)aftersome stdio operation, or compare the result ofgetc(3)withEOF(etc....) to detect end-of-file conditions!
|
This question already has an answer here:What does the following for loop syntax mean in C?(1 answer)Closed9 years ago.
For example,
```
for (;;)
{
//do something
}
```
How is this different from
```
{
//do something
}
```
| It's an infinite loop. Pretty much the same as writing
```
while (true)
{
// do something
}
```
|
This question already has an answer here:What does the following for loop syntax mean in C?(1 answer)Closed9 years ago.
For example,
```
for (;;)
{
//do something
}
```
How is this different from
```
{
//do something
}
```
| It's an infinite loop. Pretty much the same as writing
```
while (true)
{
// do something
}
```
|
How can I codetest al,alin c language?
I've triedif((n & 0xFF) & 0){}but this is not correct.
Thanks.
| I'm guessing that you're checking the zero flag next, i.e.jzor similar. In that case you'd want
```
if ((n & 0xFFFF) != 0) {
```
Note that
AX is 16-bit not 8 bit (as e.g. AL and AH are) so you want 0xFFFF not 0xFF (if you even need this restriction)& 0can only ever give= 0and so false.
|
Say I have a python script that opens a file to write:
The python modules also call C modules that change the directory with
```
chdir()
```
Will the python script still have the file open and be able to write?
| Files are tracked by file handles, and once open for a particular file, stays open to that file until closed.
|
Given aSecKeyRefloaded usingSecItemImportfrom an RSA private key is there a way to obtain or create aSecKeyReffor only the public key components? In OpenSSL this could be done by copying the modulus and public exponent to a new struct, butSecKeyRefis opaque and I've been unable to find a function that performs this operation.
| As of macOS 10.12, iOS/tvOS 10, and watchOS 3 the functionSecKeyCopyPublicKeynow exists to do this.
|
Hello I am writing a program and dynamic loadable modules. Those modules are loaded using 'dlopen'. How do I use a program function in the module? Are function pointers the right way? Thank you
| Yes you need function pointers and have to calldlsym()to get them
|
Hello I am writing a program and dynamic loadable modules. Those modules are loaded using 'dlopen'. How do I use a program function in the module? Are function pointers the right way? Thank you
| Yes you need function pointers and have to calldlsym()to get them
|
```
char foo[] = "something";
char *p = foo;
```
Is there a way to change the value pointed and increment the pointer to the next element using only one ;?
I mean, make the effect of these 2 lines below in a single statement?
```
*p = 'S';
p++;
```
| I think you want
```
*p++ = 'S'; // as good as --> *(p++) = 'S';
```
Sample run.
|
I have a struct that declared as follow:
```
struct a {
struct b {
int d;
} c;
};
```
How to declare a variable ofboutsidea? In C++ I can usea::b x;. But, in C it required to specifiesstructkeyword before struct name.
| C has a flat layout; when you declare a struct within another struct, the former is just being put into the global namespace.
So, in your example, it is juststruct b.
|
```
unsigned char endian[2] = {1, 0};
short x;
x = *(short *) endian;
```
I don't understand the value held in x. If I have a little-endian system, x is 1.
But if I have a big-endian system, x is 256.
Why is the value 256 rather than 128 ?
Thanks for your help.
| Because the bytes01 00, in big-endian, are the value0x0100, which equals1 << 8 == 2**8 == 256(Recall there are 8 bits in a byte).
|
```
unsigned char endian[2] = {1, 0};
short x;
x = *(short *) endian;
```
I don't understand the value held in x. If I have a little-endian system, x is 1.
But if I have a big-endian system, x is 256.
Why is the value 256 rather than 128 ?
Thanks for your help.
| Because the bytes01 00, in big-endian, are the value0x0100, which equals1 << 8 == 2**8 == 256(Recall there are 8 bits in a byte).
|
I have a pre-built static library (.a) and the source code for it. How do I attach the source so so I can step through it while debugging in Eclipse with gdb?
| You can't step through the source code if your library has not been compiled with the debug option (gcc -g, assuming you are using gcc). The easiest thing would be to compile the library yourself in Eclipse, in debug mode, then link your program against the newly-compiled library.
|
I have a pre-built static library (.a) and the source code for it. How do I attach the source so so I can step through it while debugging in Eclipse with gdb?
| You can't step through the source code if your library has not been compiled with the debug option (gcc -g, assuming you are using gcc). The easiest thing would be to compile the library yourself in Eclipse, in debug mode, then link your program against the newly-compiled library.
|
Is this legal in C?
```
struct Doubles
{
double a,b,c;
};
void foo(struct Doubles* bar)
{
double* baz = (double*)bar;
baz[0]++;
baz[1]++;
baz[2]++;
}
```
I know that it "works" on MSVC 2010, but I don't know if it's legal, or if different layouts could cause UB.
| This leads to undefined behaviour. The layout of the struct is not totally prescribed by the standard. For instance, there may be padding.
|
strlen() is terminated by null right? So how come both char c[]={'1','1'} and char d[]={'1','1','\0'} gives the same output 2 when strlen(c) and strlen(d) is used?
| The former is undefined behavior; it could output 2, it could also output 500, terminate your program or destroy your computer.
|
I have a portable library that in one place needs to do X if compiled under Visual Studio or just with Microsoft's C/C++ compiler, and Y otherwise. What#defineshould I look for?
| Aquick Google searchleads topredefined macros on MSDNwhich lists all macros predefined by MSVC. Out of these,_MSC_VERis likely the best candidate.
|
I need to check string values and if a string with value 0d0a in hex comes i need to break while loop.
How to check this since those are unprintable characters ?
| To check if a string consists of just those two characters:
```
if ( 0 == strcmp(my_string, "\x0d\x0a") )
{
// action to take if it matches
}
```
If your intent is to look for CR-NL pairs then"\r\n"is equivalent (in ASCII encoding) and documents that a bit more clearly.
|
I need to check string values and if a string with value 0d0a in hex comes i need to break while loop.
How to check this since those are unprintable characters ?
| To check if a string consists of just those two characters:
```
if ( 0 == strcmp(my_string, "\x0d\x0a") )
{
// action to take if it matches
}
```
If your intent is to look for CR-NL pairs then"\r\n"is equivalent (in ASCII encoding) and documents that a bit more clearly.
|
I need to check string values and if a string with value 0d0a in hex comes i need to break while loop.
How to check this since those are unprintable characters ?
| To check if a string consists of just those two characters:
```
if ( 0 == strcmp(my_string, "\x0d\x0a") )
{
// action to take if it matches
}
```
If your intent is to look for CR-NL pairs then"\r\n"is equivalent (in ASCII encoding) and documents that a bit more clearly.
|
This is my little program:
```
#include <unistd.h>
#include <stdio.h>
int main() {
printf("1");
fork();
printf("2");
fork();
return 0;
}
```
The output of this code is12121212and I ask:Why does it print more than122?
| Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.
|
Dogccandclhave an equivalent forifortreal-sizecompiler flag? If not, what should I use instead? MACRO?
```
#ifdef DOUBLE_PRECISION
#define REAL double
#else
#define REAL float
#endif
REAL myvar;
```
| gfortran has compile-time option-fdefault-real-8. But not gcc.
|
This is my little program:
```
#include <unistd.h>
#include <stdio.h>
int main() {
printf("1");
fork();
printf("2");
fork();
return 0;
}
```
The output of this code is12121212and I ask:Why does it print more than122?
| Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.
|
Dogccandclhave an equivalent forifortreal-sizecompiler flag? If not, what should I use instead? MACRO?
```
#ifdef DOUBLE_PRECISION
#define REAL double
#else
#define REAL float
#endif
REAL myvar;
```
| gfortran has compile-time option-fdefault-real-8. But not gcc.
|
I have an int that I need to round down to the nearest 100.
As an example:
91 would be rounded down to 0
101 would be rounded down to 100
199 would be rounded down to 100
| ```
main()
{
int a=0;
scanf ("%d", &a)
a= ( a/100) * 100;
printf ("Result:%d", a);
}
```
The above code will satisfy your requirement.
|
I need an event which handles clicks on main window of my program.
I usedbutton-press-eventbut when i click on my window nothing happens.
I'm designing my GUI usingGlade Interface Designer.
please explain for me whenbutton-press-eventwill be called in gtk+ & is it the event i need or not?
| Check you've got the button press event mask set for the window under the
Window Properties - Common tab in glade
|
I need an event which handles clicks on main window of my program.
I usedbutton-press-eventbut when i click on my window nothing happens.
I'm designing my GUI usingGlade Interface Designer.
please explain for me whenbutton-press-eventwill be called in gtk+ & is it the event i need or not?
| Check you've got the button press event mask set for the window under the
Window Properties - Common tab in glade
|
```
int main() {
int i,j=6;
for(;i=j;j-=2)
printf("%d",j);
return 0;
}
```
This piece of code gives output 642
please explain me why this loop doesn't run infinitely and stops when j is non-positive
| Whenjbecomes0the expressioni=jevaluates to0. Hence, the loop terminates.
Note that ifjwere to start as negative number ( e.g.-1)or as an odd number (e.g.5), then the condition will never evaluate to0and will result in an infinite loop.
|
Why is this bad?
```
if (true)
int stuff = 10;
else
int stuff = 5;
printf("Stuff is %d\n",stuff);
```
Is it because of scope?
| Yes.stuffonly exists in the scope of theifandelseblocks (where they are two different variables). You have to declare it outside the if-else to work.
```
int stuff;
if (true)
stuff = 10;
else
stuff = 5;
printf("Stuff is %d\n",stuff);
```
|
Why is this bad?
```
if (true)
int stuff = 10;
else
int stuff = 5;
printf("Stuff is %d\n",stuff);
```
Is it because of scope?
| Yes.stuffonly exists in the scope of theifandelseblocks (where they are two different variables). You have to declare it outside the if-else to work.
```
int stuff;
if (true)
stuff = 10;
else
stuff = 5;
printf("Stuff is %d\n",stuff);
```
|
```
main() {
unsigned int a=-9;
printf("%d",a);//gives output -9
cout<<a;// gives output 9429967287
getch();
}
```
Why it gives different output in both cases?
Do 'printf' and 'cout' treat bit pattern in a different way?
Why is 'printf' not giving the positive answer?
| Because you told it to:%dis for printing an argument as asignedint. To print an unsigned int, you should have used%u.
|
I'm experienced with Objective C and easily know how to use NSScanner. I have a project I need to write in either C or Python that needs to use similar functionality to NSScanner(such as scanUpToString). Are there any standard or non-standard libraries that could provide similar functionality?
| In Python take a look at thefindmethod ofstr.
You could combine it like so:
```
foo ="barbazzapp"
foo[:foo.find("zapp")] # Returns 'barbaz'
```
|
If y is of integer type, then the expressions:
```
3*(y-8)/9
```
and
```
(y-8)/9*3
```
Will yield different result always or is it possible for them to yield same result?
What does it depend on?
Explanation with an example will be helpful.
| May yield different or same result, it is depend on 'y' value. The operations will be carried from left to right.
Ex: for y=11:
3*(y-8)/9: 1 (y-8)/9*3: 0
for y = 10
3*(y-8)/9: 0 (y-8)/9*3: 0
|
In my C program I am using void* pointers. Is there anyway to check in an if statement if the void* pointer is pointing to an int* or a char*?
| Nope. There is no run-time type information in C. Avoid*is just an address. That's it. It's completely up to the programmer to know / keep track of what information avoid*points to.
With more information about how/why you're usingvoid*, a workaround could possibly be suggested.
|
I am using LDA algorithm to classify a signal, how can i do that with multiple classes ? I have read some references but don't get the result.
I I've looked example code atlink
but it doesn't have explicit classifier part for me!
| You can use OpenCV to keep doing this.
|
I have stored an int in a void * variable in a struct
```
void * data = &ID;
```
and now I want to print it. How would I do this? I tried to dereference it but the compiler complained about dereferencing void*. Thanks!
| You should castdatatoint *first, then derefer it:
```
printf("%d\n", *(int *)data);
```
|
I have stored an int in a void * variable in a struct
```
void * data = &ID;
```
and now I want to print it. How would I do this? I tried to dereference it but the compiler complained about dereferencing void*. Thanks!
| You should castdatatoint *first, then derefer it:
```
printf("%d\n", *(int *)data);
```
|
Working on this little piece of code, but for some reason it keep crashing the whole time.
Anyone got an idea what i'm doing wrong
```
char *str;
printf("Enter a string\n");
gets(str);
printf("The size of the string is %d", strlen(str));
system("PAUSE");
return 0;
```
| You have not allocated any memory forstr. Declare a buffer, for examplechar str[50], but be aware ofbuffer overflows.
|
If on linux I try to compile c code in the standard way
```
gcc -myprog.c
```
the generated binary uses only the base CPU features, since the modern CPUs have a lot of special features to increase the performances, like AVX, AVX2, SSE3, SSE4 etc. according the model
Since I want targeting only a specific CPU type (i7 Sandy Bridge), Is there a way to set the copiler to take advantage of these features?
| Look at the -march and -mtunegcc flags
|
If on linux I try to compile c code in the standard way
```
gcc -myprog.c
```
the generated binary uses only the base CPU features, since the modern CPUs have a lot of special features to increase the performances, like AVX, AVX2, SSE3, SSE4 etc. according the model
Since I want targeting only a specific CPU type (i7 Sandy Bridge), Is there a way to set the copiler to take advantage of these features?
| Look at the -march and -mtunegcc flags
|
I'm sure this has been asked many times before but this kind of thing is pretty difficult to search for.Say foo and bar are both pointers to separate arrays, what does this line do?
```
*foo++ = *bar++;
```
At what point does each pointer get incremented, and is it an assignment of pointers or values?Thank you
| ```
*foo++ = *bar++;
```
copies whatbarpoints at over whatfoopoints at. Then it increments both pointers to the next element.
|
I am a beginner to Linux console and start write some code in C.
I try to compile code and hope to see messages using command
gcc foo.c -o foo -v | less
But the result text cannot be paged. Any wrong I do? Thanks.
| The|pipe command just redirects stdout. To redirect stderr as well as stdout use|&:
```
gcc foo.c -o foo -v |& less
```
|
There is any api in c which can set multicast ip address in route table in linux.
like
through command it can be like this
ip route add multicast dev
there is any c api which will same as above command is doing.
thanks in advance
| You might want to look at the documentation forrtnetlink
This is the userspace api to interact with the kernel routing rules.
|
Is there anyway to emit the llvm-ir bytecode from inside my pass, into a file? I want the same format that I am getting by using the opt tool, so I can pass this file to the opt later.
| To print a module in the textual representation (whichoptcan parse just file) to stdout, useModule::dump(). To save it to a file, useModule::print(and just pass null as the 2nd argument).To dump it to a bitcode file, usellvm::WriteBitcodeToFile.
|
Is there anyway to emit the llvm-ir bytecode from inside my pass, into a file? I want the same format that I am getting by using the opt tool, so I can pass this file to the opt later.
| To print a module in the textual representation (whichoptcan parse just file) to stdout, useModule::dump(). To save it to a file, useModule::print(and just pass null as the 2nd argument).To dump it to a bitcode file, usellvm::WriteBitcodeToFile.
|
I'm trying to make a simple c-shell like program on C (for Linux) that will execute scripts.
I need to read a script file in order to execute it, but how can I read it if it has only execute permission, and no read permission?
| In short,
A binary file you can execute with only execute permissions.A script is a text file, so you need read permissions.
So, you would need to play some games with group ownership, sudo, or similar.
|
This question already has answers here:Are empty macro definitions allowed in C? How do they behave?(3 answers)Closed9 years ago.
I encountered some codes as the following:
```
#define MY_IDENTIFIER
void someCode()
{
...
MY_IDENTIFIER
...
}
```
What's the upper code doing ?
| Absolutely nothing. The pre-processor is simply replacingMY_IDENTIFIERwith nothing wherever it encounters it.
|
I have the following c code:
```
int argv = 2;
char **argv = {"test arg 1",
"test arg 2"};
```
When I compile it, I get teh following warning:
warning: initialization from incompatible pointer type [enabled by default]
Can you please tell me what's wrong for my initialization?
Thank you.
| char **is a pointer type not an array type.
Use an array type:
```
char *argv[] = {"test arg 1", "test arg 2"};
```
|
Can anybody tell me how to useitoafunction in C?
The prototype is:
```
char*itoa(int_Val,char*_DstBuf,int_Radix)
```
I think thatint_Valis the value that I want to convertchar*_DstBuf, is the string where I want to store the result
But what isint_Radix?
| It is the base to convert to
10 - Decimal
16 - Hexidecimal
8 - Octal
A per the manual pagehttp://www.cplusplus.com/reference/cstdlib/itoa/
|
I'm writing an multithreaded application and I'm wondering about following:
When using-D_REENTRANTmacro, do I need to explicitly use_rsuffixed functions?
e.g. Shall I usestrtok_reverywhere in the code or can I usestrtokand make sure I pass-D_REENTRANTmacro to the compiler?
Thanks a lot
| Defining_REENTRANTwon't change the semantics ofstrtok(). You'll need to usestrtok_r().
|
How do I convert the following macro into a function?
```
#define xtime(x) ((x<<1) ^ (((x>>7) & 1) * 0x1b))
```
| ```
template<typename T>
T xtime(T x)
{
return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
}
```
|
is there some way to define static structure that is already one and only instance of itself?
Like the way you can do it with the struc keyword in nasm?
| You can use an anonymous structure, like this:
```
struct {
int memberA, memberB;
} my_struct;
my_struct.memberA = 1;
my_struct.memberB = 2;
printf("%d %d\n", my_struct.memberA, my_struct.memberB);
```
|
Basically it's all in the title. I'm calling C code from R via .Call(). The C code is throwing an error, but using traceback() or options(error=recover), the .Call() function is the farthest I can drill down to. Is there a way to view the C call stack when an error is thrown in the C code?
| Use gdb (or lldb under clang) to debug C code, perhaps as outlinedhere
|
By using c language I need to create a text file in/tmpdirectory, but I don't know how to do this. Is there anyone who knows how to create a text file in/tmpfolder?
| There'smkstempfunction for this
|
By using c language I need to create a text file in/tmpdirectory, but I don't know how to do this. Is there anyone who knows how to create a text file in/tmpfolder?
| There'smkstempfunction for this
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.