question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
As static arrays are created during compile-time, may I set the length of the array with a variable obtained through e.g. another function? I believe this is dependent on whether the compiler can be smart enough to know what value this variable will have?
Example code where I obtain the size troughsnprinf(). This code is compiling without errors or warnings usinggccwith the-Wallflag.
```
#include <stdio.h>
int main(void)
{
int mac[6] = {0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
int size = snprintf(NULL, 0, "%02X", mac[0]);
char str[size + 1];
snprintf(str, size + 1, "%02X", mac[0]);
printf("%s\n", str);
return 0;
}
```
Compiling and running results in:
```
AA
```
Why is this possible?
|
stris not a static array it is what C calls a VLA, variable length array.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question
```
int main()
{
int i= 0;
printf("i value is %d\n",i);
scanf("%c", &i); // I am giving an input of 255 here
printf("i after scan %d\n",i); // This prints 50. How???
return 0;
}
```
Can someone explain how does the printf statement give 50? I have a little-endian machine.
|
Your program won't even compile asIis undeclared. I am assuming that it is a typo. Since you are scanning%cit will read only one character which is 2 from 255. Now 2 has ascii code of 50 which is being printed.
|
I'm new to C and ASCII numbers, so I was using a code sample to print ASCII numbers
```
int main(){
int c;
while ((c = getchar()) != EOF){
printf("%d\n", c);
}
}
```
Output for "d" was
```
100
10
```
Whatever letter I tend to type, the result will be the ASCII code of said letter and 10 at the end as well. I'm not sure where this 10 is coming from.
|
That's the code for the newline character that ended the input line.
if you want to stop at the end of the line and not include it, add another check.
```
while ((c = getchar()) != EOF && c != '\n'){
printf("%d\n", c);
}
```
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question
```
int main()
{
int i= 0;
printf("i value is %d\n",i);
scanf("%c", &i); // I am giving an input of 255 here
printf("i after scan %d\n",i); // This prints 50. How???
return 0;
}
```
Can someone explain how does the printf statement give 50? I have a little-endian machine.
|
Your program won't even compile asIis undeclared. I am assuming that it is a typo. Since you are scanning%cit will read only one character which is 2 from 255. Now 2 has ascii code of 50 which is being printed.
|
I'm new to C and ASCII numbers, so I was using a code sample to print ASCII numbers
```
int main(){
int c;
while ((c = getchar()) != EOF){
printf("%d\n", c);
}
}
```
Output for "d" was
```
100
10
```
Whatever letter I tend to type, the result will be the ASCII code of said letter and 10 at the end as well. I'm not sure where this 10 is coming from.
|
That's the code for the newline character that ended the input line.
if you want to stop at the end of the line and not include it, add another check.
```
while ((c = getchar()) != EOF && c != '\n'){
printf("%d\n", c);
}
```
|
I am programming in C using SDL2 and I am getting this error:
```
`main': main.c:(.text+0x2d0): undefined reference to 'IMG_Load'`
```
I have these includes:
```
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
```
For reference I am using Arch Linux and using GCC with this command to compile:
```
gcc main.c `sdl2-config --libs -lSDL2 -lSDL2_image` -o game
```
I've looked all over for solutions but none of them seem to rectify the issue.
|
This:
```
gcc main.c `sdl2-config --libs -lSDL2 -lSDL2_image` -o game
```
should be:
```
gcc main.c `sdl2-config --libs` -lSDL2 -lSDL2_image -o game
```
In other words, onlysdl2-config --libsis the subcommand.
|
This question already has answers here:Why is the gets function so dangerous that it should not be used?(13 answers)Closed3 years ago.
Why is implicit declaration of gets() not allowed in C99?I had referred this question, which was how I came to know about it's deprecation.
|
Yes, you should usefgets()instead.
|
I am programming in C using SDL2 and I am getting this error:
```
`main': main.c:(.text+0x2d0): undefined reference to 'IMG_Load'`
```
I have these includes:
```
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
```
For reference I am using Arch Linux and using GCC with this command to compile:
```
gcc main.c `sdl2-config --libs -lSDL2 -lSDL2_image` -o game
```
I've looked all over for solutions but none of them seem to rectify the issue.
|
This:
```
gcc main.c `sdl2-config --libs -lSDL2 -lSDL2_image` -o game
```
should be:
```
gcc main.c `sdl2-config --libs` -lSDL2 -lSDL2_image -o game
```
In other words, onlysdl2-config --libsis the subcommand.
|
This question already has answers here:Why is the gets function so dangerous that it should not be used?(13 answers)Closed3 years ago.
Why is implicit declaration of gets() not allowed in C99?I had referred this question, which was how I came to know about it's deprecation.
|
Yes, you should usefgets()instead.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed3 years ago.Improve this question
Just out of curiosity, how to redefine a standard library function, such asfreeto be something else? Something like:
```
delete_function free;
void free() {
printf("I'm free!");
}
```
|
Within pure C, you can't. If you really want to, look at your linker documentation, but your are more likely to find what you are looking for in an instrumentation toolkit like valgrind.
|
What is the order one has to read the bits from the bin value? Having for e.g.this official MS docsite regarding thelParamof theWM_CHARmessage, they explain what bits have what meaning. Taking the bits16-23for thescan codevalue should I read the bits from right to left or vice versa?
|
The page you linked to usesLSB 0 bit numberingso you can extract bits 16-23 with
```
lParam & 0b00000000111111110000000000000000U
// | | | |
// bit 31 23 16 0
// MSB LSB
```
Note: The0bprefix for binary numbers requires C++14. In C it's only available as an extension in some implementations.
You may also want to shift down the result with
```
(lParam & 0b00000000111111110000000000000000U) >> 16U
```
or simpler
```
(lParam >> 16U) & 0b11111111U // or (lParam >> 16U) & 0xFFU
```
|
I tried to sort an array of Products by its unit price but the result doesn't work.
```
typedef struct {
int supply;
int totalPrice;
double unitPrice;
} Product;
int comparator(const void * a, const void * b) {
return (*(Product*) b).unitPrice - (*(Product*) a).unitPrice;
}
int main() {
Product m[3] = {
{18, 75, 4.17},
{15, 72, 4.80},
{10, 45, 4.50}
};
qsort(m, 3, sizeof(Product), comparator);
for (int i = 0; i < 3; i++) {
printf("unitPrice=%f\n", m[i].unitPrice);
}
}
```
|
comparatoris broken. It subtracts twodoublevalues and returns anint. Any fraction in the subtraction result is lost, so numbers less than one unit apart will be considered equal.
Fix it to return a non-zero number if the items differ.
|
It is clearly possible to computesqrt(x*x + y*y)without using thehypot(x,y)function. Why is this function part of the standard?
Is this related to some internal (hardware based) optimizations?
|
Thehypotfunction performs this calculation while avoiding overflows.
Section 7.12.7.3p2 of theC standardregarding thehypotfunction states:
Thehypotfunctions compute the square root of the sum of
the squares ofxandy, without undue overflow or underflow. A
range error may occur.
|
I am learning how to write some code in the Linux kernel, and i would like to start practicing writing code in the kernel, but my question is what is the process of building and running the modified kernel?
should I just each time, when I modify the kernel code, to recompile the kernel, reinstall it on my machine and then reboot my machine, or is there another way of doing this process in the real life, in the industry?
|
Well, easiest is if you can have the code you're modifying in amodule, then you can remove the old version and load in the new version.
Alternatively, you could run the kernel in a virtual machine inside your host computer! That way you need to only reboot the virtual machine, not the entire physical computer.
|
I am learning how to write some code in the Linux kernel, and i would like to start practicing writing code in the kernel, but my question is what is the process of building and running the modified kernel?
should I just each time, when I modify the kernel code, to recompile the kernel, reinstall it on my machine and then reboot my machine, or is there another way of doing this process in the real life, in the industry?
|
Well, easiest is if you can have the code you're modifying in amodule, then you can remove the old version and load in the new version.
Alternatively, you could run the kernel in a virtual machine inside your host computer! That way you need to only reboot the virtual machine, not the entire physical computer.
|
Is it possible to use a field more than 999 bytes in ISO8583?
I wanna to send data in a filed which has more than 999 bytes. What is the best solution?
Can I define a new type: LLLLVAR to do that? I think we are enable to do that in JPOS but I cannot find it inWIKI_ISO8583.
Note that I used an specialized library to do that in c.
|
Yes you can, as long as you agree with the other party the length of the length field.
In ISO8583, V2003 there are some fields defined as LLLLVAR such as DE 34 and 43 defined also in jPOS CMF.
I'm not sure it's defined in v87 of ISO8583 since I don't have the spec, which is on what the Wikipedia page is based on.
Either way the Wikipedia page is not fully comprehensive on the standard.
|
I really don't like when I have to navigate backwards in my includes.
I'd mutch more prefere if there would be a way to avoid that. Look at this folder for example:
Is there any way to tell the compiler (gcc) to start looking for includes from RootFolder, so I can say#include "Logic/Entitiy/Player.h"in my MainView.h/c or anywhere else, so I can avoid that unappealing backwards navigations.
|
You can pass include directories to your compiler. The configuration depends on the compiler. For gcc you set an include directory with-I.https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html
|
There is no code for this question at all..Just a simple question... As strings return their memory location\address but do int do the same or there is something else going on? || (pardon me if there's any mistake in this question I am just a beginner in programming and I just know the basic concepts of it.)||
|
You don't return a string, you return a pointer to a char.
When you return a pointer to a char (address of a char), a pointer (an address) is returned.char *x; ... return x;When you return a pointer to an int (address of an int), a pointer (an address) is returned.int *x; ... return x;When you return an int, an int is returned.int x; ... return x;
|
I am just starting to learn openssl for C. I am having some trouble figuring out the difference between theSSL_set_connect_statefunction and theSSL_connectfunction as they seem to do thee same thing on my system. Could someone explain what the difference is?
|
SSL_connectinvokesSSL_do_handshake, which performs the actual SSL handshake after invokingSSL_set_connect_state.
Full function:
```
int SSL_connect(SSL *s)
{
if (s->handshake_func == NULL) {
/* Not properly initialized yet */
SSL_set_connect_state(s);
}
return SSL_do_handshake(s);
}
```
|
Why does the code snippet 1 works but NOT code snippet 2
Code Snippet 1:
```
#define mkstr(x) #x
int main(void)
{
printf(mkstr(abc));
return (0);
}
```
Code Snippet 2:
```
int main(void)
{
printf(#abc);
return(0);
}
```
|
The first snippet works because it has a function-like macro defined in which you put anything, the value is correctly assigned as a constant.
OTOH, the second one has a syntactic error because the compiler doesn't expects that parameter passed inprintf(). Thus, the#is meaningless there.
|
This question already has answers here:How to set, clear, and toggle a single bit(27 answers)Closed3 years ago.
I'm trying to write a C function that takes auint64_tand replace it's nth byte to a given one.
```
void setByte(uint64_t *bytes, uint8_t byte, pos)
```
I know I can easily get the nth byte like so
```
uint8_t getByte(uint64_t bytes, int pos)
{
return (bytes >> (8 * pos)) & 0xff;
}
```
But I have no idea how to Set the nth byte
|
Try this:
```
void setByte(uint64_t *bytes, uint8_t byte, int pos) {
*bytes &= ~((uint64_t)0xff << (8*pos)); // Clear the current byte
*bytes |= ((uint64_t)byte << (8*pos)); // Set the new byte
}
```
|
I am trying to fix the error in the following C program, that I get in the terminal in VSCode ?
```
#include <stdio.h>
main()
{
printf("just one small step for coders.one giant leap for\n");
printf("programmers\n");
return 0;
}
```
Below is the error that I get while compiling in the VSCode terminal:
```
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
|
Try to put return data type of main function
```
int main(){
```
Maybe this is noy solution but this is the only reason that comes to mind.
|
The top image is compiled Chromium and the bottom one is a design I made in Photoshop
I downloaded the gclient files and can now see all the components that make the Chrome build. The files are a lot though and I didn't find the file responsible for this. Any help?
| ERROR: type should be string, got "\nhttps://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/ui/views/location_bar/location_bar_view.cc;l=1\n\nmost of the ui stuff you would want to customize is in chrome/browser/ui/views\n\nand most of the ui graphics are in\nui/resources/default_100_percent/\n\n200_percent is for the retina displays, basically 2x resolution\n" |
I get null memory using following code of malloc/calloc. Sometimes it fails to allocate memory for "name1" and then strcpy fails. Please guide.
```
struct testMalloc
{
char name1[90];
char name2[90];
struct testMalloc* ptr;
};
int main(int argc, char* argv[])
{
struct testMalloc* test = 0 ;
int size = 0;
size = sizeof(struct testMalloc);
printf("Size of struct is %d", size);
test = (struct testMalloc*) calloc(sizeof(struct testMalloc));
strcpy((test->name1), "hdshdssdsdfsfffffffffffffffffffffffffffffh");
return 0;
}
```
|
You do not include<stdlib.h>for the compiler to know the signature ofcallocand in this case it usesK&Rcalling convention.
If you include<stdlib.h>the code won't compile before to correctly call thecalloc.
|
When I write some code with ANSI escape sequence like....\e[4m ~ \e[0m,
I got the error that
C4129 'e': unrecognized character escape sequence
and the program show me that escape sequence did not set and just indicates\e[4Hello\e[0.
How can I fix it?
|
The\eis supposed to insert an ESC character (ASCII code 27), but it doesn't exist in standard C, only in some nonstandard extensions.
You can use\33instead1. (33 is the octal representation of decimal 27.)
1:This will work fine (and is the shortest way) for regular ANSI escape sequences since the following character will always be[. But in case you ever need to use the ESC character in other circumstances, please note that you'll need\033in case it is followed by a digit between 0 and 7, because otherwise that next digit would errornously be considered part of the octal number. As dxiv mentioned in the comments, it may be the case with some VT100 escape sequences.
|
I want my application to instantly draw all the data to a display. In windows there isSwapBuffers()function to do such kind of things, where you can do all the drawings to a second virtual window and then swap that virtual window with an existing one. OpenGL provides aglXSwapBuffers()function to do roughly the same. However I don't want to use it. Therefore, I am curios, what are the ways to implement this functionality in pure XLib
|
In X11 there are thePixmapresources which are considered asDrawable(likeWindow).
Then you can draw to aPixmapusing as many steps as necessary, and finally useXCopyArea()to send the resulting drawing to aWindow.
Note that aPixmapstands on the server side, like aWindow, so the final copy operation is local to the server.
|
What is the difference between
```
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
enum week day = Wed;
```
and
```
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int day = Wed;
```
in C?
I couldn't find what is the benefit of using variables of typeenumover using a regularint.
|
The benefit is that using anenummake your intentions clearer, both to people reading your code and to the compiler. For example, any half-way decent compiler will warn you if you use an enum with incompleteswitchcases:
```
switch (day) {
case Mon: printf("Monday\n"); break;
case Tue: printf("Tuesday\n"); break;
}
```
Here GCC (with-Wall) emits:
warning: enumeration value 'Wed' not handled in switch [-Wswitch]7 | switch (day) {
| ^~~~~~…
If the type ofdaywasint, you wouldn’t get this very helpful warning.
|
Command :
```
% cat <<EOF | cpp -DVERBOSE=3
#if VERBOSE >= 2
printf("trace message");
#endif
EOF
```
Output :
```
# 1 "<stdin>"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 362 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "<stdin>" 2
printf("trace message");
```
Anyone know how to suppress those lines such as# 1 "<stding>" 2, I need to include some instructions like# dockerfile syntax=experiementalin the input Dockerfile.
|
how to suppress those lines such as # 1 "" 2
Fromgcc manual:
-P
Inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers.
```
cpp -P ...
```
|
```
unsigned long fileSize = file.size();
byte buf[4];
buf[0] = (byte) fileSize & 0xFF;
buf[1] = (byte) (fileSize >> 8) & 0xFF;
buf[2] = (byte) (fileSize >> 16) & 0xFF;
buf[3] = (byte) (fileSize >> 24) & 0xFF;
```
can anyone explain me this code.assuming a file with a size of your choice
|
Supposing you wanted to split a decimal number 8375 into digits. You could do it this way:
```
unsigned value = 8375;
unsigned digit_0 = value % 10; // Gives 5
unsigned digit_1 = (value / 10) % 10; // Gives 7
unsigned digit_2 = (value / 100) % 10; // Gives 3
unsigned digit_3 = (value / 1000) % 10; // Gives 8
```
Well, the code you posted does just that. Only it splits the number intooctetswhich arepairs of hexadecimaldigits. I.e. every octet can take values in the range [0..255].
And the posted code uses bitwise operations:(a >> 8)is actually(a / 256), and(a & 0xFF)is(a % 256).
|
What is the difference between
```
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
enum week day = Wed;
```
and
```
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int day = Wed;
```
in C?
I couldn't find what is the benefit of using variables of typeenumover using a regularint.
|
The benefit is that using anenummake your intentions clearer, both to people reading your code and to the compiler. For example, any half-way decent compiler will warn you if you use an enum with incompleteswitchcases:
```
switch (day) {
case Mon: printf("Monday\n"); break;
case Tue: printf("Tuesday\n"); break;
}
```
Here GCC (with-Wall) emits:
warning: enumeration value 'Wed' not handled in switch [-Wswitch]7 | switch (day) {
| ^~~~~~…
If the type ofdaywasint, you wouldn’t get this very helpful warning.
|
Command :
```
% cat <<EOF | cpp -DVERBOSE=3
#if VERBOSE >= 2
printf("trace message");
#endif
EOF
```
Output :
```
# 1 "<stdin>"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 362 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "<stdin>" 2
printf("trace message");
```
Anyone know how to suppress those lines such as# 1 "<stding>" 2, I need to include some instructions like# dockerfile syntax=experiementalin the input Dockerfile.
|
how to suppress those lines such as # 1 "" 2
Fromgcc manual:
-P
Inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers.
```
cpp -P ...
```
|
```
unsigned long fileSize = file.size();
byte buf[4];
buf[0] = (byte) fileSize & 0xFF;
buf[1] = (byte) (fileSize >> 8) & 0xFF;
buf[2] = (byte) (fileSize >> 16) & 0xFF;
buf[3] = (byte) (fileSize >> 24) & 0xFF;
```
can anyone explain me this code.assuming a file with a size of your choice
|
Supposing you wanted to split a decimal number 8375 into digits. You could do it this way:
```
unsigned value = 8375;
unsigned digit_0 = value % 10; // Gives 5
unsigned digit_1 = (value / 10) % 10; // Gives 7
unsigned digit_2 = (value / 100) % 10; // Gives 3
unsigned digit_3 = (value / 1000) % 10; // Gives 8
```
Well, the code you posted does just that. Only it splits the number intooctetswhich arepairs of hexadecimaldigits. I.e. every octet can take values in the range [0..255].
And the posted code uses bitwise operations:(a >> 8)is actually(a / 256), and(a & 0xFF)is(a % 256).
|
This question already has answers here:How to use redirection in C for file input(4 answers)Closed3 years ago.
I want to make a program similar to "cat" that reads a text file.
ex) mycat abc.txt
And I add a few options such as "<" but it cannot read < as a parameter. ex) mycat < abc.txt
I am trying to use getopt function and other option works well except for "<".
How do I handle a command "<" as a parameter for my program in Linux?
|
<is not a parameter that the program reads. It's a shell input redirection. It means that the shell will make the specified file thestdinof the program.
What this means for you is that if you don't get any parameters then you read fromstdin.
|
This question already has answers here:How to escape double quotes in JSON(8 answers)Closed3 years ago.
I am using Visual Code Studio as my IDE, and wanted to write a simple snippet for printing:
```
printf("%d", );
```
the snippet:
```
"Print": {
"prefix": "printf",
"body": [
"printf("%d",$1);",
"$2"
],
"description": "print"
}
```
It is a JSON file, however it gives me an error with %d and doesnt treat %d as a string, I suppose. The error being:Expected commajson(514)
|
You need to escape double-quotes that appear in strings with a backslash, otherwise it looks like you're ending and restarting the string:
```
"Print": {
"prefix": "printf",
"body": [
"printf(\"%d\",$1);",
"$2"
],
"description": "print"
}
```
|
Simply, if I were to do:
```
typedef char arrayOne[10];
```
and in main:
```
char arrayTwo[10];
```
wouldmalloc(sizeof(arrayOne))take more memory thanmalloc(sizeof(arrayTwo))?
Or in other words; I'm using typedef to keep the code more simple, but is it worth it or I should just forget it because it uses unnecessary extra memory?
|
There's no relation between memory allocation &typedef. The keywordtypedefsimply creates aliases to make the long name datatypes into shorter & more meaningful to read.
|
This question already has answers here:How to use redirection in C for file input(4 answers)Closed3 years ago.
I want to make a program similar to "cat" that reads a text file.
ex) mycat abc.txt
And I add a few options such as "<" but it cannot read < as a parameter. ex) mycat < abc.txt
I am trying to use getopt function and other option works well except for "<".
How do I handle a command "<" as a parameter for my program in Linux?
|
<is not a parameter that the program reads. It's a shell input redirection. It means that the shell will make the specified file thestdinof the program.
What this means for you is that if you don't get any parameters then you read fromstdin.
|
This question already has answers here:How to escape double quotes in JSON(8 answers)Closed3 years ago.
I am using Visual Code Studio as my IDE, and wanted to write a simple snippet for printing:
```
printf("%d", );
```
the snippet:
```
"Print": {
"prefix": "printf",
"body": [
"printf("%d",$1);",
"$2"
],
"description": "print"
}
```
It is a JSON file, however it gives me an error with %d and doesnt treat %d as a string, I suppose. The error being:Expected commajson(514)
|
You need to escape double-quotes that appear in strings with a backslash, otherwise it looks like you're ending and restarting the string:
```
"Print": {
"prefix": "printf",
"body": [
"printf(\"%d\",$1);",
"$2"
],
"description": "print"
}
```
|
Simply, if I were to do:
```
typedef char arrayOne[10];
```
and in main:
```
char arrayTwo[10];
```
wouldmalloc(sizeof(arrayOne))take more memory thanmalloc(sizeof(arrayTwo))?
Or in other words; I'm using typedef to keep the code more simple, but is it worth it or I should just forget it because it uses unnecessary extra memory?
|
There's no relation between memory allocation &typedef. The keywordtypedefsimply creates aliases to make the long name datatypes into shorter & more meaningful to read.
|
We have docker files which based on alpine linux.
I want for the built container to check the version of themusllibrary ,
I mean run the container and and in RT check the musl version
how can I do that ?
I've tried something like
```
docker run -it --rm alpine /bin/ash
```
and run
```
musl -v
```
Got
```
/bin/ash: musl: not found
```
|
libcitself is an executable. You can run it and the usage message will print out the version:
```
/ # /lib/libc.musl-x86_64.so.1
musl libc (x86_64)
Version 1.1.24
Dynamic Program Loader
Usage: /lib/libc.musl-x86_64.so.1 [options] [--] pathname [args]
```
|
Now i have just started to learn graphics for rendering. I have spent a lot of errors trying to resolve this error.I have placed the glew32.dll file in system32,have placed the header files in the header files path of the devcpp,have set the path of glew32.lib and glew32s.lib from the compiler options. But still am getting "undefined reference to__imp_glewInit'" and "undefined reference to__imp_glewGetErrorString'". Please tell the error.
```
#include<stdio.h>
#include<glew.h>
#include<GL/gl.h>
#include<GL/glu.h>
int main()
{
GLenum err = glewInit();
if( GLEW_OK != err )
{
fprintf(stderr, "Error initializing GLEW: %s\n",
glewGetErrorString(err) );
}
return 0;
}
```
|
I think you should be using the glew32.lib. I am sure this answer will help,
https://stackoverflow.com/a/40988434/13876104
|
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 answered with facts and citations.Closed3 years ago.Improve this question
How to extract text from doc file using C language? I need free library, with simple function likechar* doc2txt(const char*)
|
I did not find any solution, so I created my own libraryhttps://github.com/uvoteam/libdocIt can be used for Python also
|
I have a piece of code that will be executed many times (5,000+), and an if statement that will be true only the first time. I've thought of using a "FIRST" variable and compare it each time, but it just seems like a waste to check it every single time, even if I know it's not needed.
```
bool FIRST = true;
void foo(){
if(FIRST){
/* do something only once */
FIRST = false;
}
/* something something... */
}
```
I also don't know if there is some compiler optimization that does this automatically, or another way to do it; if there is, please let me know.
And yes, I know that a mere if statement isn't a big thing, but it just annoys me.
|
If you're using gcc, there are macros calledunlikelyandlikelythat can allow it to make optimizations based on a condition.
In your case the condition will only be true the first time, so you would useunlikely:
```
if (unlikely(FIRST)) {
```
|
This is what I write:
```
const int MAX=100;
int main (){
int notas [MAX]={0};
```
The compiler says the following:
[Error] variable-sized object may not be initialized[Warning] excess elements in array initializer
When I writeMAXwith#define MAX 100, it works. But I don´t understand what's the matter with doing it this way?
|
In this case
```
const int MAX=100;
```
does not create a compile time constant, so the array is treated asVLA. By definition, VLAs can not be initialised, hence the error.
On the other hand,#define MAX 100is a pre-processor macro, and based on the textual replacement property, it results in a compile time constant value of100, then the array is not a VLA and can be initialized as per the initialization rules.
|
I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.
|
Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.
|
I have a piece of code that will be executed many times (5,000+), and an if statement that will be true only the first time. I've thought of using a "FIRST" variable and compare it each time, but it just seems like a waste to check it every single time, even if I know it's not needed.
```
bool FIRST = true;
void foo(){
if(FIRST){
/* do something only once */
FIRST = false;
}
/* something something... */
}
```
I also don't know if there is some compiler optimization that does this automatically, or another way to do it; if there is, please let me know.
And yes, I know that a mere if statement isn't a big thing, but it just annoys me.
|
If you're using gcc, there are macros calledunlikelyandlikelythat can allow it to make optimizations based on a condition.
In your case the condition will only be true the first time, so you would useunlikely:
```
if (unlikely(FIRST)) {
```
|
This is what I write:
```
const int MAX=100;
int main (){
int notas [MAX]={0};
```
The compiler says the following:
[Error] variable-sized object may not be initialized[Warning] excess elements in array initializer
When I writeMAXwith#define MAX 100, it works. But I don´t understand what's the matter with doing it this way?
|
In this case
```
const int MAX=100;
```
does not create a compile time constant, so the array is treated asVLA. By definition, VLAs can not be initialised, hence the error.
On the other hand,#define MAX 100is a pre-processor macro, and based on the textual replacement property, it results in a compile time constant value of100, then the array is not a VLA and can be initialized as per the initialization rules.
|
I'm trying to make changes and compile open source 3d printers firmware in eclipse. Added all the project related to firmware but it showing symbol could not be resolved error. The cause of error is IDE cannot find the symbols. How can I solve this. It's compiling properly and also working on board.
|
Found the solution in indexer of the eclipse used active configuration settings and it solved all the Indexer error. Thanks for the help guys.
|
Let's say that we have the following case:
```
#include <stdio.h>
#include <stdlib.h>
struct test {
int a;
int b;
};
int main()
{
struct test *ptest = malloc(sizeof(struct test));
struct test jtest;
ptest->a = 3;
ptest->b = 2;
jtest = *ptest;
free(ptest);
printf("a: %d\nb: %d\n", jtest.a, jtest.b);
return 0;
}
```
As I've freed the pointer toptest, and consequently the memory area that it refers to, my access tojtestis compromised after the free ofptest? Or when a make a dereference to assign the values ofjtestit's made a copy of the values present on the address ofptest?
|
In C, if you're not using pointers, a copy is always made. So, whenptestis freed,jteststill has its own copy of the memory.
|
How would I simplify all of this into one line?
```
REG &= ~BITA;
REG &= ~BITB;
REG &= ~BITC;
REG &= ~BITD;
REG &= ~BITE;
```
|
You can use|(bitwise or) operator.
```
REG &= ~(BITA | BITB | BITC | BITD | BITE);
```
|
I have a remote source of PCM audio samples which keeps changing the sample rate. It sometimes supplies 16Khz and the later 48Khz depending upon the bandwidth. I would like to convert them to FLTP through a filter, before feeding to an audio decoder. When I do that I get the error "Changing audio frame properties on the fly is not supported. [Invalid argument]".
Can someone please suggest a way this can be done?
Is it possible to create a filter graph with multiple buffer sources but only one sink?
|
I used swr_convert_frame() keeping an array of SwrContext * for different input sample rates.
|
I have a remote source of PCM audio samples which keeps changing the sample rate. It sometimes supplies 16Khz and the later 48Khz depending upon the bandwidth. I would like to convert them to FLTP through a filter, before feeding to an audio decoder. When I do that I get the error "Changing audio frame properties on the fly is not supported. [Invalid argument]".
Can someone please suggest a way this can be done?
Is it possible to create a filter graph with multiple buffer sources but only one sink?
|
I used swr_convert_frame() keeping an array of SwrContext * for different input sample rates.
|
```
//Assume "char str[n]" declared & initialized
printf("The String \"%s\"",str);
printf("contains %d bytes in RAM", sizeof(str));
```
Is there a way to write this code like in the below Java format in C language?
```
System.out.println("The String " + str + " contains " + sizeof(str) + " bytes in RAM"); //I know there is no //sizeof(...) in Java, i just wrote it to demonstrate :D
```
|
You can pass multiple arguments toprintf, for example:
```
printf("%d times %d equals %d\n", 3, 5, 3*5);
```
The order of your arguments must match the order in which the formatting specifiers (those starting with%) appear in the format string.
|
I am embedding a Java VM (JVM) using JNI in a DLL for a native application on Windows (altv-server.exe). Internally JNI_CreateJavaVM calls_setmode( _fileno(stdin), _O_BINARY )which causes the process to wait for Enter key input before it continues. The function succeeds but the waiting for input is undesirable.
The mode is in_O_TEXTprior to calling_setmode( _fileno(stdin), _O_BINARY).
This behaviour happens when the DLL is built with/MD.With/MDd, calling_setmodefrom the DLL will not wait for input, but the function call made fromjvm.dllstill causes the process to wait for input.
The server is built with/MD, and so it is required by the DLL to also be built with/MD.
|
It appears that the native application had a thread that was reading from stdin. Calling_setmode(_fileno(stdin), _O_BINARY)causes this undesirable behaviour.
Starting that thread after_setmode(_fileno(stdin), _O_BINARY)resolved this particular problem.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question
This code gives Segmentation Error can someone help. I've to XOR string "HelloWorld" with 0.
```
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int main()
{
char str[] = "Hello World";
int n = strlen(str);
char y[n];
for (int p=0;p<n;p++) {
y[p]=str[p]^0;
printf("%c",y[p]);
}
return 0;
}
```
|
Shouldn’t the char array be n + 1 size to store null character? At least that should be the issue on C, but I think it should be similar on c++
|
I'm trying to create a program that will print Accepted when a letter of the alphabet it entered, excludingu. Whenuis entered it prints declined.
```
#include <stdio.h>
int main(void) {
char val;
printf("Enter your letter : \n");
val = scanf("%c", &val);
if (val == 'u' || (val >= '0' || val <= '9'))
printf("DECLINED\n");
else
print("ACCEPTED\n");
return (0);
}
```
|
If you only want to accept letters i think you should convert char to int (ASCII values) and check like this
```
#include <stdio.h>
int main () {
char val;
int c;
printf("Enter your letter :\n");
scanf("%c", &val);
c = (int) (val);
if ( ( val != 'u') && (c >= 97 && c <= 122) || (c >= 65 && c <= 90)){
printf("ACCEPTED\n");
} else {
printf("DECLINED\n");
}
return (0);
}
```
|
i am trying to find factorial by recursively.My function works but why i recieve "segmenatation fault (core dumped)" when i input -1.
```
#include <stdio.h>
int fak(int number);
int main(){
int i;
printf("give me an integer: ");
scanf("%d",&i);
printf("factorial: %d\n",fak(i));
return 0;
}
int fak(int number){
if(number == 1 || number == 0){
return 1;
}
return number * fak(number - 1);
}
```
|
To answer the question: you will get a stack overflow because your recursive method will never end normally (see all the comments).
If you put in -1, the method will be called again with -2.
It depends on your stack-size when it will crash.
You can change your condition to:
```
if(number <= 1){
return 1;
}
```
Besides of that: the factorial of -1 doesn't exist.
|
I'm trying to create a program that will print Accepted when a letter of the alphabet it entered, excludingu. Whenuis entered it prints declined.
```
#include <stdio.h>
int main(void) {
char val;
printf("Enter your letter : \n");
val = scanf("%c", &val);
if (val == 'u' || (val >= '0' || val <= '9'))
printf("DECLINED\n");
else
print("ACCEPTED\n");
return (0);
}
```
|
If you only want to accept letters i think you should convert char to int (ASCII values) and check like this
```
#include <stdio.h>
int main () {
char val;
int c;
printf("Enter your letter :\n");
scanf("%c", &val);
c = (int) (val);
if ( ( val != 'u') && (c >= 97 && c <= 122) || (c >= 65 && c <= 90)){
printf("ACCEPTED\n");
} else {
printf("DECLINED\n");
}
return (0);
}
```
|
i am trying to find factorial by recursively.My function works but why i recieve "segmenatation fault (core dumped)" when i input -1.
```
#include <stdio.h>
int fak(int number);
int main(){
int i;
printf("give me an integer: ");
scanf("%d",&i);
printf("factorial: %d\n",fak(i));
return 0;
}
int fak(int number){
if(number == 1 || number == 0){
return 1;
}
return number * fak(number - 1);
}
```
|
To answer the question: you will get a stack overflow because your recursive method will never end normally (see all the comments).
If you put in -1, the method will be called again with -2.
It depends on your stack-size when it will crash.
You can change your condition to:
```
if(number <= 1){
return 1;
}
```
Besides of that: the factorial of -1 doesn't exist.
|
I'm trying to create a program that will print Accepted when a letter of the alphabet it entered, excludingu. Whenuis entered it prints declined.
```
#include <stdio.h>
int main(void) {
char val;
printf("Enter your letter : \n");
val = scanf("%c", &val);
if (val == 'u' || (val >= '0' || val <= '9'))
printf("DECLINED\n");
else
print("ACCEPTED\n");
return (0);
}
```
|
If you only want to accept letters i think you should convert char to int (ASCII values) and check like this
```
#include <stdio.h>
int main () {
char val;
int c;
printf("Enter your letter :\n");
scanf("%c", &val);
c = (int) (val);
if ( ( val != 'u') && (c >= 97 && c <= 122) || (c >= 65 && c <= 90)){
printf("ACCEPTED\n");
} else {
printf("DECLINED\n");
}
return (0);
}
```
|
i am trying to find factorial by recursively.My function works but why i recieve "segmenatation fault (core dumped)" when i input -1.
```
#include <stdio.h>
int fak(int number);
int main(){
int i;
printf("give me an integer: ");
scanf("%d",&i);
printf("factorial: %d\n",fak(i));
return 0;
}
int fak(int number){
if(number == 1 || number == 0){
return 1;
}
return number * fak(number - 1);
}
```
|
To answer the question: you will get a stack overflow because your recursive method will never end normally (see all the comments).
If you put in -1, the method will be called again with -2.
It depends on your stack-size when it will crash.
You can change your condition to:
```
if(number <= 1){
return 1;
}
```
Besides of that: the factorial of -1 doesn't exist.
|
With TCP, I'm designing some programs like next.
clients' recv in many threads are waiting for one server's send message. However, there is a condition. recv is waiting for a specific send message.
For example
client
```
thread 1: recv (key = 4)
thread 2: recv (key = 6)
thread 3: recv (key = 9)
```
server
```
send(value = A) for key 4 - send(value = B) for key 9 - send(value = C) for key 6
```
then, thread 1 should get value A, thread 3 should get value B, thread 2 should get value C
how can recv functiondistinguishserver send messages? Is there any good idea or solution?
Thanks.
|
recvdoesn't support content-filtered data receiving.
You should distinguish those kind of messages on your own.
|
```
struct date{
int date;
int month;
int year
};
struct date current_date;
```
I have this struct. Then I wanna store the current date in current_date. How can I do this using C language?
Thank You so much!
|
struct tmis a very standard structure for representing a broken down time representation with second resolution.
You would:
```
// get current time
time_t t = time(NULL);
struct tm *tm = localtime(&t);
// assign to your structure
current_date.date = tm->tm_mday;
current_date.month = tm->tm_mon + 1;
current_date.year = tm->tm_mon + 1900;
```
|
```
float sigma;
// ...
int kernel_size = ((6.0 * sigma) % 2 == 0) ? (6 * sigma + 1) : (6 * sigma);
```
In this line, I want to get the smallest integer bigger than 6*sigma value using ternary operator. By the waysigmais float.
I'm not sure that the above code is correct.I also cannot compile, gettingexpression must have integral type.
|
Your code is definitely wrong because it doesn't compile.
Usingceil(x)(returns smallest integer not less thanx), your calculation can be done like this:
```
float sigma;
// ...
float s6 = 6.0 * sigma;
float c = ceil(s6);
int kernel_size = c == s6 ? c + 1 : c;
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed3 years ago.Improve this question
I want to be able to build and execute the currently opened C file using a shortcut like in IDEs as I don't want to type a command every time I run.
|
Use a shell script that compiles and executes the file.
```
gcc file.c
./a.out
```
only works if you work with one file or #include, or you have to add the other files to the compiler.
As you probably work with a text editor, there are no other options than this, or doing it manually.
|
Why does the following instruction create an infinite list of negative numbers (-1, -3, -5, ...) if i=1?
```
while (i--)
printf("\n%i", --i);
```
|
```
i = 1 // 1
while (i--) // value of 'i--' is 1 is true; side-effect i = 0
printf("\n%i", --i); // print value of '--i' ie -1, side-effect i = -1
while (i--) // value of 'i--' is -1 is true; side-effect i = -2
printf("\n%i", --i); // print value of '--i' ie -3, side-effect i = -3
while (i--) // value of 'i--' is -3 is true; side-effect i = -4
printf("\n%i", --i); // print value of '--i' ie -5, side-effect i = -5
...
```
Note thatside-effectabove may occur before or after (or even during) the evaluation of rest of the expression.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed3 years ago.Improve this question
I want to be able to build and execute the currently opened C file using a shortcut like in IDEs as I don't want to type a command every time I run.
|
Use a shell script that compiles and executes the file.
```
gcc file.c
./a.out
```
only works if you work with one file or #include, or you have to add the other files to the compiler.
As you probably work with a text editor, there are no other options than this, or doing it manually.
|
Why does the following instruction create an infinite list of negative numbers (-1, -3, -5, ...) if i=1?
```
while (i--)
printf("\n%i", --i);
```
|
```
i = 1 // 1
while (i--) // value of 'i--' is 1 is true; side-effect i = 0
printf("\n%i", --i); // print value of '--i' ie -1, side-effect i = -1
while (i--) // value of 'i--' is -1 is true; side-effect i = -2
printf("\n%i", --i); // print value of '--i' ie -3, side-effect i = -3
while (i--) // value of 'i--' is -3 is true; side-effect i = -4
printf("\n%i", --i); // print value of '--i' ie -5, side-effect i = -5
...
```
Note thatside-effectabove may occur before or after (or even during) the evaluation of rest of the expression.
|
This question already has answers here:What does #x inside a C macro mean?(4 answers)Closed3 years ago.
I am new to C, what exactly does#algodo here?
```
#define run(algo) execute(&algo, #algo)
```
In the function definition ofexecuteit looks like it's somehow used for constant parameters ...
```
void execute(int (*algo_func)(int *, int, int), const char * algo_name)
{
int hit = 0, miss = 0;
...
```
I found this here at line 408:https://github.com/scandum/binary_search/blob/master/binary-search.c
|
It's apreprocessor stringizing operator. The preprocessor replaces#algowith whatever was passed to therun()macro converted to a string literal, so:
```
run(some_algorithm)
```
would be changed to:
```
execute(&some_algorithm, "some_algorithm")
```
|
This question already has answers here:What does #x inside a C macro mean?(4 answers)Closed3 years ago.
I am new to C, what exactly does#algodo here?
```
#define run(algo) execute(&algo, #algo)
```
In the function definition ofexecuteit looks like it's somehow used for constant parameters ...
```
void execute(int (*algo_func)(int *, int, int), const char * algo_name)
{
int hit = 0, miss = 0;
...
```
I found this here at line 408:https://github.com/scandum/binary_search/blob/master/binary-search.c
|
It's apreprocessor stringizing operator. The preprocessor replaces#algowith whatever was passed to therun()macro converted to a string literal, so:
```
run(some_algorithm)
```
would be changed to:
```
execute(&some_algorithm, "some_algorithm")
```
|
Because FILE struct is depended on implementation, is there any fail-proof way to resolve FILE "object" to the path of the file it was create with?
|
It seems it is either hard due toFILEstructure being implementation dependent, or a sign of improperly designed code. As it stands now,stdlibdoes not provide any way of checking this exact thing. There are ways to check file handles, but those are system dependent and are not practical.
|
I wrote this little code just to start learning someifstatements and C coding in general. However, there is an issue. When running it, if the largest element is the last one, the code won't recognize it. Why is that?
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int num[100];
int max;
int i;
printf("Enter 10 numbers: \n");
for(i = 1; i < 10; i++){
scanf("%d\n", &num[i]);
}
max = num[0];
for(i = 0; i < 10; i++){
if(max < num[i]){
max = num[i];
}
}
printf("The biggest nr is: %d", max);
return 0;
}
```
|
Your first loop should start from 0, not 1.
```
for(i = 0; i < 10; i++){
scanf("%d\n", &num[i]);
}
```
maxalready starts with an uninitialized value, here be dragons.
|
How does one definecopyanddeepcopymethods for a Python type defined in a C extension?
Looking at thedocumentation, there doesn't appear to be atp_slot for these methods.
|
There's no slot. You just define the same methods you'd define in Python, but in C. (Typically, that means implementing__reduce__and getting the default__reduce__-basedcopy.copyandcopy.deepcopybehavior, but you can also implement__copy__and__deepcopy__if you want.)
|
how do i print the highest index number?
|
The highest index is just one less than the length of the list. So:
```
puts [expr {[llength $list] - 1}]
```
To print the element at the largest index, you can refer to it as 'end':
```
puts [lindex $list end]
```
If I misunderstood the question and you want the index of the largest number in the list, that can be done as follows:
```
puts [lindex [lsort -indices -integer -decreasing $list] 0]
```
|
I have the following code:
```
#include <stdio.h>
int foo2(int *px, int *py)
{
int sum = *px + *py;
*px = *px + 1;
*py = *py - 1;
printf("foo2 : res=%d x=%d y=%d\n", sum, *px, *py);
return sum;
}
int main() {
int x = 4, y = 7, res;
res = foo2(&(x++), &(y--));
printf("%d", res);
return 0;
}
```
I need to incrementx, decrementy, then I need to pass them infoofunction as arguments.
I haveerror: lvalue required as unary ‘&’ operand. Also I tried to usex + 1andy - 1instead ofx++andy++.
How can I incrementxandyvalues and pass pointer to them infoo2function call? Is it possible?
|
You can use the comma operator:
```
res = foo2((x++, &x), (y--, &y));
```
However this is not very readable, so unless you have a really good reason it is better to write it as three separate statements:
```
x++;
y--;
res = foo2(&x, &y);
```
|
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double *array;
unsigned int size;
printf("Choose size for your number array: ");
scanf("%u", &size);
array = malloc(sizeof(double) * size);
return 0;
}
```
I memory allocatedsizeof(double) * size, which I don't know ifsizeof(double)is necessary, butsizeof(double)is not 1, so I don't know if I should either:
```
for (int i = 0; i < size; i++) {
}
```
For loop throughsizewithout multiply it withsizeof(double), or:
```
for (int i = 0; i < sizeof(double) * size; i++) {
}
```
For loop and multiply size withsizeof(double)as well? The reason why I'm asking is because I really want to be careful and prevent going over size.
For loop without multiplyingsizeof(double)or not?
|
You allocatesizeof(double) * sizememory to have array of doubles, the number of elements issize. So multiply inmalloc, don't multiply infor
|
Does a function such as
```
int GetSize(int type){
switch(type){
case 0:
return 15 * 16 + 17 / 2;
case 1:
return 25 * 6 + 7 / 42;
}
}
```
get optimized? I have a function such as this that will be called 100s of times per second but the return values for each case are always the same. I could put in a comment what each returned value represents if returning a hard coded value is that much faster, or I could leave it as such if the compiler pre calculates each result.
|
Does a function such as [...] get optimized?
Yes,heavily:
|
Let's say I have a struct and variables in C like this:
```
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
}my_type;
my_type a;
my_type a10[10];
```
With C99 is it certain that
sizeof(a) == 3? (and not 4 or 8)sizeof(a10) == 30? (and not 40 or 80)
|
With C99 is it certain thatsizeof(a) == 3?
This type will be used as color for an RGB888 framebuffer. So it's important to NOT have space between the adjacent RGB values.
```
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
}my_type;
```
No. The size may be 3 or 4 (or theoretically others, but not likely)
2 solutions:
Give up portability and use compiler specif code topackthe structure.Changestructto an array of 3uint8_tand adjust code.
I recommend the last.
|
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double *array;
unsigned int size;
printf("Choose size for your number array: ");
scanf("%u", &size);
array = malloc(sizeof(double) * size);
return 0;
}
```
I memory allocatedsizeof(double) * size, which I don't know ifsizeof(double)is necessary, butsizeof(double)is not 1, so I don't know if I should either:
```
for (int i = 0; i < size; i++) {
}
```
For loop throughsizewithout multiply it withsizeof(double), or:
```
for (int i = 0; i < sizeof(double) * size; i++) {
}
```
For loop and multiply size withsizeof(double)as well? The reason why I'm asking is because I really want to be careful and prevent going over size.
For loop without multiplyingsizeof(double)or not?
|
You allocatesizeof(double) * sizememory to have array of doubles, the number of elements issize. So multiply inmalloc, don't multiply infor
|
Does a function such as
```
int GetSize(int type){
switch(type){
case 0:
return 15 * 16 + 17 / 2;
case 1:
return 25 * 6 + 7 / 42;
}
}
```
get optimized? I have a function such as this that will be called 100s of times per second but the return values for each case are always the same. I could put in a comment what each returned value represents if returning a hard coded value is that much faster, or I could leave it as such if the compiler pre calculates each result.
|
Does a function such as [...] get optimized?
Yes,heavily:
|
Let's say I have a struct and variables in C like this:
```
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
}my_type;
my_type a;
my_type a10[10];
```
With C99 is it certain that
sizeof(a) == 3? (and not 4 or 8)sizeof(a10) == 30? (and not 40 or 80)
|
With C99 is it certain thatsizeof(a) == 3?
This type will be used as color for an RGB888 framebuffer. So it's important to NOT have space between the adjacent RGB values.
```
typedef struct {
uint8_t x;
uint8_t y;
uint8_t z;
}my_type;
```
No. The size may be 3 or 4 (or theoretically others, but not likely)
2 solutions:
Give up portability and use compiler specif code topackthe structure.Changestructto an array of 3uint8_tand adjust code.
I recommend the last.
|
I am translating a C program and have the following loop:
```
while (octaves--) {
/* do stuff */
}
```
should this be:
```
while (octaves > 0) do
begin
// do stuff
dec(octaves);
end;
```
or should be decrement bebeforethe loop content?
Thanks in advance. :)
|
Here is a minimal example of the c code
```
#include <stdio.h>
int main(){
int i = 3;
while(i--){
printf("%x,\n",i);
}
return 0;
}
```
this prints
```
2,
1,
0,
```
The same program can be written as
```
int main(){
int i = 3;
while(i){
i--;
printf("%x,\n",i);
}
return 0;
}
```
Which produces the same output. This code can now be directly translated to pascal.
```
while (i > 0) do
begin
dec(i);
// do stuff
writeln(i);
end;
```
|
Generally, How can I preventinteger overflowfrom happening in C programming language? I mean, Is there any functions to prevent?
And finally, Isinteger overflowgoing to get me hacked likebuffer overflowor etc?
|
Assume you have two int values a, b, and you want to check that a+b doesn't produce overflow or underflow.
There are two cases: a ≥ 0 and a ≤ 0. In the first case, you cannot have underflow. You have overflow if b > INT_MAX - a. In the second case, you cannot have overflow. You can have underflow if b < INT_MIN - a. As a single expression:
```
a >= 0 ? b > INT_MAX - a : b < INT_MIN - a
```
|
I have cross-compiled an executable from c code for an arm-based embedded system. When I execute the binary in the embedded system, it gives the following error:
```
line 1: syntax error: unexpected word (expecting ")")
```
I searched around, and figured out it is because the embedded system (some version of Linux) I am using does not havebashbut onlysh. Is it possible to make my compiled binary executable usingsh, without installing bash in it (which is troublesome)?
|
Binaries are not built for the shell program. They are built for a particular architecture and OS environment. All shell does is,fork()a child process and callsexec(). So it won't matter whether your host machine is havingbashorsh. Just make sure that binary is for the correct architecture and the machine. And you are indeed executing the binary, not the source.
|
I have cross-compiled an executable from c code for an arm-based embedded system. When I execute the binary in the embedded system, it gives the following error:
```
line 1: syntax error: unexpected word (expecting ")")
```
I searched around, and figured out it is because the embedded system (some version of Linux) I am using does not havebashbut onlysh. Is it possible to make my compiled binary executable usingsh, without installing bash in it (which is troublesome)?
|
Binaries are not built for the shell program. They are built for a particular architecture and OS environment. All shell does is,fork()a child process and callsexec(). So it won't matter whether your host machine is havingbashorsh. Just make sure that binary is for the correct architecture and the machine. And you are indeed executing the binary, not the source.
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed3 years ago.Improve this question
Is there any difference betweenint main(int argc, char* argv[])andint main(int argc, char** argv)I don't see any difference.And, which is better to use?
|
There is no semantic difference between
```
int main(int argc, char* argv[])
```
and
```
int main(int argc, char** argv)
```
. They have identical meaning. I personally prefer the former, as I think it more clearly conveys the significance of the second argument.
|
I was reading about Euclid's algorithm to calculate GCD and found the following code:
```
#include <stdio.h>
int main()
{
int m, n;
scanf("%d%d", &n, &m);
if (n < 0) n = -n;
if (m < 0) m = -m;
while(n != 0)
{
int temp = n;
n = m % n;
m = temp;
}
if(m != 0)
printf("The gcd is %d\n", m);
return 0;
}
```
But I have some questions:
why ifn<0orm<0we letn=-norm=-mWhat if m==0 what should I return? The smallest possible GCD is 1 but this function doesn't return anything in this case... (If we ignorereturn 0which is necessary for main)
|
The second part of the algorithm only works for non-negative values of m and n. Since gcd(m,n) = gcd(|m|,|n|) they are made positive.
If m = 0 and n != 0 the gcd is n and vica versa.
If both n and m are 0 the gcd is undefined because every number is a divisor of 0. Therefore, nothing is printed in this case.
|
I know this question has been discussed several times, but I didn‘t manage to detect whether a socket disconnected in C / C++ on Unix.
Is there any way to do so ?
Thx, Regards from Brooks
|
I assume that the socket might be closed by the peer.
It very depends on where you want to detect the disconnection.
If you are in the blockingrecv:manpage
These calls return the number of bytes received, or -1 if an error occurred. In the event of an error, errno is set to indicate the error.
When a stream socket peer has performed an orderly shutdown, the
return value will be 0 (the traditional "end-of-file" return).
If you want to know onsend:manpage
On success, these calls return the number of bytes sent. On error, -1 is returned, and errno is set appropriately.
|
i'm having process id from Task manager, i need to get the process name (complete with extension) from it.
is it possible?
i checked other questions, they are mostly command based.
|
Do you mean 'get the .exe filename by process ID' from C code?
If so, you may have interesting inOpenProcess()and followingGetModuleFileNameEx().
Don't forget toCloseHandle()after you get the exe filename. :)
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed3 years ago.Improve this question
Is there any difference betweenint main(int argc, char* argv[])andint main(int argc, char** argv)I don't see any difference.And, which is better to use?
|
There is no semantic difference between
```
int main(int argc, char* argv[])
```
and
```
int main(int argc, char** argv)
```
. They have identical meaning. I personally prefer the former, as I think it more clearly conveys the significance of the second argument.
|
I was reading about Euclid's algorithm to calculate GCD and found the following code:
```
#include <stdio.h>
int main()
{
int m, n;
scanf("%d%d", &n, &m);
if (n < 0) n = -n;
if (m < 0) m = -m;
while(n != 0)
{
int temp = n;
n = m % n;
m = temp;
}
if(m != 0)
printf("The gcd is %d\n", m);
return 0;
}
```
But I have some questions:
why ifn<0orm<0we letn=-norm=-mWhat if m==0 what should I return? The smallest possible GCD is 1 but this function doesn't return anything in this case... (If we ignorereturn 0which is necessary for main)
|
The second part of the algorithm only works for non-negative values of m and n. Since gcd(m,n) = gcd(|m|,|n|) they are made positive.
If m = 0 and n != 0 the gcd is n and vica versa.
If both n and m are 0 the gcd is undefined because every number is a divisor of 0. Therefore, nothing is printed in this case.
|
I know this question has been discussed several times, but I didn‘t manage to detect whether a socket disconnected in C / C++ on Unix.
Is there any way to do so ?
Thx, Regards from Brooks
|
I assume that the socket might be closed by the peer.
It very depends on where you want to detect the disconnection.
If you are in the blockingrecv:manpage
These calls return the number of bytes received, or -1 if an error occurred. In the event of an error, errno is set to indicate the error.
When a stream socket peer has performed an orderly shutdown, the
return value will be 0 (the traditional "end-of-file" return).
If you want to know onsend:manpage
On success, these calls return the number of bytes sent. On error, -1 is returned, and errno is set appropriately.
|
i'm having process id from Task manager, i need to get the process name (complete with extension) from it.
is it possible?
i checked other questions, they are mostly command based.
|
Do you mean 'get the .exe filename by process ID' from C code?
If so, you may have interesting inOpenProcess()and followingGetModuleFileNameEx().
Don't forget toCloseHandle()after you get the exe filename. :)
|
I have such an array:
```
const char arg_arr[][100] = {
"a",
"b",
"c",
"d",
};
```
and then I have such a methodParseCmdLine(const char *argv[]);
So, in order to pass myarg_arrI need to get pointer to it.
I try to invoke this method such wayParseCmdLine(*arg_arr)or like thisParseCmdLine(&arg_arr), but it doesn't work.
Question is - how to pass this arr as a pointer?
|
Change:
```
const char arg_arr[][100] = {
...
};
```
To:
```
const char *arg_arr[] = {
...
};
```
|
I am really curious about the full name of the flag IPC_EXCL when I uses function shmget in Linux. I know it is used with IPC_CREAT to ensure failure if the shared memory segment already exists. Any reply will be appreciated.
|
Hulk's guess in the comments on the question is correct: "EXCL" is an abbreviation of "exclusive". This is not apparent from the specification of IPC_EXCL itself (quotinghttps://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_ipc.h.html):
IPC_EXCLFail if key exists.
... but if you know that the flag was named by analogy with theopen(2)flagO_EXCL, then itisapparent from the specification ofthatflag (quotinghttps://pubs.opengroup.org/onlinepubs/9699919799/basedefs/fcntl.h.html):
O_EXCLExclusive use flag.
|
I have such an array:
```
const char arg_arr[][100] = {
"a",
"b",
"c",
"d",
};
```
and then I have such a methodParseCmdLine(const char *argv[]);
So, in order to pass myarg_arrI need to get pointer to it.
I try to invoke this method such wayParseCmdLine(*arg_arr)or like thisParseCmdLine(&arg_arr), but it doesn't work.
Question is - how to pass this arr as a pointer?
|
Change:
```
const char arg_arr[][100] = {
...
};
```
To:
```
const char *arg_arr[] = {
...
};
```
|
I am really curious about the full name of the flag IPC_EXCL when I uses function shmget in Linux. I know it is used with IPC_CREAT to ensure failure if the shared memory segment already exists. Any reply will be appreciated.
|
Hulk's guess in the comments on the question is correct: "EXCL" is an abbreviation of "exclusive". This is not apparent from the specification of IPC_EXCL itself (quotinghttps://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_ipc.h.html):
IPC_EXCLFail if key exists.
... but if you know that the flag was named by analogy with theopen(2)flagO_EXCL, then itisapparent from the specification ofthatflag (quotinghttps://pubs.opengroup.org/onlinepubs/9699919799/basedefs/fcntl.h.html):
O_EXCLExclusive use flag.
|
I wantscanfto accept only certain word, for example, if I want to accept eitherfooorbarfrom the user, I will write something like:
```
scanf(/*more input specifiers before and after*/ "%s[foo/bar]", demo);
```
This will return 1 and assigndemowith user input, only if the user have entered eitherfooorbar.
How can I achieve such functionality fromscanf?
Note: should be compatible with C89 and should work when usingfscanf.
|
Thescanf()function reads the data from thestdinand stores it according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.
Another work ofscanf()is that it does returns the number of successfully read items. It has no any working ability to compare the given string likefoo /OR/ bar.
|
I have a 1280 inodes per block in a EXT2 filesystem.
I want to know the status of the inode 1282, which I know is used.
I read the first byte of the inode bitmap corresponding to the second group.
I get 0x07, meaning 00000111, meaning that the inode 1282 is free, when it's not.
What's failing in my understanding?
Thanks
|
The first three inodes are marked as used. Your problem is you are reading the bits from left to right, whereas the lowest bit, i.e. the one on the right, shows you the state of the first inode, so you should be reading the bits from right to left.
|
so I am currently attempting to locally map my suspended thread when I pop my program into CFF explorer it says that the value of PIMAGE_NT_HEADERS is 00004550:
however while attempting to map it by myself my value comes out to be 00400080:
```
typedef struct pe {
PIMAGE_DOS_HEADER peDH;
PIMAGE_NT_HEADERS peNH;
} pe;
PE.peDH = (PIMAGE_DOS_HEADER)imgBase;
PE.peNH = (PIMAGE_NT_HEADERS)((u_char*)PE.peDH + PE.peDH->e_lfanew);
printf("[?] - NT Headers section is located at: 0x%x\n", PE.peNH);
```
|
it says that the value of PIMAGE_NT_HEADERS is 00004550
No, it doesn't. Look at it again more carefully. It actually says theSignaturefield of theIMAGE_NT_HEADERSstruct is00004550. But you are not printing theSignature, you are printing thePIMAGE_NT_HEADERSpointer itself. Not the same thing.
Change your print to this instead:
```
printf("[?] - NT Headers Signature is: 0x%08x\n", PE.peNH->Signature);
```
|
I've been experimenting with simple code and I noticed:
```
short x = 0x8765;
int y = (int)x;
printf("y = %d\n",y);
```
would print out "y = -30875".
I'm wondering why is it the case since when I convert 0x8765 from hex into decimal I got y = 34661.
|
The bit pattern of0x8765is negative in a 16-bit signed two's complement integer, but positive in a 32-bit signed two's complement integer.
In anint16_t:
```
0b1000011101100101
//^ sign bit set
```
In anint32_t:
```
0b00000000000000001000011101100101
//^ sign bit unset
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.