question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I want to read/write C float values from a binary file if it was created in C?
The file was created like this:
```
#include <stdio.h>
int main() {
const int NUMBEROFTESTELEMENTS = 10;
/* Create the file */
float x = 1.1;
FILE *fh = fopen ("file.bin", "wb");
if (fh != NULL) {
for (int i = 0; i < NUMBEROFTESTELEMENTS; ++i)
{
x = 1.1*i;
fwrite (&x,1, sizeof (x), fh);
printf("%f\n", x);
}
fclose (fh);
}
return 0;
}
```
Ifound a methodlike this:
```
file=open("array.bin","rb")
number=list(file.read(3))
print (number)
file.close()
```
But this won't guarantee to me the read value was a C float.
|
```
import struct
with open("array.bin","rb") as file:
numbers = struct.unpack('f'*10, file.read(4*10))
print (numbers)
```
This should do the job.numbersis atupleof the 10 values.
|
This question already has answers here:How can I suppress "unused parameter" warnings in C?(13 answers)Best way to suppress C warning "Unused variable x"? [duplicate](11 answers)Closed1 year ago.
In the function below I'm not using the parameter (void **arg). But since it's unused inside the function compiler gives me the error below:
```
error: unused parameter 'arg' [-Werror=unused-parameter]
bool decodeString(pb_istream_t *stream, const pb_field_t *field, void **arg)
```
I tried to suppress it by writing void(arg) inside the function without any luck.
Can anyone help me with the correct way?
|
Use the parameter in an expression casted tovoid. Then the parameter is "used".
```
bool decodeString(pb_istream_t *stream, const pb_field_t *field, void **arg)
{
(void)arg;
...
}
```
|
Specifically "the uri parameter may be a comma- or whitespace-separated list of URIs containing only the schema, the host, and the port fields" what does this mean?
Working with openLDAP in c.
|
It is simple list of URIs. The list can be separated by whitespace or comma:
Example:
http://myhost.com:4567,http://myhost1.com:45,http://myhost2.com:34545
or
http://myhost.com:4567 http://myhost1.com:45 http://myhost2.com:34545
|
So I tried to do very precise math in C using a__float128-type.
My code looks something like this:
```
#include <stdio.h>
int main() {
__float128 num;
}
```
I tried compiling it without any options like this:
```
gcc -o test test.c
```
The error I get is:
```
test.c:4:5: error: __float128 is not supported on this target
```
My gcc was installed using Homebrew on an x86 Macbook.
|
My gcc was installed using Homebrew on an x86 Macbook.
You may have done that, but thegccthat you ran to compile your test program is actually Apple clang disguised as GCC, as you'll see if you dogcc -v. Apple clang doesn't support __float128, but the real GCC does. Do/usr/local/bin/gcc-11 -o test test.cto use the real GCC that you installed, and then it should compile successfully.
|
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.Closed1 year ago.Improve this question
I have an array which is the months of the year:
```
const char *months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December" };
```
I want to take user input using scanf and then print the corresponding month to the number the user enters.
|
Take the user input with scanf saving it in an int variable. Then just use square brackets to access that position and print it.
Code would be
```
int a;
const char *months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December" };
scanf("%d", &a);
printf("%s",months[a]);
```
|
Imagine having this code and you don't really know what to except in the pointer of char (a string terminated or an array of chars (string not terminated)), is possibile to use strlen function on a safe way that handle not terminated string? (prevent overflows if the input is not a string terminanted) or can you fix it only by knowing the size of what you pass in input? so the function will becomefoo(char *c, size_t MAXSIZE)?
```
void foo(char *c) {
a = strlen(c);
}
```
|
We never know what really is behind a pointer. It could also only be a pointer to a single character.
Even by passing a size, you could imagine someone passing a bad pointer and an unrelated value.
C is not a safe language, it does not have runtime type checks. You can do anything you want, you can't prevent others from doing anything they want with your functions.
|
```
typedef struct _Text {
char *str;
int length;
int counter;
} *Text;
int main(void) {
Text txt= malloc(sizeof(Text));
char *txtStr="hi";
txt->str=txtStr;
return 0;
}
```
The struct simply doesn't work as expected, the char array given is not saved properly when checked.
|
```
typedef struct Text {
char *str;
int length;
int counter;
} Text;
```
is better to read
and then
```
int main(void) {
Text *txt = malloc( sizeof( Text ));
txt->str = malloc( sizeof( char ) *3);
strcpy( txt->str, "hi" );
printf("%s\n", txt->str );
return 0;
}
```
|
This question already has answers here:What kind of loop is for (;;)?(12 answers)Closed1 year ago.
Sometimes when im reading code it appears to be written for with no params to load
Like this:
```
for(;;)
{
/*Some piece of code*/
}
```
|
Any combination of the three expressions can omitted, including all of them.
If the first or third expression is omitted, no code is evaluated when those expression would be evaluated. (If both of these are omitted, one effectively has a purewhileloop.)
If the middle expression is omitted, it's as if a true expression was provided. This creates a loop that can only be exited usingbreak,return,exitand long jumps.
For example, the following loops until a valid answer is given.
```
int x;
for (;;) { // Or `while (1)`
display_prompt();
x = get_answer();
if (is_valid(x))
break;
printf("Invalid input\n");
}
```
|
I'm trying to compile my code from the old MS-DOS days and this doesn't seem to work with GCC:
```
typedef struct { int x,y,z; } vector;
inline void vect_add(vector& c,vector a, vector b)
{
c.x=a.x+b.x;
c.y=a.y+b.y;
c.z=a.z+b.z;
}
```
Basically I'm trying to return a struct which is later used as vector.x etc instead of rewriting it as a pointer to struct and rewriting all as vector->x etc
see(vector& c,
|
That is possibly valid C++, but it's not valid C.
In C, you need to use a pointer, a global var, or actually return a struct.
```
typedef struct { int x, y, z; } vector;
inline void vect_add(vector* c, vector a, vector b)
{
c->x = a.x + b.x;
c->y = a.y + b.y;
c->z = a.z + b.z;
}
vect_add(&c, a, b);
```
|
When I run this piece of code (from a tutorial to binary security), I always get an "%" in my zsh shell. Where do these percentage signs come from and how to get rid of them?
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buf[256];
memcpy(buf, argv[1],strlen(argv[1]));
printf("%s", buf);
}
% ./a.out 234
234%
% ./a.out 23466
23466%
% ./a.out 2
2%
```
|
I found this comment onreddit.
Zsh has a nice feature where it can tell you whether the previous
command did or didn't have a trailing newline. You can customize what
gets printed in this case. I have this option in my ~/.zshrc:PROMPT_EOL_MARK='%K{red} ' This will print a red block instead of
inverted % (or inverted # when you are root). I find it nicer.You can also set this parameter to empty.PROMPT_EOL_MARK=''
|
My code is a spellchecker program that checks words from an input file and that checks those words from the inputfile with a dictionary file.
I am trying to create a makefile and keep getting this error here makefile:2: *** missing separator. Stop. In Addition, I am writing my code in repl.it.
I don't know what is happening or why it is doing that?
This is my makefile contents:
```
a.out: main.o spell_lib.o spell.o
gcc *.o
main.o: main.c spell_lib.h spell_lib.c
gcc -c main.c
spell_lib.o: spell_lib.h spell_lib.c
gcc -c spell_lib.c
```
|
regarding:gcc *.o
this line must begin with a<tab>not a space
|
This question already has answers here:What kind of loop is for (;;)?(12 answers)Closed1 year ago.
Sometimes when im reading code it appears to be written for with no params to load
Like this:
```
for(;;)
{
/*Some piece of code*/
}
```
|
Any combination of the three expressions can omitted, including all of them.
If the first or third expression is omitted, no code is evaluated when those expression would be evaluated. (If both of these are omitted, one effectively has a purewhileloop.)
If the middle expression is omitted, it's as if a true expression was provided. This creates a loop that can only be exited usingbreak,return,exitand long jumps.
For example, the following loops until a valid answer is given.
```
int x;
for (;;) { // Or `while (1)`
display_prompt();
x = get_answer();
if (is_valid(x))
break;
printf("Invalid input\n");
}
```
|
I'm trying to compile my code from the old MS-DOS days and this doesn't seem to work with GCC:
```
typedef struct { int x,y,z; } vector;
inline void vect_add(vector& c,vector a, vector b)
{
c.x=a.x+b.x;
c.y=a.y+b.y;
c.z=a.z+b.z;
}
```
Basically I'm trying to return a struct which is later used as vector.x etc instead of rewriting it as a pointer to struct and rewriting all as vector->x etc
see(vector& c,
|
That is possibly valid C++, but it's not valid C.
In C, you need to use a pointer, a global var, or actually return a struct.
```
typedef struct { int x, y, z; } vector;
inline void vect_add(vector* c, vector a, vector b)
{
c->x = a.x + b.x;
c->y = a.y + b.y;
c->z = a.z + b.z;
}
vect_add(&c, a, b);
```
|
When I run this piece of code (from a tutorial to binary security), I always get an "%" in my zsh shell. Where do these percentage signs come from and how to get rid of them?
```
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buf[256];
memcpy(buf, argv[1],strlen(argv[1]));
printf("%s", buf);
}
% ./a.out 234
234%
% ./a.out 23466
23466%
% ./a.out 2
2%
```
|
I found this comment onreddit.
Zsh has a nice feature where it can tell you whether the previous
command did or didn't have a trailing newline. You can customize what
gets printed in this case. I have this option in my ~/.zshrc:PROMPT_EOL_MARK='%K{red} ' This will print a red block instead of
inverted % (or inverted # when you are root). I find it nicer.You can also set this parameter to empty.PROMPT_EOL_MARK=''
|
My code is a spellchecker program that checks words from an input file and that checks those words from the inputfile with a dictionary file.
I am trying to create a makefile and keep getting this error here makefile:2: *** missing separator. Stop. In Addition, I am writing my code in repl.it.
I don't know what is happening or why it is doing that?
This is my makefile contents:
```
a.out: main.o spell_lib.o spell.o
gcc *.o
main.o: main.c spell_lib.h spell_lib.c
gcc -c main.c
spell_lib.o: spell_lib.h spell_lib.c
gcc -c spell_lib.c
```
|
regarding:gcc *.o
this line must begin with a<tab>not a space
|
I have a library in C that has an objectIedConnectionthat handles the connection to a remote equipment.
```
IedConnection con = IedConnection_create();
IedConnection_connect(con, &error, hostname, tcpPort);
IedConnection_destroy(con);
```
I understand how to pass and returnctypeobjects likec_int, but how would I declare theIedConnection conobject in python usingctypes?
|
IedConnectionis a pointer to a structure (typedef struct sIedConnection * IedConnection). All pointers to structures should have the same representation, so you can just use a pointer toanystructure, and need not define its contents, unless you want to dereference it or do pointer arithmetic. Hence this should work:
```
from ctypes import *
class SIedConnection(Structure):
pass
IedConnection = POINTER(SIedConnection)
```
now you can useIedConnectionas thereturn typeand in theargument typesas usual.
|
While compiling this below given code, I got theerror: lvalue required as left operand of assignmentfor both the statementsstr+i = str+((len-1)-i);andstr+((len-1)-i) = temp;.
Why?
```
char* str_reverse(char *str, int len)
{
char *temp;
int i, mid;
if(len%2 == 0)
{
mid = len/2 - 1;
}
else
{
mid = (len-1)/2;
}
for(i=0;i<mid;i++)
{
temp = str+i;
str+i = str+((len-1)-i);
str+((len-1)-i) = temp;
}
return str;
}
```
|
stris an lvalue because it is a place in memory which contains an address.
str+iis only an rvalue because it is only an address
|
This question already has answers here:Returning an array using C(8 answers)Closed1 year ago.
How do I return a char array with any length in C?
```
char string[](int, int);
```
doesn't work; is there a way to return a char array?
|
You are unable to do that in C.
Instead, return a pointer.
```
char *string(int length, int unused) {
char *s = calloc(x, sizeof(char));
return s;
}
```
|
I want to create the following struct.
```
struct student
{
char name[n+1];
int length = n;
};
```
Where n is a specific integer. Is it possible to pass an argument to a struct or another solution to achieve something like this? Maybe pointers. So I want different structs based on length.
|
You can use a flexible array member:
```
struct student {
int length;
char name[];
};
```
The struct is allocated and initialized for lengthnwith:
```
struct student *s = malloc(sizeof *s + n + 1);
s->length = n;
// initialize s->name
strcpy(s->name, the_name_of_n_chars);
```
Remember to callfreeonswhen it is no longer used.
|
I've tried of reading articles of writing makefiles, I don't get it. I have a file structure like this.
```
- project
- bin
- main.exe
- src
- main.c
- inc
- ...
- ...
```
I've tried different answers here, but those are complex for me for a beginner to understand. I need to have three commands in my makefile:runcompileclean. I'm using GCC as a compiler.
|
```
hellomake: hellomake.c hellofunc.c
gcc -o hellomake hellomake.c hellofunc.c -I.
```
this is the optimal way to make an makeFile.
some cases you need to download even a plug in.
which software are you using?
|
This question already has answers here:How to reset SIGINT to default after pointing it some user-defined handler for some time?(2 answers)Closed1 year ago.
Hello I am making a program in c and I need to make asignal(SIGINT, SIG_IGN);but I need then at a certain point in the code to stop ignoring those signals, is there something like that?
|
You can set a signal to use its default signal handling by passingSIG_DFLtosignal.
```
signal(SIGINT, SIG_DFL);
```
|
I'm using the <dirent.h> header file in the function I'm referencing DT_REG, however, I'm getting error an saying " 'DT_REG' undeclared (first use in this function) "
The snippet of the code is:
```
DIR * dirp;
struct dirent * entry;
dirp = opendir(path);
if(entry->d_type == DT_REG) { //.... }
```
In my makefile I'm using "cc -std=c11 -Wall -Werror -pedantic".
Any ideas for the reason?
|
DT_REGis not part of ISO C11 extensions. Setting-std=c11strictly enables only features defined in C11 standard.
You can usefeature macrosto enable additional extensions. Asreaddir manualmentions, you need_DEFAULT_SOURCEmacro to enable file type constants.
You can do this in the source code before includingdirent.h
```
#define _DEFAULT_SOURCE
#include <dirent.h>
```
or via command line as a compiler option
```
cc -std=c11 -D_DEFAULT_SOURCE -Wall -Werror -pedantic
```
|
The problem is my code doesn't execute the for loop. It's just taking one input and printing it.
```
#include<stdio.h>
int main(){
int A[100], B[100], C[100], D[100];
int r[100];
for(int i = 0; i < 3; i++)
{
scanf("(%d+%d)x(%d-%d)", &A[i], &B[i], &C[i], &D[i]);
r[i] = (A[i]+B[i])*(C[i]-D[i]);
}
for(int k = 0; k < 3; k++)
{
printf("%d", r[k]);
}
return 0;
}
```
|
Assuming you input expressions are separated by a newline, when the second call toscanfis made, the first unread character is a newline rather than a left parenthesis. To makescanfskip leading whitespace characters, start the format string with a space, i.e." (%d+%d)x(%d-%d)".
https://pubs.opengroup.org/onlinepubs/000095399/functions/fscanf.html
|
What variable "a" do I need to have to make my "shot" variable equal to 0?
This is the code.
```
int shot = 0;
shot |= 1 << a;
```
|
There is no reliable solution to the problem.
Regarding the bit-shift operators,§6.5.7 ¶3 of the ISO C11 standardstates the following:
If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
Therefore, you can only solve this problem by invokingundefined behaviorand hoping that your compiler will give you the result that you want.
|
is it possible to buildpjsipwithopus-codecforwindowsas dll?
I built pjsua2.dll alone but seems no way to use opus with it.
|
I downloaded opus and pjsip , opened pjsip from visual studio solution, added opus projects to solution and made reference to them from libpjpproject, then build it using this linklink
|
I am getting from a sensor via UART communication every second 10 bytes. But I don't need all bytes, actually only certain bytes to work with. Now what I do is to save all bytes into an array and create two newuint8_t's and assign them the byte from the buffer array I need.
Is there a way to only receive and save the bytes I need in the first place instead of all 10?
```
uint8_t buffer[10];
HAL_UART_Receive_DMA(&huart4, (uint8_t*)buffer, 10)
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart4)
{
uint8_t value1 = buffer[4];
uint8_t value2 = buffer[5];
.
.
.
}
```
|
In DMA mode you need to provide the full size buffer. There is no other way as reception is not controlled by the core (it is done ion the background) and the DMA controller signals end (ad if you want half and error conditions) of the transaction only
|
I am getting from a sensor via UART communication every second 10 bytes. But I don't need all bytes, actually only certain bytes to work with. Now what I do is to save all bytes into an array and create two newuint8_t's and assign them the byte from the buffer array I need.
Is there a way to only receive and save the bytes I need in the first place instead of all 10?
```
uint8_t buffer[10];
HAL_UART_Receive_DMA(&huart4, (uint8_t*)buffer, 10)
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart4)
{
uint8_t value1 = buffer[4];
uint8_t value2 = buffer[5];
.
.
.
}
```
|
In DMA mode you need to provide the full size buffer. There is no other way as reception is not controlled by the core (it is done ion the background) and the DMA controller signals end (ad if you want half and error conditions) of the transaction only
|
I have the code below:
```
static char *name[] = {
"January",
"February",
"March",
};
printf("%s", name[0]);
```
When I passed printf withname[0], it printsJanuary. But shouldn't it print theaddressof January, since the array above stores apointerto January?
|
The conversion specifier%sinterprets the corresponding argument as a pointer to first character of a string that is outputted until the terminating zero character'\0'is encountered.
If you want to output the pointer itself then you should write
```
printf( "%p", ( void * )name[0] );
```
Pay attention to that in this declaration
```
static char *name[] = {
"January",
"February",
"March",
};
```
the string literals used as initializers are implicitly converted to pointers to their first characters and these pointers are stored in the arrayname.
|
```
#include <stdio.h>
#include <stdint.h>
struct s1
{
uint8_t a;
uint16_t b;
uint8_t c;
};
struct s2
{
uint8_t d;
uint8_t e;
};
int main()
{
struct s1 *d1;
struct s2 *d2;
d1->a = 1;
d1->b = 2;
d1->c = 3;
d2->d =4;
d2->e =5;
&d1->b = d2;
return 0;
}
```
Why doesn't&d1->b = d2;work?bis 32 bit and thestruct s2is also 32 bit? As we are just assigning the address.
If that line is changed tod1 = (void *)d2;It works without an error.
|
First. The pointerd1andd2are not initialized. Using this pointer invokes Undefined Behavior. To fix it I suggest making the the actual object with automatic storage.
```
struct s1 d1;
struct s2 d2;
```
You cannot assignd2tod1.bbecause the types do not match.struct s2anduint16_tare not compatible. To do this type of type punning usememcpy().
```
memcpy(&d1.b, &d2, sizeof d2);
```
|
This question already has answers here:Avoid trailing zeroes in printf()(16 answers)Print float/double without trailing zeros? [duplicate](5 answers)Closed1 year ago.
How can I variably influence the number of digits printed in C program?I do not want to write unnecessary zeros in decimal development
x=7
Output: 7
x=7.700
Output 7.7
x=7.77700
Output: 7.777
My point is not to have fixed printf ("%. 3lf", yourVariable); , but but it changed variably on the values I would send there
|
You can make use of%gFormat Specifierin C for this.
Working Fiddle
Working Code
```
#include <stdio.h>
int main() {
float number;
printf("Enter an integer: ");
// reads and stores input
scanf("%f", &number);
// displays output
printf("You entered: %g", number);
return 0;
}
```
|
```
#include <stdio.h>
#include <conio.h>
int sum();
//find the sum of two numbers entered by the user.
int main(){
int n, m;
printf("Enter two numbers: \n");
scanf("%d", &m);
scanf("%d", &n);
int result = sum(m, n);
printf(result);
getch();
return 0;
}
int sum(m, n){
int c;
c = m+n;
return c;
}
```
i was just writing a simple program with function but i don't know why it is not running it tells me to debug can someone tell me what is the problem with it
|
Change int sum() ; to int sum(int, int) ;
Change printf(result) to printf("%d", result) ;
Change int sum(m, n) to int sum(int m, int n) ;(https://i.stack.imgur.com/Z07cx.jpg)
Another way of writing above program is
(https://i.stack.imgur.com/VOXRY.jpg)
|
I have some questions regarding the storage allocator in Kernighan - Ritchie: The C Programming Language - The Unix System Interface, page 185-189?
It says on page 186:
The search for a free block of adequate size begins at the point (freep) where the last block was found; this strategy helps keep the list homogeneous.
As I see, we don't necessarily need freep, we could start each search from base.
How does this strategy keep the list homogeneous?Why do we need freep at all? Does it decrease search time? (I mean, only free blocks are in the list, so we can start anywhere, right?)
|
If you always start at the beginning, you will drain the beginning of the list of larger blocks (because they satisfy requests more easily). So the list will start with lots of smaller blocks, and requests for medium or larger sizes will have to traverse more of the list to get to something suitable.
|
I know this kind of initialisation is discouraged but I can't remember why, while it's working, so does anyone knows why this should be avoided :
```
typedef struct struct_test {
int a = 1;
int b = 2;
int c = 3;
} t_test;
```
thanks
|
It's illegal in C.
In C++ it's not discouraged. Unlike initializing in the constructor, it doesn't require you to list all fields the second time (seeDRY), making it harder to forget to initialize fields.
|
```
printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678);
```
I tried putting \n at the end of the series of floats to separate the line
```
printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678)\n;
```
|
That \n should be inside the strings of printf not after it
```
printf("%f %.3f %.2f %.1f \n", 4.5678, 4.5678, 4.5678, 4.5678);
```
|
I can understand the first solution.But in the second solution i am confused about the wayscanf, accept 4 values at the same time and apply them to theforloop.
```
//first solution
#include <stdio.h>
int main() {
int pin[4],i;
for(i=0; i<4; i++){
printf("Give value: ");
scanf("%d", &pin[i]);
}
return 0;
}
```
```
//second solution
#include <stdio.h>
int main() {
int pin[4],i;
printf("Give 4 values: ");
for(i=0; i<4; i++){
scanf("%d", &pin[i]);
}
return 0;
}
```
|
The difference is only that in the first example there is a printf that asks you for the input values at every iteration of the cycle while in the first example there is a printf (only one) before the cycle.
The operation that matters (the scanf) is exactly the same in the two examples.
|
I can understand the first solution.But in the second solution i am confused about the wayscanf, accept 4 values at the same time and apply them to theforloop.
```
//first solution
#include <stdio.h>
int main() {
int pin[4],i;
for(i=0; i<4; i++){
printf("Give value: ");
scanf("%d", &pin[i]);
}
return 0;
}
```
```
//second solution
#include <stdio.h>
int main() {
int pin[4],i;
printf("Give 4 values: ");
for(i=0; i<4; i++){
scanf("%d", &pin[i]);
}
return 0;
}
```
|
The difference is only that in the first example there is a printf that asks you for the input values at every iteration of the cycle while in the first example there is a printf (only one) before the cycle.
The operation that matters (the scanf) is exactly the same in the two examples.
|
I've seen a little bit of code that deals withunsigned short arraysand storing "strings" in them. But I am curious how one might go about converting or extracting the string out of the unsigned short array into a char array for use inprintf()for debugging purposes.
```
unsigned short a[5];
char b[5];
a[0] = 'h';
a[1] = 'e';
a[2] = 'l';
a[3] = 'l';
a[4] = 'o';
printf("%s\n", a);
// output is just the 'h'
```
From my recent understanding, an unsigned short is 2 bytes so the 'h' has a Null terminator with it. Whereas typically a char is used and each character is 1 byte.
Is there a good way to extract the "string" 'hello' and put it into a char[] so it can be printed out later? Iterate over theunsigned shortarray and store the value into achararray?
|
How to convert?:
```
char b[6];
for(size_t i = 0; i < 5; i++) b[i] = a[i];
b[5] = 0;
```
|
Context: C compiler option/Zeenables allMicrosoft extensions to C and C++.
A simple question: is it possible to enable specific language extensions (i.e. not all at once)?
|
/Zais super-ancient... ANSI 89. The/Zeflag is deprecated. Don't use either of them.
For modern language conformance, the/Zc,/permissive-, and/std:*switches are the way to go.
If you are looking for C rather than C++ conformance, seeMicrosoft Docsfor details on the new/std:c11and/std:c17switch in VS 2019 (16.8 or later).
|
I am usingntdll.libfunctions in my code to set the system timer to a higher resolution.
But when I build my project I get this error:
```
...
.../bin/ld.exe: ... undefined reference to `__imp_NtSetTimerResolution'
collect2.exe: error: ld returned 1 exit status
...
```
How do I tell the linker to link withntdll.libin my CMake?
|
This worked for me:
```
if (WIN32)
target_link_libraries(executable ntdll)
endif()
```
|
Apparently, I am trying to usegif-hlibrary for gif creation with qt 4.7 for a C++ project. After embedding the library to the project, I can generate GIF through my qt GUI app, however, the colours on the final/actual GIF are swapped. What I mean is that:below red framebecomes below blue frameand same goes for other way round (i.e. blue frame becomes red frame).
Just like above, below orange framebecomes below sky blue frameand same goes for other way round (i.e. sky blue frame becomes orange frame).
Could someone familiar with the library or graphics or gif creation in code guide me?
I am happy to provide more information about image capturing and such, as and when needed.
Thank you in advance.
|
Ok, I have managed to resolve the problem by using QImage::rgbSwapped() function. Thank you to @Pablo Yaggi particularly for the hint.
I will have to remove the code snippet from the question due to security reasons.
|
I read that C doesn't suppose function overloading. But in this Slide we can see it's not correct and my professor said: "How Is it possible that we have 2 different signatures for same function name in C?"
Can someone explain this?
|
It isn't possible. Code such as this:
```
int open(const char* path, int flags);
int open(const char* path, int flags, mode_t mode);
```
is invalid C and will not compile (but valid C++).
However, C supportsvariadic functionsand the oldopenfunction is implemented using that. It's actually declared as:
```
int open(const char *path, int oflag, ... );
```
Where the...allows a variable amount of arguments through the features ofstdarg.h.
|
I tried assigning a tuple to anintvariable. Here is my code.i = (12, 45, 58, -1, 90, 100);When I printi, it shows the value of100. How does tuple work in C language ?
Thanks
|
The right hand side expression is an expression with the comma operator
```
i = (12, 45, 58, -1, 90, 100);
```
Its value and the type is the value and the type of the last operand.
In fact the above statement is equivalent to
```
i = 100;
```
because other sub-expressions do not have a side effect.
From the C Standard (6.5.17 Comma operator)
2 The left operand of a comma operator is evaluated as a void
expression; there is a sequence point between its evaluation and that
of the right operand. Then the right operand is evaluated; the result
has its type and value.
|
The following code:
```
main(){
uint8_t id = 1;
uint8_t str[] = "shutdown 1";
uint8_t* (rcm)[];
rcm = &str; //line 83
```
Returns the warning in line 83:
```
invalid lvalue in assignment
```
Anyone know how can I solve that? I'm stucked on this for hours...
|
If you have an array declared like
```
uint8_t str[] = "shutdown 1";
```
then a pointer to the first element of the array will look like
```
uint8_t *rcm = str;
```
If you want to declare a pointer that will point to the whole array as a single object then you can write
```
uint8_t ( *rcm )[11] = &str;
```
As for this record
```
uint8_t* (rcm)[];
```
then it is not a declaration of a pointer. It is a declaration of an array with unknown size and with the element typeuint8_t *.
|
I need to spawn a long-running child process and then kill it from the parent code. At the moment I do like this:
```
int PID = fork();
if (PID == 0) {
execl("myexec", "myexec", nullptr);
perror("ERROR");
exit(1);
}
// do something in between and then:
kill(PID, SIGKILL);
```
This does the job in the sense that the child process is stopped, but then it remains as a zombie. I tried to completely remove it by adding:
```
kill(getpid(), SIGCHLD);
```
to no avail. I must be doing something wrong but I can't figure out what, so any help would be greatly appreciated. Thanks.
|
```
signal(SIGCHLD, SIG_IGN);
kill(getpid(), SIGCHLD);
```
Presto. No zombie.
By ignoring SIGCHLD we tell the kernel we don't care about exit codes so the zombies just go away immediately.
|
There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56.
Here's the code that I tried:
|
```
int sum;
sum=(int)num1+(int)num2;
printf("%d",sum);
```
or
```
printf("%d",(int)num1+(int)num2);
```
The datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!
|
I need to spawn a long-running child process and then kill it from the parent code. At the moment I do like this:
```
int PID = fork();
if (PID == 0) {
execl("myexec", "myexec", nullptr);
perror("ERROR");
exit(1);
}
// do something in between and then:
kill(PID, SIGKILL);
```
This does the job in the sense that the child process is stopped, but then it remains as a zombie. I tried to completely remove it by adding:
```
kill(getpid(), SIGCHLD);
```
to no avail. I must be doing something wrong but I can't figure out what, so any help would be greatly appreciated. Thanks.
|
```
signal(SIGCHLD, SIG_IGN);
kill(getpid(), SIGCHLD);
```
Presto. No zombie.
By ignoring SIGCHLD we tell the kernel we don't care about exit codes so the zombies just go away immediately.
|
There are two floating point numbers 23.54 and 33.22 have to make a program to add them with just left side integral value like 23+33=56.
Here's the code that I tried:
|
```
int sum;
sum=(int)num1+(int)num2;
printf("%d",sum);
```
or
```
printf("%d",(int)num1+(int)num2);
```
The datatype of num1 is float and I'm using (int) to typecast to integer type.Since we typecast the datatype this is called explicit typecasting!
|
so I'm actually trying to do this exercise;
input twointegernumber, with a >= 1 and b <= 2 power of 32. find the value of a + b
I know this is a simple task but the things is, for small numbers value it worked correctly ( like 20 + 9 = 29), but for value like 1788909566 + 2626399043 the result is incorrect (it should be 4415308609 but 120341313 came out)
this the code that I worked on :
```
int main() {
unsigned int a, b;
scanf("%u %u", &a, &b);
printf("%u + %u = %u", a, b, a + b);
return 0;
}
```
|
Always uselong longdata type while dealing with large numbers."%llu" is the format specifier for long long.
unsigned long long is of8 bytesand stores number in range of0to18,446,744,073,709,551,615
```
int main() {
unsigned long long a, b;
scanf("%llu %llu" , &a, &b);
printf("%llu + %llu = %llu", a, b, a + b);
return 0;
}
```
|
when I run the command
```
pidof lh
```
for lh program, I get two values. what are they. I was looking of pid oflhrunning program so I can increase the number of open files limithttps://unix.stackexchange.com/a/422732/211761
Why i am getting two values, if one is pid then what is the other
OUTPUT
```
37354 7968
```
which one above is pid and what is the other number. please tell
|
Both. You have two lh processes running.
|
I need to convert atime_tvariable into string of formatDD/MM/YYYY/HH:mm. I made the following function.
```
int time_to_str(time_t value, char *string)
{
struct tm *timeinfo;
time(&value);
timeinfo = localtime(&value);
strftime(string, sizeof(string), "%d/%m/%Y/%H:%M", timeinfo);
}
```
Testing the function with the following:
```
time_t variable = time(NULL);
char buffer[100];
time_to_str(variable, buffer);
printf("%s", buffer);
```
I get the following output and I don't see the problem... Any ideas?
```
07/10/
```
|
The second argument ofstrftimeshould be the size of the buffer to write to, i.e. 100 in this case.sizeof(string)results in the size of apointer to char, which is usually 4 or 8. Hence,strftimeonly writes several characters to thestringbuffer.
For more information, see the documentation forstrftime.
|
From thispostand thiscodebase, I know that there are pointers for
Youngest childYoungest siblingOldest sibling.
So withOldest child, how do I get?
I am thinking of access "children" pointer (current->children) and traverse to the end of that doubly linked list.
|
Get the oldest sibling of the youngest child:
```
current->p_cptr->p_osptr
```
|
Our activity requires to input 4 numbers, positive or negative and only add the negative numbers.
Example:
```
-30.22
10.50
-2.2
-1.8
```
Result is-34.22which sums up the negative numbers only.
We have not discussed the loop or array at this moment. Is it possible to solve in a mathematical equation? I can’t seem to find any answers if I try to code it.
Can it be solved using if-else-elseif statements?
|
Read the input into four variables, then use fourifstatements to add them to the total when they're negative.
```
float a, b, c, d;
scanf("%f %f %f %f", &a, &b, &c, &d);
float total = 0;
if (a < 0) {
total += a;
}
if (b < 0) {
total += b;
}
if (c < 0) {
total += c;
}
if (d < 0) {
total += d;
}
printf("%.2f\n", total);
```
You can also use the conditional operator.
```
float total = (a < 0 ? a : 0) + (b < 0 ? b : 0) + (c < 0 ? c : 0) + (d < 0 ? d : 0);
```
|
I have a code that uses std=c++20.
I want to use a C library that was build with old gcc version.
Should I recompile the C library using the same compiler ?
If no, how could you judge that the 2 ABIs are compatible?
|
There should be no problem using the library as it is. Don't forget to addextern "C"around the function prototypes.
More info:Using C Libraries for C++ Programs
|
From thispostand thiscodebase, I know that there are pointers for
Youngest childYoungest siblingOldest sibling.
So withOldest child, how do I get?
I am thinking of access "children" pointer (current->children) and traverse to the end of that doubly linked list.
|
Get the oldest sibling of the youngest child:
```
current->p_cptr->p_osptr
```
|
Our activity requires to input 4 numbers, positive or negative and only add the negative numbers.
Example:
```
-30.22
10.50
-2.2
-1.8
```
Result is-34.22which sums up the negative numbers only.
We have not discussed the loop or array at this moment. Is it possible to solve in a mathematical equation? I can’t seem to find any answers if I try to code it.
Can it be solved using if-else-elseif statements?
|
Read the input into four variables, then use fourifstatements to add them to the total when they're negative.
```
float a, b, c, d;
scanf("%f %f %f %f", &a, &b, &c, &d);
float total = 0;
if (a < 0) {
total += a;
}
if (b < 0) {
total += b;
}
if (c < 0) {
total += c;
}
if (d < 0) {
total += d;
}
printf("%.2f\n", total);
```
You can also use the conditional operator.
```
float total = (a < 0 ? a : 0) + (b < 0 ? b : 0) + (c < 0 ? c : 0) + (d < 0 ? d : 0);
```
|
I have a code that uses std=c++20.
I want to use a C library that was build with old gcc version.
Should I recompile the C library using the same compiler ?
If no, how could you judge that the 2 ABIs are compatible?
|
There should be no problem using the library as it is. Don't forget to addextern "C"around the function prototypes.
More info:Using C Libraries for C++ Programs
|
I'm asking, of course, in terms of the actual "bit data" returned.
In other words, can the following function ever returnfalse:
```
bool func(uint x, uint y)
{
return x / y == (uint)((int)x / (int)y);
}
```
?
|
Absolutely it can. 4294967295 / 2 == 0x7fffffff, but -1 / 2 == 0.
The big value is of typeuint32_twhere all bits are set, and -1 is also a 32-bit valueint32_twhere all the bits are set. When the top bit of the parameters is set, you should expect different results. The exception isa / a == 1, for both signed and unsigned divisions, whena != 0.
The thing is that the compiler knows to emit a different instruction for the CPU, when the arithmetic is between signed vs unsigned operands.
|
Here is an example code:
```
int* arr = (int*)malloc(2 * sizeof(int));
arr = arr + 1;
*arr = 11;
arr[-1] = 22;
int x = arr[0]; // x = 11
int y = arr[1]; // y = 194759710
```
After a memory allocationarrpointer is incremented. I have expected to get the following results:
```
x == 22
y == 11
```
Could you explain how it works ?
|
When you setxandy, you forgot thatarrno longer points on allocated memory.
This code do what you want:
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int* arr = (int*)malloc(2 * sizeof(int));
int *original = arr;
arr = arr + 1;
*arr = 11;
arr[-1] = 22;
int x = original [0]; // x = arr[-1]
int y = original [1]; // y = arr[0]
printf("%d, %d\n", x, y);
}
```
|
I did not define both symboles SYMBOL1 and SYMBOL2, and I'm supprised when I see that the printf is called in the following code:
```
#include <stdio.h>
int main()
{
#if (SYMBOL1==SYMBOL2)
printf("Hello World");
#endif
return 0;
}
```
Could you please explain why? any reference to the standard?
|
As per the ISO C standard (C11 6.10.1 Conditional inclusion):
After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers (including those lexically identical to keywords) arereplaced with the pp-number 0,and then each preprocessing token is converted into a token. The resulting tokens compose the controlling constant expression which is evaluated ...
In other words, your expression becomes0 == 0, which is obviously true. Hence theprintfis included in the source stream.
|
Here is an example code:
```
int* arr = (int*)malloc(2 * sizeof(int));
arr = arr + 1;
*arr = 11;
arr[-1] = 22;
int x = arr[0]; // x = 11
int y = arr[1]; // y = 194759710
```
After a memory allocationarrpointer is incremented. I have expected to get the following results:
```
x == 22
y == 11
```
Could you explain how it works ?
|
When you setxandy, you forgot thatarrno longer points on allocated memory.
This code do what you want:
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int* arr = (int*)malloc(2 * sizeof(int));
int *original = arr;
arr = arr + 1;
*arr = 11;
arr[-1] = 22;
int x = original [0]; // x = arr[-1]
int y = original [1]; // y = arr[0]
printf("%d, %d\n", x, y);
}
```
|
I did not define both symboles SYMBOL1 and SYMBOL2, and I'm supprised when I see that the printf is called in the following code:
```
#include <stdio.h>
int main()
{
#if (SYMBOL1==SYMBOL2)
printf("Hello World");
#endif
return 0;
}
```
Could you please explain why? any reference to the standard?
|
As per the ISO C standard (C11 6.10.1 Conditional inclusion):
After all replacements due to macro expansion and the defined unary
operator have been performed, all remaining identifiers (including those lexically identical to keywords) arereplaced with the pp-number 0,and then each preprocessing token is converted into a token. The resulting tokens compose the controlling constant expression which is evaluated ...
In other words, your expression becomes0 == 0, which is obviously true. Hence theprintfis included in the source stream.
|
I want to check if a line begins with the charatcer "#". My current code gives me a segmenation fault when I run it. How do I get the first character from a char*?
```
int checkLine(char* line){
char l [250];
strcpy(l,line);
char first_char = l[0];
//Check for comment
if (first_char == "#"){
return 0;
}
return 1;
}
```
|
you just got to change the If statement, instead of using "#" you should use '#', as you're representing a char, not a String. Btw, there is no need to copy your first char into a variable, you can useif (l[0]=='#')
|
Fread apparently knows the place where it last stopped, by that I mean this:
```
while(fread(buffer, 1, 1, file))
{
…
}
```
This loop would continue the next time where it stopped the last time. I assume it just moves thefilepointer forward, but could someone explain if it’s exactly like that?
|
The functionfreadreads from a stream, which is not necessarily a file. Streams can also be linked to consoles/terminals. Some streams are seekable and have a file position indicator, some do not. Streams which are linked to actual files usually do have a file position indicator.
The functionfreaditself does not advance any file position indicator (it does not callfseek). It just reads from the stream.
If a stream has a file position indicator, then theruntime librarywill advance the file position indicator, whenever a read takes place on the stream. It does this for all reads on the stream, not just forfread.
|
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.Closed1 year ago.Improve this question
I want to know how can I see the functions and the contents of a library in C language?
|
isnm libconfig.a | c++filtwhat you are looking for?
|
I am using gurobi solver to solve MIP. It's an NP-hard formulation with many constraints. It takes a significantly large amount of time to find an optimal solution; so, I had to add time constraints to the problem. I do not require to save the solution, and value of variables obtained by gurobi in the specified time only, but require to save the upper bound, and solution gap as well which get reported when we solve MIP. May you provide a way to do that?
|
I found a solution,Gurobi websitehas given all the attributes and these can be used in some other languages, specificallyC, C++, C#, Java, and VBAin addition to python; fortunately, there is attribute MIPGap and ObjBoundC that meets my specification.model.Runtimeprovides the time duration in which problem was solved; ifmodel.Runtime>= Time Constraint thenmodel.MIPGapprovidesMIPGap = abs(ObjVal - ObjBound)/ abs(ObjVal), andmodel.ObjBoundCprovides'ObjBound'dubble.
|
I am trying to convert a range of ip addresses contained in a text file using inet_pton function. I need to get ip adresses strings from the text file and pass as src address parameter to inet_pton(). After i check inet_pton() return 0 not 1.
Please, i would be grateful for any help
```
whitelist= fopen("/home/...../whitlist.txt","r");
while(fgets(line, sizeof(line), whitelist) ) {
printf("%s", line);
}
if(inet_pton (AF_INET,line, &a)==1){
printf("1");
} else if(inet_pton (AF_INET,line, &a)==0){
printf("0\n");
} else {
printf("-1");
}
```
|
I do not know the function but it seems you need to remove the new line character. For example
```
while(fgets(line, sizeof(line), whitelist) ) {
line[ strcspn( line, "\n" ) ] = '\0';
puts( line);
}
```
|
So basically I'm trying to reverse a word (a single word, not a string with multiple words) and I've managed to reverse the word using this
```
{
int end, x;
end = strlen(myString) - 1;
for (x = end; x >= 0; --x) {
printf("%c", myString[x]);
}
}
```
(myString is defined somewhere else in the code)
But here's the kicker, I need to print the reversed word like this:
```
printf("The word reversed is '%c'", myString);
```
And I've no idea how to actually take the word reversed by the for loop and putting it into the second printf command. Any ideas?
|
Here you are.
```
for ( size_t i = 0, n = strlen( myString ); i < n / 2; i++ )
{
char c = myString[i];
myString[i] = myString[n - i - 1];
myString[n - i - 1] = c;
}
printf("The word reversed is '%s'\n", myString);
```
|
I am using gurobi solver to solve MIP. It's an NP-hard formulation with many constraints. It takes a significantly large amount of time to find an optimal solution; so, I had to add time constraints to the problem. I do not require to save the solution, and value of variables obtained by gurobi in the specified time only, but require to save the upper bound, and solution gap as well which get reported when we solve MIP. May you provide a way to do that?
|
I found a solution,Gurobi websitehas given all the attributes and these can be used in some other languages, specificallyC, C++, C#, Java, and VBAin addition to python; fortunately, there is attribute MIPGap and ObjBoundC that meets my specification.model.Runtimeprovides the time duration in which problem was solved; ifmodel.Runtime>= Time Constraint thenmodel.MIPGapprovidesMIPGap = abs(ObjVal - ObjBound)/ abs(ObjVal), andmodel.ObjBoundCprovides'ObjBound'dubble.
|
I am trying to convert a range of ip addresses contained in a text file using inet_pton function. I need to get ip adresses strings from the text file and pass as src address parameter to inet_pton(). After i check inet_pton() return 0 not 1.
Please, i would be grateful for any help
```
whitelist= fopen("/home/...../whitlist.txt","r");
while(fgets(line, sizeof(line), whitelist) ) {
printf("%s", line);
}
if(inet_pton (AF_INET,line, &a)==1){
printf("1");
} else if(inet_pton (AF_INET,line, &a)==0){
printf("0\n");
} else {
printf("-1");
}
```
|
I do not know the function but it seems you need to remove the new line character. For example
```
while(fgets(line, sizeof(line), whitelist) ) {
line[ strcspn( line, "\n" ) ] = '\0';
puts( line);
}
```
|
So basically I'm trying to reverse a word (a single word, not a string with multiple words) and I've managed to reverse the word using this
```
{
int end, x;
end = strlen(myString) - 1;
for (x = end; x >= 0; --x) {
printf("%c", myString[x]);
}
}
```
(myString is defined somewhere else in the code)
But here's the kicker, I need to print the reversed word like this:
```
printf("The word reversed is '%c'", myString);
```
And I've no idea how to actually take the word reversed by the for loop and putting it into the second printf command. Any ideas?
|
Here you are.
```
for ( size_t i = 0, n = strlen( myString ); i < n / 2; i++ )
{
char c = myString[i];
myString[i] = myString[n - i - 1];
myString[n - i - 1] = c;
}
printf("The word reversed is '%s'\n", myString);
```
|
I need to make a code that have the output of 1 to 10 when you input the number 1 and 10, but also have the output of 10 to 19 when you input the number 10 and 10.
I've tried the following :
```
#include <stdio.h>
int main()
{
int N;
int M;
scanf ("%d %d", &N, &M);
for (int i = N ; i <= M ; i ++)
while (N <= M) {
printf ("%d\n", N ++);
}
return 0;
}
```
but when I put 10 and 10, the output is also 10.
Thanks for your answer in advance, I only recently started learning and I'm already stuck.
|
```
for ( int i = N; i < ( N + M ); i++ )
printf( "%d\n" , i )
```
Just a loop from the bottom number, to the max. From your description, I assume the max is N + M.
Alternatively, you can loop fro0toM, but do addition in the output to get the min back in.
```
for ( int i = 0; i < M; i++ )
printf( "%d\n" , i + N )
```
|
I am programming a microcontroller (PSoC5), which doesn't have a system time.
What is the best way to generate a seed to initializesrand?
TIA
|
If the chip has ADCs, one option is to take advantage of noise picked up on the ADCs. Basically, you can take a few reads of the ADCs, then bitwise AND to keep the least significant bit. Then use the all of the least significant bits sampled to generate your seed.
|
I am writing a C program to sum up prime numbers below a certain limit (9 for now).I expect 17 but the compiler gave me an unexpected output of 32781.
```
#include <stdio.h>
#include <stdbool.h>
bool isprime(int n);
int main(){
const int LIMIT=9;
int sum;
for (int j=1;j<LIMIT;j++){
if (isprime(j)){
sum+=j;
}
}
printf("%d",sum);
return 0;
}
bool isprime(int n){
if (n<=1){
return false;
}
else{
for(int i=2;i<n;i++){
if (n%i==0){
return false;
break;
}
}
return true;
}
}
```
Does anyone understand why this happened?
|
You declarredint sum;but didn't give sum a starting value, so it's basically reading garbage from memory. In c you need to initialize your variables properly.int sum = 0;should fix the problem.
If you are using clang as your compiler, compiling using -Wall should warn you about this.
|
I'm reading a C program where a function is declared like so:
```
__global__ void square(float *d_out, float *d_in);
```
what does the__global__specifier mean?
|
It is not standard C, only some extension or#define.
It looks like CUDA.
__global__function is executed on GPU, it can be called from CPU or the GPU.
Calling__global__functions is often more expensive than__device__.
If it is a#define, compile the file with the-E(gcc) or similar option and see how this macro is expanded.
|
I'm trying to wrap a C project with swig for Python.
I have a .h file I'm including in swig with %include. I'd like everything in the header file to be wrapped.
Is there anything I can do to handle the below error, without having to edit the source header file.
test.h
```
#define SEPARATOR "-"
#define SEPARATOR_SIZE ((int)sizeof(SEPARATOR))
typedef char SEPARATOR_ARRAY [SEPARATOR_SIZE];
```
test.i
```
%module test
%{
#include "test.h"
%}
%include test.h
```
After runningswig -python test.iI gettest.h:3: Error: Syntax error in input(1).
Using swig version 4.0.2.
|
Found the answer:
Swig only supported sizeof(<type>). Since this question there has been a commit to swig's github which handles the parsing of some further values in sizeof, such as "foo" 'f' and 300, but this still seems to cause compilation issues later on.
https://github.com/swig/swig/commit/7ab24e7e865e0f1281f002fefdaba11b80416ea2
|
I'm doing a shell from scratch. If I store all tokens in an arraychar**, what I supposed to put in a string of arraychar**when quote is empty?
Example:
```
input>echo "" "" "" | cat -e
output>(space)(space)(space)$
```
|
If you're mimicking POSIX shells then each""would tokenize to an empty string. The pipeline as a whole should tokenize to:
```
char *tokens[] = {"echo", "", "", "", "|", "cat", "-e"};
```
|
One of the changes for the upcoming C2x standard seems to be the
Removal of K&R function definitions
From what i understand the K&R style definitions is the reason why we have to declare a function that takes no parameters as
```
void foo(void);
```
instead of
```
void foo();
```
Does the removal of the K&R style in C2x mean we can/should now simply use empty brackets for functions that are taking no paramers like in other languages?
|
K&R style function definitions are things like
```
int foo(a, b)
int a;
int b;
{
/* function body here*/
```
They are completely orthogonal to the question of(void)vs()in a function declaration
|
What’s the difference between the amount of decimal values in adoubledata type and along doubledata type in c?
|
C does not require a difference in the amount of significant decimal digits betweendoubleandlong double. They may be the same.
To report the number of significant decimal digits a floating point type canat leastfaithfully encode, seexxx_DIG.
```
#include <float.h>
printf("long double %d\n", LDBL_DIG); // min: 10, Typically 15, 18 or 33
printf("double %d\n", DBL_DIG); // min: 10, Often 15
printf("float %d\n", FLT_DIG); // min: 6, Often 6
```
|
In what situations we need to use.hfile and when to use the.cfile in C.Are they two alternatives for a same purpose?.Please explain.
|
Never include .c filesIf you include something, it should be a .h file.Code goes into code files, .c.Headers, .h files, contain only what can be compiled more than once, i.e. declarations, macro definitions, more includes.If necessary, headers use reinclusion guards.
Whenever you feel tempted to include a .c file, you instead want to add it to your project so that it gets processed during building, i.e. gets compiled by its own and in a further build step gets linked into the created binary.
|
since I'm fairly new to C, so this might be a dumb question.
I aimed to use the bitwise operators & to do bit masking.
For example:
If inputs are 0x00F7 and 0x000F,my program should returns 0x0007. However, the output of 0x007&0x000F is just 7, 0x0077&0x00FF is just 77. So is there any way I can count the characters of a hexadecimal number so that I can know how many zeros should I print out?
```
printf("%X",0x077&0x00FF);
```
|
You don't need to count.You can getprintfto pad the number for you, just specify the maximum length like so:
```
printf("%04X", 0x77 & 0xff);
```
Note that when you write an integer (no quotes) it makes no difference if you write 0x0077 or 0x77.
Only when you useprintfto output a string zeros can be added for visibility.
|
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.Closed1 year ago.Improve this question
```
#include <stdio.h>
int main() {
char char1 = 'M';
char char2 = 'A';
char char3 = 'L';
char char4 = "I";
char char5 = "K";
printf("My name is %c%c%c%c%c",char1,char2,char3,char4,char5);
return 0;
}
```
|
```
char char3 = 'L';
char char4 = "I";
```
Can you spot the difference?
If not then the latter is wrong and it should be
```
char char4 = 'I';
```
|
I'm learning and tinkering with the C programming language. Unfortunately, While learning and playing with the do-while loop, I'm confused. I wrote and ran a program to increment a variable from 1 to 100 with condition i<=100; the code ran successful, but when I changed the condition of the do-while loop to i==100, the output confuses me because only 1 is printed on the console. Please help.
The code below gives the expected output.
```
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i<=100);
}
```
The code below gives output 1.
```
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i==100);
}
```
Thank you.
|
The second one loops ifi == 100. It is not the truth (as i == 1) on the first iteration and loop exits.
|
I want to know if there is a way to print all the memory locations that say an int variable is stored in.
Example:
```
#include <stdio.h>
int main()
{
int x = 5;
int *y = &x;
printf("%p", (void*)y);
}
```
Example output: 0x100000000001
This will show the memory address that the first byte of x is stored in, but I want to see the memory address of each byte that it is stored in.
Is there any way to do this? Or do I just assume the following memory place values since they're consecutive?
i.e. the other memory locations of this int would be:
0x100000000002?
0x100000000003?
0x100000000004?
|
a way to print all the memory locations that say an int variable is stored in.
Sure. Form a loop [0...sizeof(int)).
```
int main() {
int x = 5;
void *y = &x;
for (size_t i = 0; i < sizeof x; i++) {
printf("%p\n", (void*)((char *)y + i));
}
}
```
|
I have been readingthisand have a doubt what is correct and portable way to print this datatype?
```
uint_fast8_t
uint_fast16_t
uint_fast32_t
uint_fast64_t
```
Signed as well.
|
include<inttypes.h>and use the macros therein
```
#include <inttypes.h> // <inttypes.h> also includes <stdint.h> on its own
uint_fast8_t a = 0;
uint_fast16_t b = 0
uint_fast32_t c = 0;
uint_fast64_t d = 0;
printf("%" PRIuFAST8 " %" PRIuFAST16 " %" PRIuFAST32 " %" PRIuFAST64 "\n", a, b, c, d);
```
|
I'm learning and tinkering with the C programming language. Unfortunately, While learning and playing with the do-while loop, I'm confused. I wrote and ran a program to increment a variable from 1 to 100 with condition i<=100; the code ran successful, but when I changed the condition of the do-while loop to i==100, the output confuses me because only 1 is printed on the console. Please help.
The code below gives the expected output.
```
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i<=100);
}
```
The code below gives output 1.
```
#include<stdio.h>
int main(){
int i=1;
do{
printf("\n%d\n",i);
++i;
} while(i==100);
}
```
Thank you.
|
The second one loops ifi == 100. It is not the truth (as i == 1) on the first iteration and loop exits.
|
I want to know if there is a way to print all the memory locations that say an int variable is stored in.
Example:
```
#include <stdio.h>
int main()
{
int x = 5;
int *y = &x;
printf("%p", (void*)y);
}
```
Example output: 0x100000000001
This will show the memory address that the first byte of x is stored in, but I want to see the memory address of each byte that it is stored in.
Is there any way to do this? Or do I just assume the following memory place values since they're consecutive?
i.e. the other memory locations of this int would be:
0x100000000002?
0x100000000003?
0x100000000004?
|
a way to print all the memory locations that say an int variable is stored in.
Sure. Form a loop [0...sizeof(int)).
```
int main() {
int x = 5;
void *y = &x;
for (size_t i = 0; i < sizeof x; i++) {
printf("%p\n", (void*)((char *)y + i));
}
}
```
|
I have been readingthisand have a doubt what is correct and portable way to print this datatype?
```
uint_fast8_t
uint_fast16_t
uint_fast32_t
uint_fast64_t
```
Signed as well.
|
include<inttypes.h>and use the macros therein
```
#include <inttypes.h> // <inttypes.h> also includes <stdint.h> on its own
uint_fast8_t a = 0;
uint_fast16_t b = 0
uint_fast32_t c = 0;
uint_fast64_t d = 0;
printf("%" PRIuFAST8 " %" PRIuFAST16 " %" PRIuFAST32 " %" PRIuFAST64 "\n", a, b, c, d);
```
|
I'm very new to fork() processes and in the given code below
```
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
int n = 4;
for(i=0; i<n; i++)
fork();
printf("hello\n");
return 0;
}
```
prints out something like
```
cse [prompt] ./Program1
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
cse [prompt] hello
hello
hello
hello
hello
hello
```
Why exactly does the prompt print out again before finishing printing all the hellos? It doesn't really make sense to me.
|
save each PID returned by FORK().
Then use the functionwaitpid()for each sub process, so the main process does not exit until all the sub processes (the child processes) have exited.
|
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed1 year ago.
```
#include<stdio.h>
void main(){
char marital[5];
printf("enter your marital details-");
scanf("%s",&marital);
if(marital=="male"){
printf("you are insured");
}
}
```
|
```
char gender[7];
scanf("%s",&gender);
char *message=(!strcmp(gender,"male"))?"gender is male":"gender is female";
printf("%s\n",message);
```
|
I have a question. I have a twin-engine boat and I want to implement an autopilot in it. Using GPS alone my boat goes to the destination like a sine wave, unfortunately for 300m. Just like the picture below.
I Use RadioLink M8N GPS SE100 (http://radiolink.com.cn/doce/UploadFile/ProductFile/SE100Manual.pdf) and STM32. It has a built-in geomagnetic sensor HMC5983. Is it possible to use this sensor and GPS to let my boat go straight?
I don't know much about all those Kalman filters, Fusion, etc.
My question is what should I use, apart from the GPS itself, what kind of sensors and filters to make my boat sail in a straight line.
Thanks in advance for the tips and hints.
|
It is important to position a boat. If you only use poor GPS receiver, you couldn't do this. In order to solve this, you should apply UKF(unscented kalman filter) with fusion of GPS and INS.
|
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed1 year ago.
```
#include<stdio.h>
void main(){
char marital[5];
printf("enter your marital details-");
scanf("%s",&marital);
if(marital=="male"){
printf("you are insured");
}
}
```
|
```
char gender[7];
scanf("%s",&gender);
char *message=(!strcmp(gender,"male"))?"gender is male":"gender is female";
printf("%s\n",message);
```
|
I have a question. I have a twin-engine boat and I want to implement an autopilot in it. Using GPS alone my boat goes to the destination like a sine wave, unfortunately for 300m. Just like the picture below.
I Use RadioLink M8N GPS SE100 (http://radiolink.com.cn/doce/UploadFile/ProductFile/SE100Manual.pdf) and STM32. It has a built-in geomagnetic sensor HMC5983. Is it possible to use this sensor and GPS to let my boat go straight?
I don't know much about all those Kalman filters, Fusion, etc.
My question is what should I use, apart from the GPS itself, what kind of sensors and filters to make my boat sail in a straight line.
Thanks in advance for the tips and hints.
|
It is important to position a boat. If you only use poor GPS receiver, you couldn't do this. In order to solve this, you should apply UKF(unscented kalman filter) with fusion of GPS and INS.
|
I am trying to call a C function from COBOL and expecting a reply from it.
I am new to this interfacing.
COBOL code:
```
ENTER C "ADD" USING A,B.
```
C code:
```
int ADD(int a,int b)
{
return a+b;
}
```
I want to get the sum value from the C function for further processing in COBOL.
|
In COBOL
```
EXTENDED-STORAGE SECTION.
01 MYVAR EXTERNAL.
05 DATA-01 PIC X(20).
```
In C
```
/*Add necessary includes */
extern char MYVAR[21];
void change_Cobol_Variable()
{
/*you can use MYVAR as normal C-variable*/
sprintf(MYVAR, "%s","Something");
}
```
If it is integer declare appropriate variables as per your need :)
|
I am trying something in C on hp-nonstop(tandem),
As part my task is to wait for sometime.
I try to use the
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("Something");
sleep(5);
printf("Something");
fflush(stdout);
}
}
```
It's compiling without any problem,
While running it is givingABENDED: each time different no.
|
The result callingsleep()from guardian environment is undefined. That might be leading to ABEND that you mentioned. If you want to wait for some time in guardian hp-nonstop environment, you should callDELAY(). It takes centi-seconds as arguments. So if you want to add delay of 5 seconds, you should call it asDELAY (500). You also need to include the header#include<cextdecs(DELAY)>
|
From my understanding, C pipes are like a special kind of file, where internally, the kernal keep tracks of the openings and closings from each process in a table.see the post here
So in that sense:
Is it possible for 1 single pipe to be connected by multiple processes?If it is possible, can multiple processes read the same data?If 2 is possible, will they be reading the same data, or does reading the data "empty" the data?
For example: process 1 writes into pipe, can process 2,3,4 read the data that process 1 wrote?
|
Yes, multiple processes can read from (or write to) a pipe.
Butdata isn't duplicated for the processes. Once data has been read from the pipe by one process, it's lost and available only to the process that actually read it.
Conversely, there's no way to distinguish data or from which process it originated if you have multiple processes writing to a single pipe.
|
This question already has answers here:Accessing variadic function arguments without stdarg(2 answers)Closed1 year ago.
I'd like to know if there is a way of iterating through a variable argument lisf without using the va_arg function.
If so, can someone show me an example please?
|
No,va_argis the only mechanism provided by standard C for iterating over variadic arguments.
There may be other ways on specific implementations (e.g. inspecting stack memory based on how an ABI defines its layout), but they will be non-portable, and there is rarely any good reason to use anything besidesva_arg.
|
quick question here...
What is the difference between...
```
if ((flags & bit1) == bit1) {
// ...
}
```
and...
```
if (flags & bit1) {
// ...
}
```
?
That's all. Pretty sure this has been answered before, but I haven't been able to find it.
|
The first checks whetherflagshas all of the bits set wherebit1is also set. The second checks whetherflagshas any (i.e. at least one) of the bits set wherebit1is also set (or vice versa; in other words, whether there's any common set bits). Ifbit1has a single bit set, then there is no difference between "any" and "all".
|
While reading thegetcman page, I came across:
may beimplemented as a macro which evaluates stream more than once.
So,getcmight be implemented as a function as well - what exactly means byevaluates stream more than once?
|
Consider a function:
```
FILE *getstream(void);
```
And a code:
```
int c = getc(getstream());
```
In casegetcis a function,getstreamwill be called only once, its result will be stored in a temporary variable/register and passed togetc.
In casegetcis a macro, let say something like:
```
#define getc(s) ((s) == NULL) ? -1 :_getc(s))
```
it will get expanded into:
```
int c = (((getstream()) == NULL) ? -1 :_getc(getstream()));
```
That is it will callgetstream()twice. In casegetstreamhas some side effects (using IO, modifying some global state), the flow of the program will be different between the two cases and one must be aware of this.
|
This question already has answers here:Assignment in ternary operator(3 answers)Closed1 year ago.
This is a code in C, which is generating this error:
error: lvalue required as left operand of assignment
Code:
```
#include <stdio.h>
int main()
{
int m =4 ; int n =5;
int c=0;
m>n?c=40: c=20;
printf("%d",c);
}
```
But when I use the brackets in ternary operator it's generating output without error.
```
#include <stdio.h>
int main()
{
int m =4 ; int n =5;
int c=0;
m>n?(c=40): (c=20);
printf("%d",c);
}
```
Output: 20
Why is this happening?
|
m>n?c=40: c=20;
Your expression is the same as below
```
(m > n ? c = 40 : c) = 20;
((m > n) ? (c = 40) : c) = 20;
```
which may make the error more obvious.
|
I am new to C (coming previously from Python). I am confused over this part of code:
```
#include <stdio.h>
#define square(x) x*x
int main()
{
int x = 36/square(6);
printf("%d", x);
return 0;
}
```
I don't know why macro square(x) is not producing output 1 and why is it printing 36? Can you shed some light on this?
|
You need to wrap the macro in parentheses, like this:
```
#define square(x) (x*x)
```
The way you've written it,36/square(6)expands to36/6*6, which is evaluated as(36/6)*6, or 36.
With parentheses, it will correctly be evaluated as36/(6*6), or 1.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.