question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I saw a pi calculate algorithm on a website and it looks like that:
```
#include <stdio.h>
int a[52514],b,c=52514,d,e,f=1e4,g,h;
main(){
for(;b=c-=14;h=printf("%04d",e+d/f)){
for(e=d%=f;g=--b*2;d/=g){
d=d*b+f*(h?a[b]:f/5);
a[b]=d%--g;}
}
}
```
it was said this code was based on this expansion,but i do not understand the relative between the code and the expansion.
pi= sigma( (i!) ^2*2^(i+1))/(2i+1)!
(i=0 to infinite)
Could you help me explain it?Thanks.
|
```
pi+3=sigma( (m!)^2 * 2^m * m / (2*m)! ) (m=1 to infinite).
```
Algorithm's S Pflouffe use it.
|
So this is a Bit maniuplation excercise that im confused about how they convert letters to the numbers, i think these arent binary so i dont know what they mean.
Can anyone suggest an approach?
Here's two examples of encryption: "cats" and "kittens".Pairs: "ca ts" "ki tt en s_" (_ represents a space) into ints: 25441
29811 27497 29812 25966 29472 XOR with 31337: 6408 3610 4352 3613
7943 2377
|
The decimal quintet for each couple of letters is just the decimal representation of the concatenated hex values of the characters in ASCII, eg:
```
"ca" = 0x63 0x61 = 0x6361 = 25441
```
Same story for the XOR key which is
```
31337 = 0x7A69
```
Indeed
```
0x6361 ^ 0x7A69 = 0x1908 = 6408 in decimal
```
|
This question already has answers here:Structure member assignment causing syntax error when not inside a function(5 answers)Closed7 years ago.
I'm trying to declare a dummyhead*as global variable but the IDE is giving this error:
```
initializer element is not constant
```
How could I fix that?
```
typedef struct MyNode{
struct MyNode *next;
int value;
}Node;
//Declare a global variable
Node *head = malloc(sizeof(Node));
head->next = NULL;
```
|
The obvious thing to do is just to declare the head variable as a global but then do the initialisation within a function.
```
typedef struct MyNode{
struct MyNode *next;
int value;
} Node;
Node *head;
int main (int argc, char **argv)
{
head = malloc(sizeof *head);
if (!head) {
/* error */
exit(-1);
}
head->next = NULL;
return 0;
}
```
|
I usually work in Java and I was given some C code, I am not finding this in any documentation -- it probably doesn't help that I'm not sure what it should be doing so I don't know where in documentation to look!
```
variable = (arg0 + arg1 == arg2 ? 0x1 : 0x0) & 0xff;
```
|
Both the mask with0xffand the ternary operator are redundant.
The first operationarg0 + arg1 == arg2is a simple comparison.
C does not have boolean types for the comparison operators, the result is of typeintand its value is either0for false or1for true.
The ternary operator, almost the same as Java's, is redundant as it evaluates as0x1for non0and0x0for0.
The bitwise mask operator&is also redundant because0 & 0xffis0and1 & 0xffis1.
Overall, this expression simplifies to justvariable = (arg0 + arg1 == arg2);which can be written more explicitly as
```
if (arg0 + arg1 == arg2)
variable = 1;
else
variable = 0;
```
|
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.Closed7 years ago.Improve this question
I have Cygwin, but can't figure out how to install GCC, Nano, Emacs or anything of the sort. Any help is appreciated.
|
You should select the installation of gcc and g++ when installing cygwin.
Here is a screenshot:
Also a quick google search gave methisandthiswhich may also answer your question about nano and emacs
|
I am having a problem with years inmktime().
Every time I pass a year lower than 1970 into mystruct tmand then run themktime()function to convert my structure, it fails (returns -1).
Does anyone have any idea why and if I can make this work somehow?
|
That is never going to work, since it's by definition outsidethe epoch, which is the start for Unix time.The manual pagestates:
Thectime(),gmtime()andlocaltime()functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
If it fails to convert the input into Unix time, it's documented to return-1so that's why you're seeing that result.
|
I am trying to create a https server that uses the ssl context. Everything works out fine for this code for TLS clients
```
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
long options = SSL_OP_ALL |SSL_OP_NO_SSLv2 |SSL_OP_NO_SSLv3;
```
This effectively disables sslv2 and sslv3 and enables certain bug fixes.
I want to keep the disabling sslv3 part optional. But removing of SSL_OP_NO_SSLv3 still does not make sslv3 work.
```
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
long options = SSL_OP_ALL |SSL_OP_NO_SSLv2 ; // SSLV3 still does not work
```
I use curl as the client:
```
curl -vk --sslv3 "https://IP/hello_world"
* Server aborted the SSL handshake
* Closing connection 0
```
For non sslv3 everything works fine.
|
The problem was in the configure section of the library. It was compiled with no ssl2 or ssl3 as below
no-ssl2 no-ssl3
Hence sslv3 did not work with sslv23.
|
I wrote a C program as follows:
```
void foo(int *a) {
if (a[1000] == a[1000]) {
printf("Hello");
}
}
int main() {
int *a;
foo(a);
return 0;
}
```
I was expecting this program to crash because I did not allocate the memory at &a[1000], but the program actually did not crash and printed "Hello". I compiled the program with command
```
gcc -O0 foo.c
```
What might be the reason for this?
|
Accessing memory places that has not been allocated is undefined behaviour.
Now, this can lead to eitherseg fault, if the memory you are accessing is restricted for your program.
Or, as in your case, it wont have any defined effects. It will probably be reading garbage values left by the previous programs. This kind of behavior is called undefined.
It may be working in your case for a particular time, but it will definitely won't work all the time.
|
I have two uint32_t variables.
These have following values -
```
uint32_t a = 0x00002000;
uint32_t b = 0x00c00000;
```
I want these two variable to be merged so they give the result0000200c.
If I simply doa+b, it does not return the correct result. Could anyone please help?
Edit - I need to put Bit number 31-20 of b to bit number 11-0 of a.
|
Bits 31-20 ofbcan be isolated by doing(b & 0xFFF00000).
Bits 11-0 ofacan be isolated by doing(a & 0x00000FFF).
Then you need to shift thebvariable to the right by 20 bits before combining it witha. Putting it all together, you get
```
uint32_t answer = ((b & 0xFFF00000) >> 20) | (a & 0x00000FFF);
```
|
I am changing my code to meet the MISRA standard. I have come across the warning
Required Rule 10.1, Prohibited Implicit Conversion: Non-constant argument to function.
```
memcpy(&Final_buff[index], Main_cal, buffer_size);
// where buffer_size is uint8, uint8 *Final_buff, and const uint8 *buffer
```
Then I changed above for a small test:
```
memcpy(&Final_buff[index], Main_cal, 12u);
```
which is accepted by MISRA. The thing is I can't hardcode the value there. How can I get rid of this warning?
|
This should solve your MISRA problem:
```
memcpy(&Final_buff[index], Main_cal, (size_t) buffer_size);
```
Rule 10.1 doesn't allow an implicit conversion in several situations, including "the expression is not constant and is a function argument", which is the situation you were running into.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question
I have char array like
```
char* str = 0x058f;
```
What should i do to convert this value to int and uint16_t and print correctly this value by uint16_t type?
That mean i want the uint16_t result is 058f as well:
```
uint16_t result = 0x058f;
```
|
You can use strtol to convert string to integer value
```
*char* str = "0x058f";
result = strtol(str,NULL,16);
printf("result = %x\n",result);*
```
I hope this helps.
|
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.Closed7 years ago.Improve this question
I have Cygwin, but can't figure out how to install GCC, Nano, Emacs or anything of the sort. Any help is appreciated.
|
You should select the installation of gcc and g++ when installing cygwin.
Here is a screenshot:
Also a quick google search gave methisandthiswhich may also answer your question about nano and emacs
|
I am having a problem with years inmktime().
Every time I pass a year lower than 1970 into mystruct tmand then run themktime()function to convert my structure, it fails (returns -1).
Does anyone have any idea why and if I can make this work somehow?
|
That is never going to work, since it's by definition outsidethe epoch, which is the start for Unix time.The manual pagestates:
Thectime(),gmtime()andlocaltime()functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
If it fails to convert the input into Unix time, it's documented to return-1so that's why you're seeing that result.
|
I am trying to create a https server that uses the ssl context. Everything works out fine for this code for TLS clients
```
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
long options = SSL_OP_ALL |SSL_OP_NO_SSLv2 |SSL_OP_NO_SSLv3;
```
This effectively disables sslv2 and sslv3 and enables certain bug fixes.
I want to keep the disabling sslv3 part optional. But removing of SSL_OP_NO_SSLv3 still does not make sslv3 work.
```
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
long options = SSL_OP_ALL |SSL_OP_NO_SSLv2 ; // SSLV3 still does not work
```
I use curl as the client:
```
curl -vk --sslv3 "https://IP/hello_world"
* Server aborted the SSL handshake
* Closing connection 0
```
For non sslv3 everything works fine.
|
The problem was in the configure section of the library. It was compiled with no ssl2 or ssl3 as below
no-ssl2 no-ssl3
Hence sslv3 did not work with sslv23.
|
I wrote a C program as follows:
```
void foo(int *a) {
if (a[1000] == a[1000]) {
printf("Hello");
}
}
int main() {
int *a;
foo(a);
return 0;
}
```
I was expecting this program to crash because I did not allocate the memory at &a[1000], but the program actually did not crash and printed "Hello". I compiled the program with command
```
gcc -O0 foo.c
```
What might be the reason for this?
|
Accessing memory places that has not been allocated is undefined behaviour.
Now, this can lead to eitherseg fault, if the memory you are accessing is restricted for your program.
Or, as in your case, it wont have any defined effects. It will probably be reading garbage values left by the previous programs. This kind of behavior is called undefined.
It may be working in your case for a particular time, but it will definitely won't work all the time.
|
I have two uint32_t variables.
These have following values -
```
uint32_t a = 0x00002000;
uint32_t b = 0x00c00000;
```
I want these two variable to be merged so they give the result0000200c.
If I simply doa+b, it does not return the correct result. Could anyone please help?
Edit - I need to put Bit number 31-20 of b to bit number 11-0 of a.
|
Bits 31-20 ofbcan be isolated by doing(b & 0xFFF00000).
Bits 11-0 ofacan be isolated by doing(a & 0x00000FFF).
Then you need to shift thebvariable to the right by 20 bits before combining it witha. Putting it all together, you get
```
uint32_t answer = ((b & 0xFFF00000) >> 20) | (a & 0x00000FFF);
```
|
I am changing my code to meet the MISRA standard. I have come across the warning
Required Rule 10.1, Prohibited Implicit Conversion: Non-constant argument to function.
```
memcpy(&Final_buff[index], Main_cal, buffer_size);
// where buffer_size is uint8, uint8 *Final_buff, and const uint8 *buffer
```
Then I changed above for a small test:
```
memcpy(&Final_buff[index], Main_cal, 12u);
```
which is accepted by MISRA. The thing is I can't hardcode the value there. How can I get rid of this warning?
|
This should solve your MISRA problem:
```
memcpy(&Final_buff[index], Main_cal, (size_t) buffer_size);
```
Rule 10.1 doesn't allow an implicit conversion in several situations, including "the expression is not constant and is a function argument", which is the situation you were running into.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question
I have char array like
```
char* str = 0x058f;
```
What should i do to convert this value to int and uint16_t and print correctly this value by uint16_t type?
That mean i want the uint16_t result is 058f as well:
```
uint16_t result = 0x058f;
```
|
You can use strtol to convert string to integer value
```
*char* str = "0x058f";
result = strtol(str,NULL,16);
printf("result = %x\n",result);*
```
I hope this helps.
|
char *p[2][3];
How does*(*(p+1)+1)[7]equalp[1][8][0]?
I thought*(*(p+1)+1)[7]would be the same as*(*(*(p+1)+1)+7)and that is equal top[1][1][7], where am I wrong?
E: I don't understand why this is being downvoted...
|
Basic facts:
[]associatesleft to right[]has higherprecedencethan the dereference operator*a[i]is*(a+i)
So
```
*(*(p+1)+1)[7]
= *((*(p+1)+1)[7]) // rule 2
= *(*(*(p+1)+1+7)) // rule 3
= *(*(*(p+1)+8))
= *(*(*(p+1)+8)+0)
= p[1][8][0] // rules 1 and 3
```
|
I aim to pass some variable values to gcc. Here my example:
command:
```
gcc -Q -fvpt -fwrapv -fwhole-program --help=optimizers
```
output:
```
-fvpt [enabled]
-fwhole-program [enabled]
-fwrapv [enabled]
```
and When I run:
```
var="-fvpt -fwrapv -fwhole-program"; gcc -Q $(var) --help=optimizers
```
output:
```
-fvpt [disabled]
-fwhole-program [disabled]
-fwrapv [disabled]
```
Why it does not work ?
|
$(var)attempts to execute the commandvarand use its output in the command line. To expand a variable in bash, you would use$var
```
var="-fvpt -fwrapv -fwhole-program"; gcc -Q $var --help=optimizers
```
|
Let say I have:
```
#define CHUNK_SIZE 256
void copy(FILE *input, FILE *output) {
char buffer[CHUNK_SIZE];
while (fgets(buffer, CHUNK_SIZE, input) != NULL) {
fputs(buffer, output);
}
}
```
But in the while loop,fgetsgets the same parameters - so how does it know to read the next line from the file in each iteration ofwhile? Doesn't it suppose to get stuck in infinite loop because it always reads the same line?
|
EDIT: added extra explanation as @KlasLindbäck pointed out that my answer wasn't entirely correct
The File is a struct that contains a field "fd" which is an integer that identifies the OS file descriptor of this file, this file descriptor can be used to retrieve the current location in the file you're reading. If you want more information about the File structhereand file descriptorhere
TL;DR: The FILE struct somehow stores where it's reading.
|
I've been studying memory management related topics. I'm wondering, whether I've understood it correctly:
pointer(virtual) address is process specificdifferent processes can have pointers with same addresses, but these pointers get translated to different physical addresses
Am I correct about these statements? If yes, do they apply for architectures x86, x86-64 and ARMv7, ARMv8?
|
Well except for:
different processes can have pointers with same addresses, but these pointers get translated to different physical addresses
while this is the general case, of course different processescouldshare mapped pages (look into shared memory) and then the pointerscouldpoint to the same data, given the pages are mapped to the same locations in virtual address space.
But yes, that's the correct understanding.
|
By Default negative number signs are printed and by adding + flag one can print the plus sign if required.I am looking to print a number without its sign.I believe there is a flag for that but that doesn't seem to work.
```
printf("'%d'", 10); --> '10'
printf("'%d'",-10); --> '-10'
printf("'%+d'",10); --> '+10'
```
It would be great if some can suggest how to print x for the inputs x and -x,(x>0).PS: I don't like to operate on numbers, I am looking for a software feature.
|
I am looking to print a number without its sign.
Nobody would want that as leaving the sign from anegativenumber makes it adifferentnumber.
PS: I don't like to operate on numbers
Well, then do what you don't like ...abs()is the function you're looking for and expresses exactly what's going on.
|
I have structure
```
typedef struct
{
char employee_name[32];
char organisation[32];
}info;
```
How can I Initialized a single or more elements of info .
I am doing like this at the start of the code:
```
info info_data= {
{'d','a','v','i','d',' ','s','c','h','o','l','e','s','\0'},
{'x','y','z',' ','I','n','c','\0'}
```
};
This works fine but I want to avoid putting all the names with each character enclosed in ' ' and adding '\0' at the end.Is there a better way to implement this.Code has to run in anembedded processor and needs to be memory and speed optimized.
|
Try this:
```
info info_data= {
{"David Scholes"},
{"xyz Inc"}
};
```
You can initialise a character array with a string.
If you want to usestrcpythen proceed as follows:
```
strcpy(info_data.employee_name, "David Scholes");
strcpy(info_data.organisation, "xyz Inc");
```
|
I get foreach macro fromhere
```
#define foreach(item, array) \
for(int keep = 1, \
count = 0,\
size = sizeof (array) / sizeof *(array); \
keep && count != size; \
keep = !keep, count++) \
for(item = (array) + count; keep; keep = !keep)
```
I don't understand "(array) + count", it's equal "&array[count]", but why not use "array[count]" instead of "(array) + count"
|
but why not use "array[count]" instead of "(array) + count"
Fromthe linked post,
```
foreach(int *v, values) {
printf("value: %d\n", *v);
}
```
In the macro,itemis of typeint*andarray[count]is of typeint.
Hence you cannot use:
```
item = array[count];
```
But you can use
```
item = (array) + count;
```
since(array) + countevaluates to anint*.
|
I'm trying to figure out if I can use clang-format to automatically format the code for my project. We have a coding style which enforces newlines after the function return type (but only in the definition, not in the declaration). I'd like to encode this in clang-format.
IOW, I want this:
```
uint32_t
my_function(uint32_t input)
{
return 0;
}
```
Not this:
```
uint32_t my_function(uint32_t input)
{
return 0;
}
```
|
AlwaysBreakAfterDefinitionReturnType(DRTBS_All)If you add that to the .clang-format file that contains all your formatting decisions it should do exactly what you want.
|
whats wrong with my code? im trying to return a value from function ignition_status, its not returning. I cant see any problem in my code.
```
#include<stdio.h>
#include<stdint.h>
const char * ignition_status();
const char *ign_st;
int main()
{
printf("%s", ignition_status(1));
return 0;
}
const char * ignition_status(int st)
{
if(st==1)
{
const char *ign_st="ON";
}
else
{
const char *ign_st="OFF";
}
return ign_st;
}
```
Thanks...
|
The comments are pointing you to the right direction, here is a working sample:
```
#include <stdio.h>
const char * ignition_status(int st)
{
const char *ign_st;
if(st==1) {
ign_st="ON";
} else {
ign_st="OFF";
}
return ign_st;
}
int main()
{
printf("%s", ignition_status(1));
return 0;
}
```
|
I've been studying memory management related topics. I'm wondering, whether I've understood it correctly:
pointer(virtual) address is process specificdifferent processes can have pointers with same addresses, but these pointers get translated to different physical addresses
Am I correct about these statements? If yes, do they apply for architectures x86, x86-64 and ARMv7, ARMv8?
|
Well except for:
different processes can have pointers with same addresses, but these pointers get translated to different physical addresses
while this is the general case, of course different processescouldshare mapped pages (look into shared memory) and then the pointerscouldpoint to the same data, given the pages are mapped to the same locations in virtual address space.
But yes, that's the correct understanding.
|
By Default negative number signs are printed and by adding + flag one can print the plus sign if required.I am looking to print a number without its sign.I believe there is a flag for that but that doesn't seem to work.
```
printf("'%d'", 10); --> '10'
printf("'%d'",-10); --> '-10'
printf("'%+d'",10); --> '+10'
```
It would be great if some can suggest how to print x for the inputs x and -x,(x>0).PS: I don't like to operate on numbers, I am looking for a software feature.
|
I am looking to print a number without its sign.
Nobody would want that as leaving the sign from anegativenumber makes it adifferentnumber.
PS: I don't like to operate on numbers
Well, then do what you don't like ...abs()is the function you're looking for and expresses exactly what's going on.
|
I have structure
```
typedef struct
{
char employee_name[32];
char organisation[32];
}info;
```
How can I Initialized a single or more elements of info .
I am doing like this at the start of the code:
```
info info_data= {
{'d','a','v','i','d',' ','s','c','h','o','l','e','s','\0'},
{'x','y','z',' ','I','n','c','\0'}
```
};
This works fine but I want to avoid putting all the names with each character enclosed in ' ' and adding '\0' at the end.Is there a better way to implement this.Code has to run in anembedded processor and needs to be memory and speed optimized.
|
Try this:
```
info info_data= {
{"David Scholes"},
{"xyz Inc"}
};
```
You can initialise a character array with a string.
If you want to usestrcpythen proceed as follows:
```
strcpy(info_data.employee_name, "David Scholes");
strcpy(info_data.organisation, "xyz Inc");
```
|
I get foreach macro fromhere
```
#define foreach(item, array) \
for(int keep = 1, \
count = 0,\
size = sizeof (array) / sizeof *(array); \
keep && count != size; \
keep = !keep, count++) \
for(item = (array) + count; keep; keep = !keep)
```
I don't understand "(array) + count", it's equal "&array[count]", but why not use "array[count]" instead of "(array) + count"
|
but why not use "array[count]" instead of "(array) + count"
Fromthe linked post,
```
foreach(int *v, values) {
printf("value: %d\n", *v);
}
```
In the macro,itemis of typeint*andarray[count]is of typeint.
Hence you cannot use:
```
item = array[count];
```
But you can use
```
item = (array) + count;
```
since(array) + countevaluates to anint*.
|
I'm trying to figure out if I can use clang-format to automatically format the code for my project. We have a coding style which enforces newlines after the function return type (but only in the definition, not in the declaration). I'd like to encode this in clang-format.
IOW, I want this:
```
uint32_t
my_function(uint32_t input)
{
return 0;
}
```
Not this:
```
uint32_t my_function(uint32_t input)
{
return 0;
}
```
|
AlwaysBreakAfterDefinitionReturnType(DRTBS_All)If you add that to the .clang-format file that contains all your formatting decisions it should do exactly what you want.
|
whats wrong with my code? im trying to return a value from function ignition_status, its not returning. I cant see any problem in my code.
```
#include<stdio.h>
#include<stdint.h>
const char * ignition_status();
const char *ign_st;
int main()
{
printf("%s", ignition_status(1));
return 0;
}
const char * ignition_status(int st)
{
if(st==1)
{
const char *ign_st="ON";
}
else
{
const char *ign_st="OFF";
}
return ign_st;
}
```
Thanks...
|
The comments are pointing you to the right direction, here is a working sample:
```
#include <stdio.h>
const char * ignition_status(int st)
{
const char *ign_st;
if(st==1) {
ign_st="ON";
} else {
ign_st="OFF";
}
return ign_st;
}
int main()
{
printf("%s", ignition_status(1));
return 0;
}
```
|
I have structure
```
typedef struct
{
char employee_name[32];
char organisation[32];
}info;
```
How can I Initialized a single or more elements of info .
I am doing like this at the start of the code:
```
info info_data= {
{'d','a','v','i','d',' ','s','c','h','o','l','e','s','\0'},
{'x','y','z',' ','I','n','c','\0'}
```
};
This works fine but I want to avoid putting all the names with each character enclosed in ' ' and adding '\0' at the end.Is there a better way to implement this.Code has to run in anembedded processor and needs to be memory and speed optimized.
|
Try this:
```
info info_data= {
{"David Scholes"},
{"xyz Inc"}
};
```
You can initialise a character array with a string.
If you want to usestrcpythen proceed as follows:
```
strcpy(info_data.employee_name, "David Scholes");
strcpy(info_data.organisation, "xyz Inc");
```
|
I get foreach macro fromhere
```
#define foreach(item, array) \
for(int keep = 1, \
count = 0,\
size = sizeof (array) / sizeof *(array); \
keep && count != size; \
keep = !keep, count++) \
for(item = (array) + count; keep; keep = !keep)
```
I don't understand "(array) + count", it's equal "&array[count]", but why not use "array[count]" instead of "(array) + count"
|
but why not use "array[count]" instead of "(array) + count"
Fromthe linked post,
```
foreach(int *v, values) {
printf("value: %d\n", *v);
}
```
In the macro,itemis of typeint*andarray[count]is of typeint.
Hence you cannot use:
```
item = array[count];
```
But you can use
```
item = (array) + count;
```
since(array) + countevaluates to anint*.
|
I'm trying to figure out if I can use clang-format to automatically format the code for my project. We have a coding style which enforces newlines after the function return type (but only in the definition, not in the declaration). I'd like to encode this in clang-format.
IOW, I want this:
```
uint32_t
my_function(uint32_t input)
{
return 0;
}
```
Not this:
```
uint32_t my_function(uint32_t input)
{
return 0;
}
```
|
AlwaysBreakAfterDefinitionReturnType(DRTBS_All)If you add that to the .clang-format file that contains all your formatting decisions it should do exactly what you want.
|
whats wrong with my code? im trying to return a value from function ignition_status, its not returning. I cant see any problem in my code.
```
#include<stdio.h>
#include<stdint.h>
const char * ignition_status();
const char *ign_st;
int main()
{
printf("%s", ignition_status(1));
return 0;
}
const char * ignition_status(int st)
{
if(st==1)
{
const char *ign_st="ON";
}
else
{
const char *ign_st="OFF";
}
return ign_st;
}
```
Thanks...
|
The comments are pointing you to the right direction, here is a working sample:
```
#include <stdio.h>
const char * ignition_status(int st)
{
const char *ign_st;
if(st==1) {
ign_st="ON";
} else {
ign_st="OFF";
}
return ign_st;
}
int main()
{
printf("%s", ignition_status(1));
return 0;
}
```
|
If I have int function1(int n), and the input variable in this case is n, can I have another function int function2(int n)? Or would the fact that the two functions have the same input variables somehow interfere with each other.
|
Converting two comments to a CW answer — so the question can be given closure.
Jonathan Lefflernoted:
They're local to each function, unrelated to each other and not going to cause any problems. And many, many functions have common names and types for their arguments — it is a non-issue.
Anduser3386109agreed:
Yes, it's ok, every variable has a scope. The scope of a function parameter is that function. So the twoint nvariables are limited to their respective functions.
|
SupposeXandYare two positive integers andYis a power of two. Then what does this expression calculate?
(X+Y-1) & ~(Y-1)
I found this expression appearing in certain c/c++ implementation of Memory Pool (Xrepresents the object size in bytes andYrepresents the alignment in bytes, the expression returns the block size in bytes fit for use in the Memory Pool).
|
&~(Y-1)whereYis a power of 2, zeroes the lastnbits, whereY= 2n:Y-1producesn1-bits, inverting that via ~ gives you a mask withnzeroes at the end, anding via bit-level&zeroes the bits where the mask is zero.
Effectively that produces a number that is some multiple ofY's power of 2.
It can maximally have the effect of subtractingY-1from the number, so add that first, giving(X+Y-1) & ~(Y-1). This is a number that's not less thanX, and is a multiple ofY.
|
I'm confused.. After it prints the first c, which is 1, then c became 2 then it's supposed to print c, which is 2..
int c = 1;
```
while (c<=10)
printf("%d\n", c);
c = c + 1;
while (c<=10)
{
printf("%d\n", c);
c = c + 1;
}
```
|
When a While loop isn't followed by
```
{
}
```
The next statement is considered only to be part of the loop
So your code runs the while loop indefinitely printing value of c since the condition for the while loop to run is always true
enclose the print and increment statement in curly braces!
|
I'm trying to useSPAMfor Matlab. I downloaded the zip file with Matlab interface. Firstly, I run the following command:
```
mex -setup
```
and it showed:
After that,I run "compile.m" script, but I got the error below:
I tried to change the compiler with "mex","clang" and "gcc" but nothing solves the issue. Can you help me fix it?
|
Finally I find a solution. I'm using Mac OS X 10.10.5 (Yosemite) and some parameters in the script "compile.m" have to be compatible with each other.
```
compiler='mex'
blas='builtin'
use_multithread=false
add_flag=' -mmacosx-version-min=10.7'
```
And there will be issue with conversion in the file "mexSimpleGroupTree.cpp" and we need to change the line 33 to:
```
mwSize cdims[] = {static_cast<mwSize>(n)};
```
That's all for me to make it compile
|
I'm trying to useSPAMfor Matlab. I downloaded the zip file with Matlab interface. Firstly, I run the following command:
```
mex -setup
```
and it showed:
After that,I run "compile.m" script, but I got the error below:
I tried to change the compiler with "mex","clang" and "gcc" but nothing solves the issue. Can you help me fix it?
|
Finally I find a solution. I'm using Mac OS X 10.10.5 (Yosemite) and some parameters in the script "compile.m" have to be compatible with each other.
```
compiler='mex'
blas='builtin'
use_multithread=false
add_flag=' -mmacosx-version-min=10.7'
```
And there will be issue with conversion in the file "mexSimpleGroupTree.cpp" and we need to change the line 33 to:
```
mwSize cdims[] = {static_cast<mwSize>(n)};
```
That's all for me to make it compile
|
```
int x = 3 > 4;
int y = 4.98;
printf("%d %d\n", x && y, x || y);
```
output:
```
0 1
```
My work:
For x variable: Since 3 > 4 is false... in C that means it returns 0 since 0 means false in C and true means 1 => x = 0
For y variable: Since y is an integer and a decimal is given then y is instantly downcasted to 4 => y=4
Binary of 0 is 0000
Binary of 4 is 0100
So
```
x && y = 0000 && 0100 = 0000
x || y = 0000 || 0100 = 0100 != 0001 (??)
```
Why does x || y = 1?
|
I think you're confusing logical and bitwise operators.&&Just means 'and', and||just means or. Since y is not 0, it's considered true, and since x is 0, it's false, sox && yis zero because x is false andx || yis 1 because y is true.
Maybe what you're thinking of is bitwise operators. Bitwise and is just&, and bitwise or is just|
https://en.wikipedia.org/wiki/Bitwise_operations_in_C
|
The function
```
int crypto_sign(unsigned char *sm, unsigned long long *smlen,
const unsigned char *m, unsigned long long mlen,
const unsigned char *sk);
```
prepends a signature to messagem. However, I am unable to find in the documentation wether libsodium signs the message directly, or creates a hash first. If it uses a hash, what kind of hashing method uses?
|
It uses the EdDSA algorithm, which is similar to Schnorr signatures.
The message is indeed hashed (actually twice) using the SHA512 function in order to compute the signature.
|
I encountered this macros definition in aCproject.
I face problems expanding the macro.
Here it is:
```
#define PT_THREAD(name_args) char name_args
#define PROCESS_THREAD(name, ev, data) \
static PT_THREAD(process_thread_##name(struct pt *process_pt, \
process_event_t ev, \
process_data_t data))
```
Some help? Thank you.
|
You can rungcc -Eto get the resulting code after the preprocessor.
Running this onPROCESS_THREAD(foo,bar,baz)results in:
```
static char process_thread_foo(struct pt *process_pt, process_event_t bar, process_data_t baz)
```
|
The problem is clock() function is not allowed, but I have no idea how to deal with time() function in thread.
|
Since you marked the post C++11, take a look at thechronolibrary:
```
#include <chrono>
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
... // <-- Code that you want to time
end = std::chrono::system_clock::now();
std::cout << "Time : " << std::chrono::duration<double>(end - start).count();
```
|
I encountered erratic behavior when initializing array in function.
I have an uninitialized pointer below:
```
int *arr;
```
And I am passing it to a function for initialization.
```
init_arr(&arr);
void init_arr(int **arr)
{
*arr = (int *) calloc(10, sizeof **arr);
}
```
The pointer is initilized, and when I try get items *arr[2] and larger I get the error:
```
Cannot access memory to address 0x0
```
The source code was compiled using gcc version 4.8.4
|
Instead of expression
```
*arr[2]
```
you have to use
```
arr[2]
```
You allocated an array of 10 integers. So to acces an element of the array it is enough to write for examplearr[2].
If you mean an access of an element of the allocated array inside the functioninitthen you have to write
```
( *arr )[2]
```
|
I encountered erratic behavior when initializing array in function.
I have an uninitialized pointer below:
```
int *arr;
```
And I am passing it to a function for initialization.
```
init_arr(&arr);
void init_arr(int **arr)
{
*arr = (int *) calloc(10, sizeof **arr);
}
```
The pointer is initilized, and when I try get items *arr[2] and larger I get the error:
```
Cannot access memory to address 0x0
```
The source code was compiled using gcc version 4.8.4
|
Instead of expression
```
*arr[2]
```
you have to use
```
arr[2]
```
You allocated an array of 10 integers. So to acces an element of the array it is enough to write for examplearr[2].
If you mean an access of an element of the allocated array inside the functioninitthen you have to write
```
( *arr )[2]
```
|
Which is the correct scanset format specifier syntax forscanf(),%[-A-B234abc]or%[A-B234abc-]? I couldn't find the answer on StackOverflow, and the following two links give contradictory answers:
cplusplusreference:A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
beez:To match a hyphen, make it the last character in the set: %[A-C-].
|
As per the n1570 (Draft of the C11 standard) and n1256 (Draft of the C99 standard),
7.21.6.2 The fscanf function[...]The conversion specifiers and their meanings are:[...][ [...]If a - character is in the scanlist and is not the first, nor the second where the first character is a ^, nor the last character, the behavior is implementation-defined.
|
```
#include <stdio.h>
void foo();
int main()
{
int b = 0;
int a[6] = {1,2,3,4,5,6};
foo();
return 0;
}
void foo()
{
//write some code to print a and b
}
```
My Question is:
How to get the local variable from outside without pass any parameter ?
|
That's not possible. You need to pass a pointer to it to access it from a function or make it global.
|
I want to know that how to print0as000and1as001in c and so on.
I tried usingprintf("%3d", var);but it doesn't seem to work
can anyone please suggest any method
|
You can do this with
```
printf("%03d", var);
```
to provide a minimum field width of 3 padded with leading zeros. Don't forget the enclosing "quotes". If you had put them in your posted code:
```
printf("%3d", var);
```
it would have been padded with spaces.
|
This question already has answers here:Why are floating point numbers inaccurate?(5 answers)Closed7 years ago.
```
#include <stdio.h>
void main() {
float num = 546.327;
printf("the number is %f\n",num);
enter code here
}
```
The out put is 546.327026.
When I tried different numbers it always ended up printing 6 numbers after the dot, when the last 3 are random.
|
Floating point numbers are stored in sums of fractions of 1/2^N
First fractional bit is 0.5,Second is 0.25,Third 0.125,etc
So their representation is not exact... If 546.327 cannot be represented summing fractions of 1/2^N it will be approximated to something close...
That's why you get the "random digits", they are not random at all, it's just a rounding inaccuracy.
If you try printing another number that can be accurate represented with sums of 1/2^N you will get the exact number. i.e. 546.5, 546.75,etc
|
```
printf("%d",pow(5,3))
```
it's printing 0, and works fine when number is different from 5 why?
Can anyone explain this ?
|
The return type of the power function is double. using the double conversion specifier to prints the output of power function.
the conversion specifier for double is not "%d". It should be "%f".
|
First off, I am not very experienced with C.
I am having to deal with arrays for a problem I need to solve, I have managed to simplify the issue to this:
```
#include <stdio.h>
#include <string.h>
char array[5] = {"hello"}
int main() {
printf(%s\n", array[0]);
return (0);
}
```
In this case I am just trying to print the 'h', yet I get a Segmentation Fault.
|
You have a number of errors to be fixed,
```
printf(%s\n", array[0]);
```
Here, you are trying to print achar, try
```
printf("%c\n", array[0]);
```
You are missing a;
```
char array[5] = {"hello"}
^
```
While declaring a string literal, you don't need the{}
```
char array[] = "hello";
```
|
so i have this C code
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
int b;
int c;
scanf("%d", &b);
scanf("%d", &a);
c = a + b;
printf(c);
return 0;
}
```
but, after i insert number for a and b, the program stop working. please help me
C noob here
|
In your code you have the following line is wrong:
```
printf(c);
```
as theprintf()syntax would be like what i've written below
```
printf("%d",c);
```
so your now code would be:
```
#include <stdio.h>
int main()
{
int a;
int b;
int c;
scanf("%d", &b);
scanf("%d", &a);
c= a + b;
printf("%d",c); //this is the correct printf() syntax
return 0;
}
```
|
This question already has answers here:Dividing 1/n always returns 0.0 [duplicate](3 answers)Closed5 years ago.
I have written a simple program, that reads one integernumberand prints:1 / number.
I do not understand why the output is always:0.000.
```
void main()
{
int n = 0;
scanf("%d",&n);
float f = 1 / n;
printf("%f",f);
}
```
|
Your (1/n) returns an integer value!
You need to have at least onefloatvalue in division!
Change (1 / n) to (1.0 / n).
|
I am revising C again and was making some test programs. At one program I was checking a condition which was translating ino this condition.
```
#include <stdio.h>
int main()
{
if(0 <= 3000.000000 <= 2000.00){ //this is the condition
printf("3000 is less than 2000, whoa.. \n");
}
return 0;
}
```
The output is always this print string. I can't understand why.
P.S
I am testing the middle value, i.e 3000.000000 here, but it can be some variable.
|
The condition is parsed like this:
```
if((0 <= 3000.000000) <= 2000.00){
```
The first part,(0 <= 3000.000000), is true, and evaluates to1in the comparison with2000.00. And1 <= 2000.00is true.
If you're trying to test whether a valuealies between two valuesbandcor is equal to either, then you need an expression along the lines of
```
(a >= b) && (a <= c)
```
|
I got the following error
```
make: *** No rule to make target `stretchy_buffer.o', needed by `tsh'. Stop
```
Trying to make this makefile
```
SRCS = stretchy_buffer.c def.c tsh_builtin_commands.c tsh_jobs.c tsh_main.c tsh_routines.c tsh_signals.c
OBJS = $(SRCS:.c=.o)
tsh: $(OBJS)
gcc -Wall -g -o tsh $(OBJS)
```
|
You need to add following rule in your makefile:
```
CFLAGS = -Wall -g
%.o:%.c
gcc $(CFLAGS) $< -o $@
```
In your existing makefile, there is no rule specified for obtaining *.o from *.c files and, hence, the error is reported.
|
I was debugging a C code and came across below expression. I want to know,
how below expression will be evaluated in c?
x += y*2 != z;
|
To figure out expressions like that start with theprecedence table:
Multiplication has precedence of 3, so it will be evaluated first!=has precedence of 7, so it will be evaluated next+=has precedence of 14, so it will be evaluated last.
Therefore,xwill be incremented by1ify*2is not equal toz.
|
My exercise is to use a structure to initialise values and then print them (sounds easy enough) but instead of using the structure to print them, we have to use the pointer *p. I know this probably has a really simple answer, but help would be appreciated!
```
#include <stdio.h>
#include <string.h>
struct info
{
int total;
char *str;
};
int main()
{
struct info s, *p = &s;
s.total = 50;
s.str = "hello";
printf("Info total: %i\n", s.total);
printf("Info *str: %s\n", s.str);
return 0;
}
```
|
```
s.total <=> p->total or (*p).total
```
Thanks to you all for the answers!
|
I am trying to run to following function as part of a bigger project:
```
#include <memory.h>
void bzero(char *s, int n)
{
memset (s, 0, n);
}
```
I am getting the following error:
"Conflicting types for 'bzero'"
I don't understand the problem, since the entire projects works fine on Linux. So I am actually trying to transfer it onto Mac and to create and executable file using Xcode, but it won't even built.
|
In your system there is already abzerofunction (a legacy POSIX function that is now removed) with a different prototype. Name your function differently likemy_bzero.
|
I have to write function in c to merge bytes from two unsigned int parameters,
taking the most significant byte of the second param and the rest of the first param.
For example if givenx = 0x89ABCDEFandy = 0x76543210so the function should return0x76ABCDEF
now I know thatchar *c = (char*) &ywill give me the MSB of y but then I don't know how to chain it to the rest of x without his MSB.
To be honest I completely forgot to do such simple thing in C as in last year all of my courses used Java, and I can't find it online, so any help would be appreciated.
|
This looks like a job for bit masking:
```
unsigned merge(unsigned x, unsigned y)
{
return (y & 0xFF000000) | (x & 0xFFFFFF);
}
```
Assuming 32-bit values, this used a bitwise AND to strip all but the top byte fromyand only the top byte fromx, then uses a bitwise OR to merge them togther.
|
I declared and initialized a 2x2 array as follows:
```
int arr[2][2] = {1, 2, 3, 4};
```
Then, a pointer to integer:
```
int *p1;
```
Initialize the pointer as:
```
p1 = arr[0]; //p1 points to {1, 2}
```
Now I can print elements usingp1as*p1
Now, when I declare:
```
int (*ptr)[2][2];
ptr = &arr;
```
To print the elements, now I have to use:
```
printf("%d\n", *(**(ptr)+1));
```
What is the difference between these two declarations?
|
int (*ptr)[2][2];is a pointer to a 2x2 matrix, not a pointer to anint. Since each dimension of a matrix behaves somewhat like a pointer, that is why you need extra dereferencing in theprintf.
|
my C program needs achar**input which I store in python as a numpy object array of strings.
```
a = np.empty(2, dtype=object)
a[0] = 'hi you'
a[1] = 'goodbye'
```
What is the correct way to pass this to my C program considering thatnumpy.ionly defines typemaps forchar*arrays?
|
That'simpossibruAFAIK, andas far as the docs go:
Some data types are not yet supported, like boolean arrays and string arrays.
You'll either have to write an intermediary function that takes the strings as separate arguments, put them in an array and pass that to your C function, or work out another way of doing things
|
This question already has answers here:What does this ">>=" operator mean in C?(5 answers)Closed7 years ago.
I know>>is Binary Right Shift Operator but what does>>=mean, like if I want Log2 onxI needwhile(x >>= 1) result++;.
|
It's the bitwise shift right assignment operator;x >>= 1is equivalent tox = x >> 1.
(It has the same precedence as assignment=).
|
I'm having trouble with splitting strings and the proper use of the function strtok:
Here's my problem:
I'm reading from stdin, and i want to split the input the following way:
```
<command> <key> <data>
```
"PUT 122gyhbhb having trouble with splitting strings and the proper use of the function streak:"
the first word(PUT) is the command, the second is the key and the other words until the end of input are the data.
Here's what i've done so far:
```
char *buffer = (char *) malloc(sizeof(char) * 2048);
fgets(buffer,2048, stdin);
char *options = strtok(buffer, " ");
char *key = strtok(NULL," ");
char *data = strtok(NULL, " ");
```
However this gets me the command, the key, but only the first word of the data. How can i change this, so it does what i want ? Thanks!
|
You need to change the delimiter for the last call tostrtok:
```
char *data = strtok(NULL, "\n");
```
|
This code is practice code for pointers. But I am not understanding the(int**)&p;means in this code.
```
void fun(void *p);
int i;
int main()
{
void *vptr;
vptr = &i;
fun(vptr);
return 0;
}
void fun(void *p)
{
int **q;
q = (int**)&p;
printf("%d\n", **q);
}
```
Please elaborate how it is evaluated.
|
It's a type cast, that interprets the value of&p, which has typevoid **, as instead having typeint **which is the type of the variable the value is stored in.
The cast is necessary, sincevoid **is not the same asvoid *and does not automatically convert to/from other (data) pointer types. This can be confusing.
|
This question already has answers here:C : #define usage [duplicate](3 answers)How does the preprocessor work in C?(9 answers)The need for parentheses in macros in C [duplicate](8 answers)Closed7 years ago.
When i compile the following program I get the output as 47. I expected the output to be 144
```
#include<stdio.h>
#define FIRST_PART 7
#define LAST_PART 5
#define ALL_PARTS FIRST_PART + LAST_PART
int main() {
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
return(0);
}
```
|
The preprocessor works before the compiler. It is a simple 'stupid' text-replace mechanism. Therefore:
ALL_PARTSgets converted to7 + 5ALL_PARTS * ALL_PARTSgets converted to7 + 5 * 7 + 5.
Because of this mechanism, it is recommended to surround the parameters of macros with parentheses and also surround the whole macro with parentheses, such as:
#define ALL_PARTS (FIRST_PART + LAST_PART)
|
I'm running the "hello-world" code from theGTK tutorial:
```
#include <gtk/gtk.h>
int main(int argc, char* argv[])
{
GTKWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_show(window);
gtk_main();
return 0;
}
```
and I'm receiving this error, when I compile it using:
```
$ gcc base.c -o base `pkg-config --cflags --libs gtk+-2.0`
base.c: In function ‘main’:
base.c:5:2: error: unknown type name ‘GTKWidget’
GTKWidget *window;
```
It seems that the issue isn't thatgtk.hisn't included, but rather that GTKWidget isn't a thing?
|
C is case-sensitive. The name of the type isGtkWidget:
```
GtkWidget *window;
```
In general GTK+ types have aGtkprefix, while the macros haveGTK, this is a common naming scheme in C.
|
I need to get time zone offset from a time zone name string expressed exactly like this "Pacific/Auckland". I know that boost::date_time would do the job, but I need to do it without that. Manipulations with TZ variable are also not allowed. Anyone have idea how to accomplish this task in such a way?
|
I know this is an old question, but I just had to write the code list the known timezones, so I'm sharing it here.
```
#include <date/tz.h>
const date::tzdb & tzdb = date::get_tzdb();
for (const date::time_zone & tz: tzdb.zones) {
cout << "TZ: " << tz.name() << endl;
}
```
This usesHoward Hinnants Date Library, and you'll need to compile in the tz.cpp file and have a path to the includes.
With C++20, the library is part of the standard, but I'm still on C++17.
|
This question already has answers here:What does this ">>=" operator mean in C?(5 answers)Closed7 years ago.
I know>>is Binary Right Shift Operator but what does>>=mean, like if I want Log2 onxI needwhile(x >>= 1) result++;.
|
It's the bitwise shift right assignment operator;x >>= 1is equivalent tox = x >> 1.
(It has the same precedence as assignment=).
|
I'm having trouble with splitting strings and the proper use of the function strtok:
Here's my problem:
I'm reading from stdin, and i want to split the input the following way:
```
<command> <key> <data>
```
"PUT 122gyhbhb having trouble with splitting strings and the proper use of the function streak:"
the first word(PUT) is the command, the second is the key and the other words until the end of input are the data.
Here's what i've done so far:
```
char *buffer = (char *) malloc(sizeof(char) * 2048);
fgets(buffer,2048, stdin);
char *options = strtok(buffer, " ");
char *key = strtok(NULL," ");
char *data = strtok(NULL, " ");
```
However this gets me the command, the key, but only the first word of the data. How can i change this, so it does what i want ? Thanks!
|
You need to change the delimiter for the last call tostrtok:
```
char *data = strtok(NULL, "\n");
```
|
This code is practice code for pointers. But I am not understanding the(int**)&p;means in this code.
```
void fun(void *p);
int i;
int main()
{
void *vptr;
vptr = &i;
fun(vptr);
return 0;
}
void fun(void *p)
{
int **q;
q = (int**)&p;
printf("%d\n", **q);
}
```
Please elaborate how it is evaluated.
|
It's a type cast, that interprets the value of&p, which has typevoid **, as instead having typeint **which is the type of the variable the value is stored in.
The cast is necessary, sincevoid **is not the same asvoid *and does not automatically convert to/from other (data) pointer types. This can be confusing.
|
This question already has answers here:C : #define usage [duplicate](3 answers)How does the preprocessor work in C?(9 answers)The need for parentheses in macros in C [duplicate](8 answers)Closed7 years ago.
When i compile the following program I get the output as 47. I expected the output to be 144
```
#include<stdio.h>
#define FIRST_PART 7
#define LAST_PART 5
#define ALL_PARTS FIRST_PART + LAST_PART
int main() {
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
return(0);
}
```
|
The preprocessor works before the compiler. It is a simple 'stupid' text-replace mechanism. Therefore:
ALL_PARTSgets converted to7 + 5ALL_PARTS * ALL_PARTSgets converted to7 + 5 * 7 + 5.
Because of this mechanism, it is recommended to surround the parameters of macros with parentheses and also surround the whole macro with parentheses, such as:
#define ALL_PARTS (FIRST_PART + LAST_PART)
|
I'm running the "hello-world" code from theGTK tutorial:
```
#include <gtk/gtk.h>
int main(int argc, char* argv[])
{
GTKWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_show(window);
gtk_main();
return 0;
}
```
and I'm receiving this error, when I compile it using:
```
$ gcc base.c -o base `pkg-config --cflags --libs gtk+-2.0`
base.c: In function ‘main’:
base.c:5:2: error: unknown type name ‘GTKWidget’
GTKWidget *window;
```
It seems that the issue isn't thatgtk.hisn't included, but rather that GTKWidget isn't a thing?
|
C is case-sensitive. The name of the type isGtkWidget:
```
GtkWidget *window;
```
In general GTK+ types have aGtkprefix, while the macros haveGTK, this is a common naming scheme in C.
|
I need to get time zone offset from a time zone name string expressed exactly like this "Pacific/Auckland". I know that boost::date_time would do the job, but I need to do it without that. Manipulations with TZ variable are also not allowed. Anyone have idea how to accomplish this task in such a way?
|
I know this is an old question, but I just had to write the code list the known timezones, so I'm sharing it here.
```
#include <date/tz.h>
const date::tzdb & tzdb = date::get_tzdb();
for (const date::time_zone & tz: tzdb.zones) {
cout << "TZ: " << tz.name() << endl;
}
```
This usesHoward Hinnants Date Library, and you'll need to compile in the tz.cpp file and have a path to the includes.
With C++20, the library is part of the standard, but I'm still on C++17.
|
I'm running the "hello-world" code from theGTK tutorial:
```
#include <gtk/gtk.h>
int main(int argc, char* argv[])
{
GTKWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_show(window);
gtk_main();
return 0;
}
```
and I'm receiving this error, when I compile it using:
```
$ gcc base.c -o base `pkg-config --cflags --libs gtk+-2.0`
base.c: In function ‘main’:
base.c:5:2: error: unknown type name ‘GTKWidget’
GTKWidget *window;
```
It seems that the issue isn't thatgtk.hisn't included, but rather that GTKWidget isn't a thing?
|
C is case-sensitive. The name of the type isGtkWidget:
```
GtkWidget *window;
```
In general GTK+ types have aGtkprefix, while the macros haveGTK, this is a common naming scheme in C.
|
I need to get time zone offset from a time zone name string expressed exactly like this "Pacific/Auckland". I know that boost::date_time would do the job, but I need to do it without that. Manipulations with TZ variable are also not allowed. Anyone have idea how to accomplish this task in such a way?
|
I know this is an old question, but I just had to write the code list the known timezones, so I'm sharing it here.
```
#include <date/tz.h>
const date::tzdb & tzdb = date::get_tzdb();
for (const date::time_zone & tz: tzdb.zones) {
cout << "TZ: " << tz.name() << endl;
}
```
This usesHoward Hinnants Date Library, and you'll need to compile in the tz.cpp file and have a path to the includes.
With C++20, the library is part of the standard, but I'm still on C++17.
|
I'm trying to (as the title says) read from a file into main, using argc and argv, taking the filename from the command line and passing it through main into a void function which opens, reads and writes it. However im gettingCannot open file...Segmentation fault.
```
void file_pass (char * argv[])
{
FILE *file_name;
if ((file_name = fopen(argv[1], "r")) == NULL)
{
printf("Cannot open file ...\n");
}
fclose(file_name);
}
```
Which leads me to think it isn't opening the file correctly but I'm not sure why.
|
In your functionvoid file_pass (char * argv[])-
```
if ((file_name = fopen(argv[1], "r")) == NULL)
```
Instead of this , you should try this -
```
if ((file_name = fopen(argv[0], "r")) == NULL) // file's name is in argv[0] in funciton
```
Because array indexing start with0and in functionargv[1]may contain nothing .
|
I have this code in C-
```
#include <stdio.h>
#include <math.h>
int main()
{
printf("%d",(12345/pow(10,3)));
}
```
It outputs any arbitrary value,why is it not outputting 12?
Isn't the above code equivalent to-
```
#include <stdio.h>
#include <math.h>
int main()
{
int i=12345/pow(10,3);
printf("%d",i);
}
```
It outputs 12,
Why the two codes outputting different values?Can someone please explain.
|
powreturns adouble, therefore causing undefined behavior because you pass it to a format string expecting anint, sincetypeof(int / double) == double.
Try
```
printf("%lf\n", 12345 / pow(10, 3));
```
or use an explicit cast, like
```
printf("%d\n", 12345 / (int) pow(10, 3));
```
|
please help me out , I'm trying to implementstrchrand I still getNullwhen I run this code... what is it wrong with it?
```
char *ft_strchr(const char *str, int c)
{
int i;
char *temp;
i = 0;
while (str[i])
{
if (str[i] == c)
{
*temp = str[i];
return (temp);
}
else
return (NULL);
i++;
}
return (str);
}
```
|
```
char* ft_strchr(const char *str, int c){
size_t i;
char *temp;
i = 0;
while (str[i])
{
if (str[i] == c)
{
temp = &str[i];
return temp;
}
i++;
}
if(str[i]==c)
{
return &str[i];
}
return NULL;
// You need to return NULL after scanning whole line..
// Or it will send NULL checking after 1st character
}
```
|
When compiling with -fsanitize do i have to compile every target with it?
I have some targets which are not supported by it (assembly and C targets).
The main executable is a supported C++ file.
Will fsanitize work? or do i need to remove the unsupported files? or will it just work the parts which were compiled with the flag?
|
The documentation tells us that-fsanitizeenables AddressSanitizer, providing a link to its homepage. With that, we can get our answer straight fromthe FAQ:
Q: I've built my main executable with ASan. Do I also need to build shared libraries?A: ASan will work even if you rebuild just part of your program. But you'll have to rebuild all components to detect all errors.
Although you're not building shared libraries, this answer demonstrates that not every object linked to your executable need have AddressSanitizer enabled.
|
So, I have a simple C program which is supposed to output a decreasing number of spaces, and an increasing number of hashmarks in my new line. Here is the code I used to try to accomplished this:
```
for(x = 0; x < n; x++) {
for(y = n - 1; y > 0; y--) {
printf(" ");
}
for(int z = 2; z < n + 2; z++) {
printf("#");
}
printf("\n");
}
```
I expect, based on the code counting down like this, that I should see an output like:
```
##
###
```
However, when I run my code, I get a consistent output of:
```
###
###
```
Any thoughts on where I went wrong in my for loops that might have caused this issue?
|
Here:
```
n = 3;
for(x = 0; x < n; x++) {
for(y = 0; y < n; y++) {
printf("%c", (y < (n - x - 1)) ? ' ' : '#');
}
printf("\n");
}
```
Result:
```
#
##
###
```
|
Can someone help me print out the following characters:
```
* ********
** *******
*** ******
**** *****
***** ****
****** ***
******* **
******** *
```
That's my code:
```
#include <stdio.h>
int main(void) {
int row;
int column;
// fig a :
for (row=1;row<=7;row++) {
for (column=1;column<=row;column++)
printf("*");
printf("\n");
}
printf("\n");
}
```
|
Right now, you're only printing the bottom half of the set of characters. You need to keep going until you hit the end of the row.
All rows are printing the same number of characters. The only difference is where the space character is. So on each row, always printcolumncharacters. If it's time to print a space, print it, otherwise print a*.
|
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.Closed7 years ago.Improve this question
Im looking for way to display double value as string in c. But using snprintf im getting questionmarks instead of value. My code:
```
char temp[50];
double c = 19.15928891;
snprintf(temp, 8,"%lf", c);
putstring(-2, temp); //send characters to rs232 (here getting only '?')
```
Can someone show me another way to display double as string?
Edited, hope now question is ok :)
|
Try%finstead of%lf. Depending on how old your library is,%lfis either the same as%for an error (so just use%fin the first place).
Also note that19.159289(the result of thatprintf) requires 10 bytes to store, not 8.
|
If i try to input the 50th number in the series it displays until the 46th and then generates random numbers however when i counted the characters in both i found they were both equal to 10, so why does it stop at precisely 46?
My Code:
```
void calculating_f(int val){
int aray[100] = {0,1};
int i;
printf("%i %i ", aray[0], aray[1]);
for (i=2; i < val; i++){
aray[i] = aray[i - 2] + aray[i - 1];
printf("%i ", aray[i]);
}
}
```
|
Integer overflow (assumingints are 32-bits on your system). The 46th Fibonacci number is largest that will fit into a signed 32-bit value.
BTW -- You don't really need an array for this.
|
What is the difference between the two following line expressions:
```
#define value (unsigned char) 0x1f
#define value 0x1fu
```
I usually find both expressions in examples in single .c file. Is there any difference between, concerning compiler behavior ?
|
Assuming we fix the broken macros to use an identifier, the difference between
```
#define FOO (unsigned char)0x1f
```
and
```
#define FOO 0x1fu
```
is theirtype. The type of the first definition isunsigned char, that of the second isunsigned int. You can see this when you compute the result of thesizeofoperator on each:
```
printf ("%zu\n", sizeof(FOO));
```
which will likely output different values.
|
Is there a proper way to declare a pointer that jumps 9 bytes when I increment it?
An example:
```
sometype* ptr = 0x0;
ptr+1; //ptr points now to 0x9
ptr+2; //ptr points now to 0x12
```
|
struct-based solutions won't generally work unless the code specifically controls padding.
However, if we do this (using twotypedefs for clarity)
```
typedef char base_type[9];
typedef base_type *some_type;
```
or (avoiding the need for the firsttypedef, but making things a little more cryptic)
```
typedef char (*some_type)[9];
```
then, given an appropriately initialised variable of typesome_type, incrementing will increase by9characters.
|
I just started using Visual Studio (Enterprise), more specifically C and C++ Programming. I was wondering, since I'm using mainly simple C programming and nothing OOP, is it possible to have multiple .cpp files in the same solution and/or project, and compile/run them separately.
I have a lot of C programs to write and I'm hoping I won't have to create a whole solution for each simple main function. I know this might be a dumb question but I'm still new to the structure of Visual Studio, any help would greatly appreciated.
Thanks.
|
You have to create a single solution with multiple project. Each project has its own main.This is a weakness of visual studio, you can not create a project with several main.
|
I'm currently trying to add 2 characters in c i.e.
```
char a = 127;
char b = 127;
char c = a + b;
printf("%d\n", c);
```
which prints out 4294967278, I'm actually having problems anytime I add 2 numbers together where the resultant ASCII value would be greater than 127, what is happening here? aren't characters 8 bits or 256 possible numbers? so adding values that would be less than 256 should work no?
|
Probably because yourchars aresignedand can hold values from -128 to 127. By using
```
char c = a + b;
```
you have an overflow and overflow ofsigned charresults in Undefined Behavior. You can use anunsigned charto get rid of the problem:
```
unsigned char c = a + b;
```
|
Let's say I have some functionfunction, are the following prototypes completely equivalent in all senses?
```
sometype function(sometype2 arr[],...);
sometype function(sometype2 * arr,...,);
```
I think they are, but my c professor never really explained that.
|
Yes, the prototypes given are equivalent.
When you pass an array to a function, what's actually happening is that a pointer to the first element of the array is being passed to the function. This is referred to as the array decaying to a pointer when passed as a parameter.
In both cases, the value ofsizeof arrwill return the size of a pointer type, typically 4 or 8 on most systems, instead of the size in bytes of the array.
|
I am trying to read in adoublevalue continuously from the user usingscanf.
Code:
```
printf("Enter A value: \n");
double input;
int result = scanf("%f", &input);
printf("INPUT: %f\n", input);
```
The output is
```
INPUT: 0.000
```
|
You lied to the compiler: when scanning,%fsays you supply a pointer tofloat. But you provided a pointer todouble.
To fix, either use%lfordeclareinputasfloat.
Note that there is an asymmetry withprintfformats, which uses%ffor bothfloatanddoublearguments. This works becauseprintfarguments are promoted todouble(and are not pointers).
|
Well, let us say i am supposed to obtain D = (A - B) mod M, where A and B are very large, large as in, long long wont help. A and B were obtained iteratively and independently and i would obtain A mod M at each iteration and B mod M at each iteration. Now, let us say B is always smaller than A, but (B mod M) can be larger than (A mod M), then when D is evaluated, a negative number will be obtained, which isnt right, because, well, B is smaller than A. How do I go about this? Thanx in advance.
|
If((A mod M) - (B mod M)) mod Mgives you a negative result (as it may, since older C leaves the result of modulus implementation-defined when either argument is negative, and C99 defines it so that the result is negative if the dividend is negative), simply addMto get the result you want. After all, x and x+M are equivalent, mod M.
|
This question already has answers here:What's the use of suffix `f` on float value(7 answers)Why floating point value such as 3.14 are considered as double by default in MSVC?(5 answers)Closed7 years ago.
I am new in C programming language and I have a question related to a variable:
```
float a=12.34f;
```
What does "f" stand for? I tried to see what happens if I remove the letter, but I couldn't find anything. The output is the same.
|
So that it will be interpret as float not double by the compiler.
See here:Suffix of "f" on float value?
|
I am trying to print a user entered string word by word, or tokenize. I have:
```
char input [1000];
char* token;
scanf("%s", input);
token = strtok (input," ,.");
while (token != NULL){
printf("%s\n",token);
token = strtok(NULL, " ,.");
}
```
When I enter something into the console, say "test test one two three.", only the first word is printed out.
|
You are only scanning in the first word withscanf.scanfexpects a formatted string input, ie in your case:
```
scanf("%s %s %s %s", string1, string2 ...
```
This isnt useful to you. You should look into usingfgets.
Please be aware thatgetshas no way of limiting input size.It can be very dangerous for your memory if not used only by you. Usefgets.
Here is a live example.
|
Say I have a struct:
```
struct guitar{
long guitarID;
short brand:3;
short strings: 6;
short price;
}x[5][5]; //Thanks chux
```
If the address of x is 0xaaa and memory is aligned at multiples of 4 then what would the address be at x[1]?
The other thing I want to know is what the range of numbers between brand and strings are now that they are affected by a bitfield?
|
Assuming long 8 bytes, short 2 bytes and memory is 4 bytes aligned size of struct is 8 byte + 3 bit + 6 bit + 2 byte = 8 + 4 = 12 bytes.
x[1] is nothing but &x[1][0].
If x is 0xaaa , x[1] is 0xaaa + (5 * 12) = 0xaaa + 60.
So x[1] is 60 bytes away from x.
|
I'm brand new to C and am trying to create a global array that will hold pointers to structs:
```
person* persons[n];
```
However, I need to make the above a global variable. To do that, I need to declare it outside of all functions. But how can I do that without knowing what n will be? Really lost here, any help would be appreciated!
The below is what I'm ultimately trying to accomplish:
```
person* persons[];
function () {
initialize global array here
}
```
|
You use a pointer of a pointers and callmallocin an init function.
```
person **persons;
int n = 42;
void init(void)
{
persons = malloc(n * sizeof *persons);
if (!persons) {
/* handle malloc failure here */
}
}
```
|
I have a very interesting problem come up while programming in MPLAB IDE v8.92.
This is just a snipit of the code but this is where the problem is occuring:
```
struct data
{
INT32 value;
};
struct data array[8] = {{0},{0},{0},{0},{0},{0},{0},{0}};
INT32 IOC[8];
INT32 IOD[8];
for ( byte i = 0; i<8; i++)
{
#ifdef DAC
IOC[i] = 0;
IOD[i] = 24;
if(array[i].value == 0) array[i].value == 1;
#endif
}
```
The code builds with no errors and when I step through this part of the code using a ICD 3 debug, IOC and IOD are assigned correctly but the if statement is skipped! i.e. the debugger does not even stop on it. Any ideas what might have happened?
|
Always compile with-Wall -Werror. Your statement would have been flagged at compile time:warning: statement with no effect [-Wunused-value]
|
I have a very interesting problem come up while programming in MPLAB IDE v8.92.
This is just a snipit of the code but this is where the problem is occuring:
```
struct data
{
INT32 value;
};
struct data array[8] = {{0},{0},{0},{0},{0},{0},{0},{0}};
INT32 IOC[8];
INT32 IOD[8];
for ( byte i = 0; i<8; i++)
{
#ifdef DAC
IOC[i] = 0;
IOD[i] = 24;
if(array[i].value == 0) array[i].value == 1;
#endif
}
```
The code builds with no errors and when I step through this part of the code using a ICD 3 debug, IOC and IOD are assigned correctly but the if statement is skipped! i.e. the debugger does not even stop on it. Any ideas what might have happened?
|
Always compile with-Wall -Werror. Your statement would have been flagged at compile time:warning: statement with no effect [-Wunused-value]
|
How can I view C11 header files content of gcc compiler in CodeLite on Linux? if not possible, How/Where can I view them?
Please ignore this location en.cppreference.com/w/c/header since it's just documentary with no actual header file content
|
All the system header files, including the standard C header files, are under/usr/include. You can open any of them with any editor, including the CodeLite editor.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.