question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I want to get a number of days from a certain date to current date.
Here is my current code that gets the days from 1/1/1970.
```
int days_since_my_birth(int day, int month, int year) {
time_t sec;
sec = time(NULL);
printf("Number of days since birth is %ld \n", sec / 86400);
return d;
}
```
Can I... |
Subtract the julian day integer of the earlier date from the julian integer of the later date. The following tells you exactly how to do that.
http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html
Otherwise,http://pdc.ro.nu/jd-code.htmlalready has a C version
```
long gregorian_calendar_... |
This question already has answers here:What is the difference between macro constants and constant variables in C? [duplicate](4 answers)Closed6 years ago.
I am rewriting a function and I noticed one particular variable is never reassigned after initialization. Is there any reason NOT to simply convert this variable... |
A macro is basically never preferable compared to a variable, since a variable which doesn't change its value can be declared asconstand it will likely be optimized away in any case.
```
const int CONST_VALUE = 1234;
```
is safer and clearly expresses the meaning more than a macro.
|
I am a beginner to vim and just downloaded the c-support plugin (for C/C++ programming) from the following link:http://www.vim.org/scripts/script.php?script_id=213
As advised in the link, to enable cmake and doxygen, i added the following lines to my _vimrc:
let g:C_UseTool_cmake = 'yes'
let g:C_UseTool_doxyge... |
(Posted on behalf of the OP).
Iopened an issueon C-Support's Github page, and the problem was solved.
|
```
int j=4;
(!j!=1)?printf("Welcome"):printf("Bye");
```
In the above code segment, according to me, firstj!=1will result in true and!trueis false which must result in printingByebut I getWelcomeas the output.
Can anyone explain this one?
|
!executed first because unary operator!has a higher precedence than!=.
!4become0then0 != 1becometrue.
So, output isWelcome.
|
I think that copying elements of array like this:
```
unsigned char *new_bytes_array = malloc(sizeof(unsigned char)*length/2);
for(int i=0, j=0; i<length; i++) {
if(i % 2 == 0) continue;
new_bytes_array[j] = old_bytes_array[i];
j++;
```
}
is making copy but value not by reference, but I would like to make ... |
new_bytes_array[j]evaluates to anunsigned char.
Assumingold_bytes_array[i]does as well, then this
```
new_bytes_array[j] = old_bytes_array[i];
```
copies anunsigned charand not a pointer, not anunsigned char*.
|
I am writing aSSL ClientusingopenSSLlibrary. I am able to connect tohttps://www.httpbin.orgusing my C program. However, i want to manually set my ownAESkey for further symmetric cryptography and notify the server about key. I know that key for symmetric encryption is set during handshake process. I am usingSSL_connect... |
This is not possible. The key used for encryption depends on data created by both server and client. This means it is not possible to for the client to have full control over the key value. See alsoComputing the Master Secretin RFC 5246 (TLS 1.2).
|
```
//fin here is a file that contains one word per line, with many lines
void* buildTypeWord(FILE* fin){
char temp[100];
Word* aWord =(Word*)calloc(1,sizeof(Word));
fgets(temp,100,fin);
strip(temp); //strips off the new line characters and replaces with a \0
aWord->ltrs=(char*)calloc(strlen(temp)+... |
You should not callfree(temp), as you have not allocated the memory block pointed bytempdynamically.
|
I was wondering what is the difference between the return value of the aforementioned constants.
sysconf(_SC_CLK_TCK)returns100CLOCKS_PER_SECreturns1,000,000
So, suppose that I have this:
```
...
start = clock();
// Process starts here
/* does something */
// Process ends here
end = clock();
double time = ((double... |
As per the documentation,clock()returns time in resolution ofCLOCKS_PER_SEC.
Other time functions return values with resolution inticks.sysconf(_SC_CLK_TCK)provides the number of ticks per second. One such time function istimes().
|
If size is a int variable
```
int size = 10;
```
And I want to round up size to a multiple of 8, what is the difference between the two ways:
A:
```
size = 1 + ((size - 1)/8);
size = size * 8;
```
B:
```
size = (size/8+1)*8;
```
Thanks in advance.
|
Is there any difference between [these] two ways to round a number to a multiple of 8 in C[?]
Yes. They produce different results for inputs that are already multiples of 8. Approach (A) returns such inputs unchanged, but approach (B) returns the next larger multiple of 8 (supposing no overflow).
|
If I want to create a new struct type that contains a pointer the type itself I wouldn't be able to do
```
typedef struct {
my_type* p;
} my_type;
```
and I will need to use a tag
```
typedef struct my_tag {
struct my_tag* p;
} my_type;
```
Is there another use for the tag mechanism? because I've seen it sever... |
Another use is"opaque type", which is usually forward- declared as
```
typedef struct my_type my_type;
```
where you want to define a type at the same time as you do a forward declaration.typedef struct my_type;would have been nonsense. In general, you can't forward-declare without a struct tag.
|
How to get the number of items / rows / length / count of gtk.ListStore in C
Here is my sample code:
```
store = gtk_list_store_new (NUM_COLS, G_TYPE_STRING, G_TYPE_UINT);
/* Append a row and fill in some data */
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter,
COL... |
Use gtk_tree_model_iter_n_children to obtain the number of rows in the list store.
In your case
```
number_of_rows = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), NULL);
```
gtk_tree_model_iter_n_children reference
|
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.Closed6 years ago.Improve this question
I have to implement a backtracing algorithm in C which will emulate a hardware in purely ... |
I've done a few maze solving algorithms, both breadth and depth first search.I'd say you should first build a graph and make sure its perfectly built and without any incoherence, and something i found to be very useful was to find a way to print my graph to check for errors :).Other than that, good luck !
|
The compiler throws an 'unused variable error', when I try to declare any type of variable and assign it a value. Below I use 'float' as the variable type and try and assign it to 1.5.
```
#include <stdio.h>
#include <cs50.h>
int main(void)
{
printf("How long is your shower?\n");
int time = GetInt();
fl... |
flowisn't used by your program - it is not involved in any side effects, you just assign a value to it and discard it. Good compilers warn against such unused variables.
By using-Werroryou turned the warning into an error.
|
This question already has answers here:EOF in Windows command prompt doesn't terminate input stream(2 answers)Closed6 years ago.
I am writing text to a file using the following program.
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int ch;
FILE *fp;
fp = fopen("myfile.txt", "w");
if(fp == NU... |
I verified using a hex editor in Windows^Zcharacter is not written to the file.
|
I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below
```
asm("MOV $00500A,#$3");
```
But I'm facing with following error
```
#error cpstm8 ..\app\sched.c:183(5) missing prototype
```
Can anyone help me in fixing this?
|
For STM8 assembly instruction, you need to use_before the instruction as shown below
```
_asm("MOV $00500A,#$3");
```
|
I have a project where I'need connect two sensors the DHT11 and DHT22 to module nodemcu esp-12e.
Is there any way to use the two sensors in the same module at the same time?
|
If you want an implementation example use steps below:
Get DHT library fromhttps://github.com/adafruit/DHT-sensor-library/Use the code snippet below, but do not forget to set your pins :#include "DHT.h"
#define DHT11PIN 2
#define DHT22PIN 3
DHT dht11(DHT11PIN, DHT11 );
DHT dht22(DHT22PIN, DHT22 );
void setup() {
... |
If I want to create a new struct type that contains a pointer the type itself I wouldn't be able to do
```
typedef struct {
my_type* p;
} my_type;
```
and I will need to use a tag
```
typedef struct my_tag {
struct my_tag* p;
} my_type;
```
Is there another use for the tag mechanism? because I've seen it sever... |
Another use is"opaque type", which is usually forward- declared as
```
typedef struct my_type my_type;
```
where you want to define a type at the same time as you do a forward declaration.typedef struct my_type;would have been nonsense. In general, you can't forward-declare without a struct tag.
|
How to get the number of items / rows / length / count of gtk.ListStore in C
Here is my sample code:
```
store = gtk_list_store_new (NUM_COLS, G_TYPE_STRING, G_TYPE_UINT);
/* Append a row and fill in some data */
gtk_list_store_append (store, &iter);
gtk_list_store_set (store, &iter,
COL... |
Use gtk_tree_model_iter_n_children to obtain the number of rows in the list store.
In your case
```
number_of_rows = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), NULL);
```
gtk_tree_model_iter_n_children reference
|
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.Closed6 years ago.Improve this question
I have to implement a backtracing algorithm in C which will emulate a hardware in purely ... |
I've done a few maze solving algorithms, both breadth and depth first search.I'd say you should first build a graph and make sure its perfectly built and without any incoherence, and something i found to be very useful was to find a way to print my graph to check for errors :).Other than that, good luck !
|
The compiler throws an 'unused variable error', when I try to declare any type of variable and assign it a value. Below I use 'float' as the variable type and try and assign it to 1.5.
```
#include <stdio.h>
#include <cs50.h>
int main(void)
{
printf("How long is your shower?\n");
int time = GetInt();
fl... |
flowisn't used by your program - it is not involved in any side effects, you just assign a value to it and discard it. Good compilers warn against such unused variables.
By using-Werroryou turned the warning into an error.
|
This question already has answers here:EOF in Windows command prompt doesn't terminate input stream(2 answers)Closed6 years ago.
I am writing text to a file using the following program.
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int ch;
FILE *fp;
fp = fopen("myfile.txt", "w");
if(fp == NU... |
I verified using a hex editor in Windows^Zcharacter is not written to the file.
|
I'm programmingSTM8micro controller inSTVD. I happen to use an assembly instruction in the middle of code. As shownhereI used a instruction as below
```
asm("MOV $00500A,#$3");
```
But I'm facing with following error
```
#error cpstm8 ..\app\sched.c:183(5) missing prototype
```
Can anyone help me in fixing this?
|
For STM8 assembly instruction, you need to use_before the instruction as shown below
```
_asm("MOV $00500A,#$3");
```
|
GDB is showing the content of a register as
```
rbp 0x604420 0x604420 <sval>
```
What does sval mean? Does it means string val?
|
What does sval mean?
It means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol.
You can runnm your-binary | grep svaland see that symbol.
Does it means string val?
No,nothingof the sort.
|
With an array of a specified size, the compiler warns me if I placed too many elements in the initialization:
```
int array[3] = {1,2,3,4}; // Warning
```
But, of course, it doesn't do so if I place too few elements (it just fills them with 0s):
```
int array[3] = {1,2}; // OK (no warning)
```
Yet, I MUST ensure ... |
First define your structure using your parameters, without specifying the size:
```
int array[] = { 1 , 2 , 3 };
```
Then simply check if the size of the created array is the same as N using _Static_assert:
```
_Static_assert( sizeof( array ) / sizeof( array[0] ) == N , "problem with array" );
```
|
I'm not familiar with C language. I'm studying it.
I've got a function as looks like this.
I'm keep trying to do to assign integer data to uint8_t *data but it does not.
I've got a error 0x00 does not match to uint8_t *data.
how do I assign to my integer(0x00) data to there?
```
sccb_write_reg(0x01, 0x00); //<---it ... |
For this particular case, the context clues tell us there should bedatain the calling function and you should pass its address in:
```
uint8_t data = 0x00;
uin16_t reg = 0x01;
sccb_write_reg(reg, &data);
```
Note the ampersand (&) before thedata. That says, "Pass in the address ofdata" which is what auint8_t *is, it... |
So lets say the input is 45392.56, the output has to be 49352.56.
How can i program this in C?
|
```
#include <stdio.h>
#include <stdlib.h>
int dotPos(char arr[]) {
int i = 0;
while (arr[++i] != '.');
return i;
}
int main() {
double d = 45392.56;
int MAX = 100;
char arr[MAX];
sprintf(arr, "%f", d);
if (dotPos(arr) > 3) {
char aux = arr[1];
arr[1] = arr[3];
... |
I am learning C usingthissite.
Underfgetc()Function the author said:
This function reads a single character from a file and after reading increments the file position pointer.
```
FILE *fp;
fp = fopen(filename, "r");
```
What I want to ask is that thefile position pointeris different from the pointerfpor not?
|
It means your current offset in the file. It is the return value offtell.
|
GDB is showing the content of a register as
```
rbp 0x604420 0x604420 <sval>
```
What does sval mean? Does it means string val?
|
What does sval mean?
It means that there is a symbol (givenx86_64target,0x604420would usually mean it's a.textsymbol) with that value in the binary, andrbphappens to point to that symbol.
You can runnm your-binary | grep svaland see that symbol.
Does it means string val?
No,nothingof the sort.
|
I've been told that the functiondprintf()can be useful in writing data to pipes. Problem is, I can't find any examples that explain how to use it. I've read everything in that link, but still don't quite understand it.
Just a very simple example will help me understand a lot. For instance, if I had a pipe:
```
int f... |
dprintfworks just likefprintf, except the first parameter is a file descriptor (i.e. anint) instead of aFILE *.
```
dprintf(fd[0], "%d : %d : %d", ID1, ID2, ID3);
```
|
Can I implement quick sort using queue?I found this article onlyhttps://www.quora.com/Can-we-use-a-queue-in-quicksort-in-C.Is this article correct?If yes, why does the textbook always implement quick sort by stack or recursive method only?Because the information about this question is rare, so I ask here.
|
bad cache performance
With stack, we have enough temporal locality, while with queue it is lost completely. We basically are trying to sort the array in breadth first search way in queue method.
EDIT(from Will Ness' answer): And larger arrays(>RAM), queue method won't even work, since it requires O(n) space for sort... |
This question already has answers here:What happens in OS when we dereference a NULL pointer in C?(5 answers)Closed6 years ago.
```
#include<stdio.h>
int main() {
int *p=NULL;
if (p == NULL) {
printf("%x",*p );
}
return 0;
}
```
If I can, How?
If I can't, What value in it?
|
No, you cannot in general dereference aNULLpointer, that gives undefined behavior.
That's sort of the point, so this idea is a bit strange.
Note that this doesn't mean that your code won't run on any platform or produce a result, but it still violates the language specification so the result from running it on some ... |
I have a string "abcdefg-this-is-a-test" and I want to delete the first 6 characters of the string. This is what I am trying:
```
char contentSave2[180] = "abcdefg-this-is-a-test";
strncpy(contentSave2, contentSave2+8, 4);
```
No luck so far, processor gets stuck and resets itself.
Any help will be appreaciated.
Qu... |
```
int len=strlen(content2save);
for(i=6;i<len;i++)
content2save[i-6]=content2save[i];
content2save[i-6]='\0'
```
This will delete first 6 charcters . Based on requirement you may modify your code. If you want to use an inbuilt function trymemmove
|
In the below code snippet , I am trying to assign a value to a global variable using an expression but it gives the error "initializer element is not constant" ,I am unable to get the logic behind this ,please clarify this .
```
#include<stdio.h>
int a=8;
int b=a+9;
int main()
{
printf("%d",b);
return 0;
}
``... |
The reason is that global variables are initialized in compiling time,
and you are trying to initializeb=a+9;as an operation that must be done in execution time.
|
I am trying to compile the basic "Hello World" C code with gcc but the following error appears:
```
ld: library not found for -lgcc
collect2: error: ld returned 1 exit status
```
The code itself it's fine, ran it in another computer without any problems.
Here there's apictureof how the terminal looks like. I am not... |
It was just an incompatibility of the compiler with Yosemite I think. Have to compile with gcc4.9 and it works just fine.
You compile with gcc4.9 this way
```
gcc-4.9 -o output file.c
```
|
When usingdprintf()I'm getting the warning "implicit declaration of dprintf". That tends to mean a necessary file isn't included, but I already included stdio.h, which is supposed to be all that it needs. Is there something else dprintf needs?
|
The "feature_test_macros" section of the man page explains that to make stdio.h declare dprintf(), you must first#define _POSIX_C_SOURCE 200809L(or higher) before you#include <stdio.h>. The reason for this is that dprintf() was not standardized until POSIX.1-2008, but<stdio.h>needs to continue to work with code writt... |
I've been told that the functiondprintf()can be useful in writing data to pipes. Problem is, I can't find any examples that explain how to use it. I've read everything in that link, but still don't quite understand it.
Just a very simple example will help me understand a lot. For instance, if I had a pipe:
```
int f... |
dprintfworks just likefprintf, except the first parameter is a file descriptor (i.e. anint) instead of aFILE *.
```
dprintf(fd[0], "%d : %d : %d", ID1, ID2, ID3);
```
|
Can I implement quick sort using queue?I found this article onlyhttps://www.quora.com/Can-we-use-a-queue-in-quicksort-in-C.Is this article correct?If yes, why does the textbook always implement quick sort by stack or recursive method only?Because the information about this question is rare, so I ask here.
|
bad cache performance
With stack, we have enough temporal locality, while with queue it is lost completely. We basically are trying to sort the array in breadth first search way in queue method.
EDIT(from Will Ness' answer): And larger arrays(>RAM), queue method won't even work, since it requires O(n) space for sort... |
This question already has answers here:What happens in OS when we dereference a NULL pointer in C?(5 answers)Closed6 years ago.
```
#include<stdio.h>
int main() {
int *p=NULL;
if (p == NULL) {
printf("%x",*p );
}
return 0;
}
```
If I can, How?
If I can't, What value in it?
|
No, you cannot in general dereference aNULLpointer, that gives undefined behavior.
That's sort of the point, so this idea is a bit strange.
Note that this doesn't mean that your code won't run on any platform or produce a result, but it still violates the language specification so the result from running it on some ... |
I have a string "abcdefg-this-is-a-test" and I want to delete the first 6 characters of the string. This is what I am trying:
```
char contentSave2[180] = "abcdefg-this-is-a-test";
strncpy(contentSave2, contentSave2+8, 4);
```
No luck so far, processor gets stuck and resets itself.
Any help will be appreaciated.
Qu... |
```
int len=strlen(content2save);
for(i=6;i<len;i++)
content2save[i-6]=content2save[i];
content2save[i-6]='\0'
```
This will delete first 6 charcters . Based on requirement you may modify your code. If you want to use an inbuilt function trymemmove
|
I have a string
```
"inet6 addr: 2620:cb:0:b007::23c3/112 Scope:Global",
```
and I want to extract only
```
"2620:cb:0:b007::23c3"
```
from the above string.
How can I extract the substring using cut/sed/awk command.
|
Here isawkversion: Using split function of awk.
```
echo $x
"inet6 addr: 2620:cb:0:b007::23c3/112 Scope:Global",
echo $x |awk '{split($3,a,"/");print a[1]}'
2620:cb:0:b007::23c3
```
Or go with this:
```
echo $x |grep -Po '(?<=(: )).*(?=/)'
2620:cb:0:b007::23c3
```
OR Usesedto capture group of data between:and f... |
I would like to create a C program to send a .xml file to a FTP server which I have been given the username and password to periodically. What would be the easiest way to do this?
One idea I had was to just create strings containing the instructions and execute these usingsystem("command")however I have not used FTP ... |
```
ftp -u ftp://user:passt@ftp.ftpserver.com/local-file.txt local-file.txt
```
Probably lftp is a better choicehere.
```
lftp ftp://user:password@host -e "put local-file.name; bye"
```
|
I have a code which is branched by#definedirective, for example:
```
#ifdef USE_LIB_CRYPTO
#include <openssl/evp.h>
#else
#include <cryptopp/pwdbased.h>
#include <cryptopp/sha.h>
#endif
```
Depending on is definedUSE_LIB_CRYPTOor not I should add
```
LIBS += -lcrypto
```
or
```
LIBS += -lcryptopp
```
How can I d... |
You can usecontainstest function of the qmake.
```
contains ( DEFINES, USE_LIB_CRYPTO ){
LIBS += -lcrypto
} else {
LIBS += -lcryptopp
}
```
|
I am currently working on a school project, and I am trying to define 12 photocells. For the first 8 sensors, nothing is wrong, but the 9th one does not work for some reason.
Here is my code:
```
const int analogInPin_0 = A0;
const int analogInPin_1 = A1;
const int analogInPin_2 = A2;
const int analogInPin_3 = A3;
c... |
The same thing happened to me. After long wasted hours, I decided to try the code on my Uno. Only then I realized that the board was selected as Uno while I was trying on my Mega. Changed the board to Mega and viola, everything worked perfectly.
|
I am a beginner in loadrunner. I am working with Loadrunner 12.53. I have recorded one simple which will login to one application and Logout.(I recorded withuser1login id) I am testing it with different users say(user2, user3, user4,..., user10, user11). The script is passing successfully tilluser9and it is failing f... |
Record your site with User 10 settings. Compare to a recording for User9. The differences in structure will need to be addressed
|
I'm studying C at the university and I just downloaded Clion; How can I change the default language so that every project I create will be ready to work?
|
Depending on the version of Clion you will either see theCMakeLists.txtcontain something like
```
set(CMAKE_CXX_FLAGS "-std=c++11")
```
or for recent EAP builds
```
set(CMAKE_CXX_STANDARD 11)
```
Simply change the variables and flags to the correct ones for C.
There's currently no way (that I know of) to make it ... |
In assembly language, if you have two variables, address a0 and byte t0, it's easy to store t0 at the very beginning of address a0 by typing
```
sb $t0,0($a0)
```
Now, I want to do the same thing in C, and in this case I've got
```
char* a0 = "AbC";
char t0 = 'w';
```
I know I can't access and modify a0[0] directl... |
You cannot replace the'A'because it is in a string literal, which is read-only.
You can, however, store the string in an array, which makes the letters and accessible and then replace the'A'easily:
```
char a0[] = "AbC";
char t0 = 'w';
a0[0] = t0;
```
|
I am trying below code:
```
typedef union Data
{
int i;
}data;
int main( )
{
data d1;
d1.i = 10; // OK
data d3 = {7};// OK
data d2.i = 20; // Gives error
}
```
My question why it is giving error fordata d2.i = 20and works for other?
|
Because it's not valid syntax.
It has nothing to do with theunion, i.e. it would be the same for astruct.
You're trying to use the name of aunionmember as a name, that's not valid. Names cannot contain the dot (.).
The initializations work since there is a matching (sort of) of the initializer expression (the right... |
I usepopento executetype -t type, this give me an error message-tnot found. When I performtype -t typein the shell this gives mebuiltin. Why doesn't this work withpopen?
|
POSIX specifies that the shell used withpopenis/bin/sh. Your interactive shell is probablybash. The behaviour of thetypecommand is different forshandbash.shdoes not support-t.
Your system probably has/bin/shsymbolically linked to/bin/dash, but that's just an implementation detail.
If you needbashbehaviour, runbashex... |
I have the following code that I don't understand
```
shiftLeft = local.tasks.first != NULL;
if(!shiftLeft)
local.tasks.last = NULL;
```
I mean the shiftLeft variable (which is boolean) supposed to be evaluated last, so in the first place evaluates local.tasks.first != NULL, but what is that?
|
This will return either true or false value (depending on fact iflocal.task.firstis aNULLvalue or not).
Iflocal.task.firstisNULLashiftLeftvariable will getfalsevalue,
Iflocal.task.firstis not aNULLvalue ashiftLeftvariable will gettruevalue.
What is important, we don't know type ofshiftLeft, if it is a bool variable... |
I read some code and came over this rather cryptic syntax:
```
size_t count = 1;
char *s = "hello you";
char *last_word = "there";
count += last_word < (s + strlen(s) - 1); #line of interest
```
Count is incremented, somehow. But I thought the < operator would return true or false.
What does this line do?
|
As per theoperator precedancetable,<binds higher than+=operator, so your code is essentially
```
count += ( last_word < (s + strlen(s) - 1)) ;
```
where, the(A < B)evaluates to either 0 or 1Note, so, finally, it reduces to
```
count += 0;
```
or
```
count += 1;
```
Note:related to the "1or0" part, quotingC11, ch... |
I read some code and came over this rather cryptic syntax:
```
size_t count = 1;
char *s = "hello you";
char *last_word = "there";
count += last_word < (s + strlen(s) - 1); #line of interest
```
Count is incremented, somehow. But I thought the < operator would return true or false.
What does this line do?
|
As per theoperator precedancetable,<binds higher than+=operator, so your code is essentially
```
count += ( last_word < (s + strlen(s) - 1)) ;
```
where, the(A < B)evaluates to either 0 or 1Note, so, finally, it reduces to
```
count += 0;
```
or
```
count += 1;
```
Note:related to the "1or0" part, quotingC11, ch... |
How to concatenate two strings for example
```
char s[5]={'s','a','\0','c','h'};
char m[11]={'b','e','\0','c','h','b','\0','e','\0','c','h'};
```
that has many null characters. I triedstrcat(). Its not working. Is there any way?
|
This is tricky, because by definition C-strings are null-terminated. So what you really have are two byte buffers that you want to put together, not two strings. (This is why functions likestrcatdon't work here, by the way -- they expect their arguments to be C-strings.)
Since you can't use the null character to tell... |
I am running a program for school and am running into a simple math problem that C is not calculating correctly. I am simply trying to divide my output by a number and it is returning the original number.
```
int main(void)
{
float fcost = 599;
float shipt = (fcost / 120);
shipt = shipt * 120;
prin... |
From what was stated in the comments, you want the result of the division to be rounded down.
In order to do that, you should useintinstead offloatso that integer division is performed (which truncates the fractional part) instead of floating point division (which retains the fractional part):
```
int fcost = 599;
i... |
i have two .c files1.cand2.cand a header file3.h
1.chas a global variable defined like thisint table
2.chas a global variable defined like thisextern int tableand
includes 3.h
3.hhasint tabledeclared.
Does compiler allow this? If yes, How likely istablein1.cgoing to be corrupted(by 2.c)?
I hope i made myself cle... |
File1.cdeclares a global variableint table;.
File3.h, once included in a source file, declares a global variableint table;. It is included in2.cso2.cnow also has declared a global variableint table;.
They will compile fine, but you probably get a linker error saying thattableis multiply defined.
|
I am trying to write a wrapper for a C library that contains a function which takes another function to achieve polymorphism (i.e. a generic function). I would like to write my wrapper such that it takes a Scheme function and passes it to the generic function as a C function pointer. Does Guile provide functionality t... |
You have to useprocedure->pointerprocedure which is described in themanual.
|
When I usefork()to create a child process the child is a duplicate of the parent. Would a pointer point to the same thing in each process or does the pointer take a new value in the child. What about an array, or file pointers?
|
Would a pointer point to the same thing in each process.
Yes, all memory is copied including pointers.
What about an array, or file pointers?
Yes. In the case of filedescriptors, it is useful to note that any file descriptors open in the parent, will refer to the same files in the child process.
Most (all?) Unix... |
I have a function called dump in file1.c.
```
void dump(unsigned long val, unsigned char raw){
unsigned long dec = 0;
dec = hex(val);
}
```
hex function is in file2.c.
```
unsigned long hex(unsigned long hex){
unsigned long result;
...
return result;
}
```
For some reason dec variable contains only 2... |
This might be a linking issue, not picking uphex()from the right file. Try linking withoutfile2.oand it should complain about the missing function.
|
I am trying to create an manage security scoped bookmarks but need to use only plain C, that is using Objective-C in a plain C file.
Is it even doable or should I just give up?
Any advices?
Can I call Obj-C function inside C function and keeping the file as .c?
Thank you in advance all,
Nikolas
|
I can't imagine why you'd want to use onlyCwhen you have support forObjective-Cavailable. But if you really want to do it, then a valid approach is to use theCoreFoundationsupport forNSURLand memory management.
All URLCoreFoundationfunctions can be foundhere.
Regarding the memory management, you might be interested ... |
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed6 years ago.Improve this question
If in code there are many if-clauses and execution of code is not sensible on a prev... |
Yes, this is idiomatic, even if, perhaps, it was not the intended use for adowhileloop. The source code for the linux kernel exploits this.
There's nothing unclear about it:while(false)does exactly what is says on the tin.
|
The only way I see to access all nodes (if the keys are not known) istwalk. Is it allowed to usetdeleteinsidetwalk? If not--how delete all nodes? (I don't wan't to use the non-portable GNU extensiontdestroy.)
|
No, you don't need to usetwalk, you can usetdeletewith a comparison function (the same function used to insert),tdeletechanges the root node, so passing and deletingwhile (root != NULL)will do the trick, something like:
```
typedef struct {
int key;
char value[50];
} t_data;
static int comp(const void *pa, c... |
I have a function which accepts a character array (ie, string) as argument.
But an integer variable's value should also be printed as part of string.
For example,
If I have a function like this:
```
int var=10;
void printStr(char str[])
{
printf("%s", str);
}
```
and I need to print the value of integer variabl... |
It seems that you need the functionsprintf/snprintffor generation of the string.
Try something like this:
```
char tempStr[30];
snprintf(tempStr, sizeof(tempStr), "The value of var is %d", var);
printStr(tempStr);
```
Is it what you need?
|
I have a simple code to reverse a string:
```
char* reverse(char* s){
int i,j,len=strlen(s);
char* r;
for(i=len-1,j=0;i>=0;i--,j++){
printf("%d:%c\n",j,s[i]);
r[j]=s[i];
}
```
assume input string is "abc" , then the output "Without" the liner[j]=s[i];inside loop is :
```
0:c
1:b
2:a
```
if I include ... |
First of all, you are writing to uninitialized pointer: char* r is declared, but never allocated. Allocate memory dynamically or on the stack, then write into it.
For example:
```
char* r = malloc(len + 1);
```
Right now your code is most likely crashing when you are trying to access uninitialized memory.
|
Using opaque typesis an acceptable method of hiding a type's structure. But why not use them all the time? What are the benefits and situations that call for transparent types, especially in C?
|
Opaque types require you to write up a full API for tasks such as assignment, comparison, formatted I/O, member access, etc., which may or may not be worth the effort.
And, sometimes, using a plain old scalaristhe right answer; would you use an opaque type to store an average? A count?
|
What is the fastest way to find unused enum members?
Commenting values out one by one won't work because I have almost 700 members and want to trim off a few unused ones.
|
I am not aware of any compiler warning, but you could possibly try withsplintstatic analyzer tool. According to itsdocumentation(emphasis mine):
Splint detects constants, functions, parameters, variables, types,enumerator members, and structure or union fields that are declared
but never used.
As I checked, it wor... |
I'm learning C pointers. I have incremented a double pointer by 1, as follows:
before ->ptr_double =0x0128
then I incremented it by 1, and then the address stored in ptr_double increases by 8 bytes, that is0x0128+ 8 which gives0x0130.
I'm unable to understand how arithmetically0x0130comes.
I know this is probably ... |
I assume you have a pointer todoublelikedouble* ptr_double;, which has its value0x128, then you increment it++ptr_double;(which makes the pointerjumpwith asizeof(double), which in this case is8). The address is in hexadecimal (base 16), so
```
0x128 + 0x8 = 0x130
```
Remember that hexadecimals belong to the range0,1... |
Can anyone explain how the following program works? herename[]is an array of pointers to char then how can name contain values instead of addresses and how come the values stored are strings rather than character?
```
#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"... |
A string literal like"Zara Ali"evaluates to the address of its first character.
The string literal is generally stored in read-only data segment.
So essentiallyyour array contains addresses.
You can also write
```
char *str="Zara Ali";
//The value of a string literal is the address of its first character.
```
|
I'm trying define "ip_addr" from lwip. That's my code:
```
#include "lwip/tcp.h"
#include "ip_addr.h"
...
struct ip_addr ip;
```
But when i'm trying to compile this, compiler gives me error:
```
error: storage size of 'ip' isn't known
```
|
Try:
```
ip_addr_t ip;
```
and your second #include line should it not be:
```
#include "lwip/ip_addr.h"
```
|
What are the differences betweenvoid quick_exit( int exit_code )which was included in c11 standard andvoid exit( int exit_code )function that already existed before c11 standard?
|
exitensures that stream buffers are flushed, closed, etc. Such behavior forquick_exitis not specified by the standard.
With these you can define two ways of quitting an application, one that lets you terminates with full cleaning (made by functions registered withatexit), and the other to let applications terminate m... |
I am trying to get aGdkRGBAfrom aGValue, but I am unable to init aGValuewith such a type.
I tried the following code:
```
GValue value;
g_value_init(value, G_TYPE_OBJECT);
gtk_style_context_get_property(style_context, "color", STATE_FLAG_NORMAL, &value);
```
But I get the following error:
cannot initialize GValue ... |
Try removing the call tog_value_initaltogether—judging by the error message it seemsgtk_style_context_get_propertywants to initialize theGValueon its own.
Also, I note there isa separate method defined onGtkStyleContextspecifically for retrieving the foreground colour, so this may be a suitable (or preferable) altern... |
Hello this is my solution to to uri 1759
```
#include <stdio.h>
int main()
{
int i,j;
scanf("%d", &i);
for (j=1;j<=i;j++)
{
printf("Ho ");
while (j==i)
{
printf("\b");
printf("!");
break;
}
}
return 0;
}
```
I don't know wha... |
Your solution maylookcorrect, it isn'tidenticalto the desired output, because of the trailing space that you erase by inserting a backspace. So, the solution is to re-craft your logic to avoid having to erase that trailing space.. One way of doing that, which I don't advise to really use, is like this:
```
#include <... |
Hi i tried out a code in c and considering that all variables in the following line of code were of "long long int",
money=(money % 1000000007)+(((2*pow(abs(a[i]-a[j]),k))%1000000007) % 1000000007);
i received an error which states that
error: invalid operands to binary % (have 'double' and 'int')
money=(mon... |
% is an integer operator and pow() returns a double. So, you may need to use fmod or fmodf or convert everything to int.
```
money=(money % 1000000007)+(((2*(long long int)pow(abs(a[i]-a[j]),k))%1000000007))) % 1000000007);
```
|
What are the differences betweenvoid quick_exit( int exit_code )which was included in c11 standard andvoid exit( int exit_code )function that already existed before c11 standard?
|
exitensures that stream buffers are flushed, closed, etc. Such behavior forquick_exitis not specified by the standard.
With these you can define two ways of quitting an application, one that lets you terminates with full cleaning (made by functions registered withatexit), and the other to let applications terminate m... |
I am trying to get aGdkRGBAfrom aGValue, but I am unable to init aGValuewith such a type.
I tried the following code:
```
GValue value;
g_value_init(value, G_TYPE_OBJECT);
gtk_style_context_get_property(style_context, "color", STATE_FLAG_NORMAL, &value);
```
But I get the following error:
cannot initialize GValue ... |
Try removing the call tog_value_initaltogether—judging by the error message it seemsgtk_style_context_get_propertywants to initialize theGValueon its own.
Also, I note there isa separate method defined onGtkStyleContextspecifically for retrieving the foreground colour, so this may be a suitable (or preferable) altern... |
Hello this is my solution to to uri 1759
```
#include <stdio.h>
int main()
{
int i,j;
scanf("%d", &i);
for (j=1;j<=i;j++)
{
printf("Ho ");
while (j==i)
{
printf("\b");
printf("!");
break;
}
}
return 0;
}
```
I don't know wha... |
Your solution maylookcorrect, it isn'tidenticalto the desired output, because of the trailing space that you erase by inserting a backspace. So, the solution is to re-craft your logic to avoid having to erase that trailing space.. One way of doing that, which I don't advise to really use, is like this:
```
#include <... |
Hi i tried out a code in c and considering that all variables in the following line of code were of "long long int",
money=(money % 1000000007)+(((2*pow(abs(a[i]-a[j]),k))%1000000007) % 1000000007);
i received an error which states that
error: invalid operands to binary % (have 'double' and 'int')
money=(mon... |
% is an integer operator and pow() returns a double. So, you may need to use fmod or fmodf or convert everything to int.
```
money=(money % 1000000007)+(((2*(long long int)pow(abs(a[i]-a[j]),k))%1000000007))) % 1000000007);
```
|
I'm using ctypes to call a function of a MinGW-w64 compiled library.
C code:
```
#include <stdio.h>
int hello()
{
printf("Hello world!\n");
return 233;
}
```
Python Code:
```
from ctypes import *
lib = CDLL("a.dll")
hello = lib.hello
hello.restype = c_int
hello()
```
Compile C code with gcc in MinGW-w64:... |
Use 'x86_64-w64-mingw32-gcc' or 'i686-w64-mingw32-gcc' instead of 'gcc' in msys!
The 'gcc' command calls x86_64-pc-msys-gcc.
|
I use codeblocks to compile my code in C language.but I faced fatal error.
my code is:
```
#include<stdio.h>
#include<stack.h>
```
the fatal erroe is:
```
stack.h:No such a file or directory
```
What is my problem?
|
```
#include <filename.h>
```
is for standard/system headers that come with the language/compiler/operating system, for example:
```
#include <stdio.h>
```
includes a well-defined header file that is part of the C standard library for IO routines.
The C standard doesnotdefine astack.hheader file, so the file you a... |
I have a pointer & 2 different structures. The first structure has a member that is a void* pointer. Now i need to access a member of the second structure using the previous pointer to the first structure.
```
struct a {
void *ptrxx;
}
struct b {
int info;
}
struct a *ptr;
```
I need to do something like :
``... |
```
((struct b *)(ptr->ptrxx))->info
```
Probably don't need all those parens, but it helps to show the order of what's happenning. Take theptrxxmember ofstruct a(which is avoid *), cast it into a pointer tostruct b, then take theinfomember of that.
|
I have 2 string value. str and str2 . i wish to xor the str and str2
My code is
```
#include <stdio.h>
int main(){
char str[] = "Hello";
char str2[] = "World";
char outupt;
output = str[] ^ str2[];
printf("%s",output)
return 0;
}
```
|
character by character:
```
#include <stdio.h>
#include <string.h>
int main(){
int i;
char str[] = "Hello";
char str2[] = "World";
char output[6];
for (i=0; i<strlen(str); i++)
{
char temp = str[i] ^ str2[i];
output[i] = temp;
}
output[i] = '\0';
printf("%s", output);
return 0;
}
... |
I'm currently writing a program that involves graphics. After some thought I decided to write directly to the frame buffer on /dev/fb0 and the code is working great but the writing speed is slow. It takes 0.161s to write a blank screen (0.213s is the program with the fb0 writing and 0.052s is the program without writi... |
You can map the framebuffer device into memory usingmmap()and blit to and from it withmemcpy()or pointers. Unless you are running X windows, in which case you need to go through an API such as X11, OpenGL or SDL.
|
I'm reading a book about bufferoverflows and shellcode, and in the book there is this code below.
I understand most of it except the purpose ofbuffer = command +strlen(command);.
When I usememset()on the buffer doesn't it overwrite what I stored there previously withcommand+strlen(command)?
Can someone clarify it fo... |
When one of the operands of+is a pointer then C does pointer arithmetic.
The result orpointer + numberis a pointer value that points to the value with indexnumber. It is equivalent to&pointer[number].
So, in this case:
```
buffer = command + strlen(command);
```
is equivalent to
```
buffer = &command[strlen(comma... |
I am currently playing withzlib.
Usual example is more or less as follows (C/C++ pseudo code)
```
z_stream zs;
memset(&zs, 0, sizeof(zs));
if (deflateInit(&zs, Z_DEFAULT_COMPRESSION) != Z_OK)
return false;
zs.next_in = input_data;
zs.avail_in = input_size;
zs.next_out = output_data;
zs.avail_out = output_si... |
Yes. You can usedeflateReset()to have the same effect asdeflateEnd()followed bydeflateInit(), but entirely avoiding the costly de- and re-allocations.
|
InC,array elements are treated as pointers. So the expressionsizeof(arr)/sizeof(arr[0])becomessizeof(int *)/sizeof(int)which results in1then why the following program give output is12 11.
```
#include <stdio.h>
int main()
{
int n1, n2;
char arr1[] = "Hello World";
char arr... |
array elements are treated as pointers
It is not a true. Arrays areNOTpointers. But they decay to pointers to first element when are passed to functions. Andsizeof(array)is the number of bytes that whole array occupies.
|
I have a MinGW folder in Windows and I didn't set any paths in environment variables. When I run the following command:
```
D:\toolchains\MinGW\bin>gcc.exe hw.c -o hw
```
I got this error:
```
gcc.exe: error: CreateProcess: No such file or directory
```
As far as I understand, this problem caused by that I didn't ... |
You either have to modify your PATH environment variable or start the gcc process with the right working directory. You can do both in python:
Modify environment variables from within pythonSpecify a working directory for a subprocess in python
I would recommend to modify the PATH variable.
|
my code can be compiled with C or C++ compilers.
I'd like to know which one is doing the compilation
is there preprocessor define to tell me this ?
|
The definition is__cplusplus.
```
#ifdef __cplusplus
// treated as C++ code
#else
// treated as C code
#endif // __cplusplus
```
|
Currently I am working on an application and need to log all the xml content in http request/response. My application is based on C and use gsoap. I have very less experience on working with gsoap.
Went through the gsoap userguide also some answers on stackoverflow which suggests to use plugins and refer to plugin.h ... |
Register the message logging plugin declared ingsoap/plugin/logging.has follows:
```
#include "plugin/logging.h"
struct soap *ctx = soap_new();
// Register the plugin
soap_register_plugin(ctx, logging);
// Change logging destinations to stdout (or another open FILE*):
soap_set_logging_inbound(ctx, stdout);
soap_se... |
In /usr/include/stdio.h
```
/* C89/C99 say they're macros. Make them happy. */
#define stdin stdin
#define stdout stdout
#define stderr stderr
```
How is this supposed to work?
|
The key point is that once a macro has been expanded, it is not replaced again in the replacement text. That means that when the preprocessor comes acrossstderrin:
```
fprintf(stderr, "Usage: %s file [...]\n", argv[0]);
```
it replaces thestderrtoken withstderr, and then rescans the replacement text, butstderris no... |
InC,array elements are treated as pointers. So the expressionsizeof(arr)/sizeof(arr[0])becomessizeof(int *)/sizeof(int)which results in1then why the following program give output is12 11.
```
#include <stdio.h>
int main()
{
int n1, n2;
char arr1[] = "Hello World";
char arr... |
array elements are treated as pointers
It is not a true. Arrays areNOTpointers. But they decay to pointers to first element when are passed to functions. Andsizeof(array)is the number of bytes that whole array occupies.
|
I have a MinGW folder in Windows and I didn't set any paths in environment variables. When I run the following command:
```
D:\toolchains\MinGW\bin>gcc.exe hw.c -o hw
```
I got this error:
```
gcc.exe: error: CreateProcess: No such file or directory
```
As far as I understand, this problem caused by that I didn't ... |
You either have to modify your PATH environment variable or start the gcc process with the right working directory. You can do both in python:
Modify environment variables from within pythonSpecify a working directory for a subprocess in python
I would recommend to modify the PATH variable.
|
my code can be compiled with C or C++ compilers.
I'd like to know which one is doing the compilation
is there preprocessor define to tell me this ?
|
The definition is__cplusplus.
```
#ifdef __cplusplus
// treated as C++ code
#else
// treated as C code
#endif // __cplusplus
```
|
Currently I am working on an application and need to log all the xml content in http request/response. My application is based on C and use gsoap. I have very less experience on working with gsoap.
Went through the gsoap userguide also some answers on stackoverflow which suggests to use plugins and refer to plugin.h ... |
Register the message logging plugin declared ingsoap/plugin/logging.has follows:
```
#include "plugin/logging.h"
struct soap *ctx = soap_new();
// Register the plugin
soap_register_plugin(ctx, logging);
// Change logging destinations to stdout (or another open FILE*):
soap_set_logging_inbound(ctx, stdout);
soap_se... |
In /usr/include/stdio.h
```
/* C89/C99 say they're macros. Make them happy. */
#define stdin stdin
#define stdout stdout
#define stderr stderr
```
How is this supposed to work?
|
The key point is that once a macro has been expanded, it is not replaced again in the replacement text. That means that when the preprocessor comes acrossstderrin:
```
fprintf(stderr, "Usage: %s file [...]\n", argv[0]);
```
it replaces thestderrtoken withstderr, and then rescans the replacement text, butstderris no... |
I am trying to define a function pointer which calculates e^-x.
Something similar to C# equivalent:
```
Func<double, double> f = x => Math.Exp(-x);
```
I tried in vain by doing something like:
```
double(*negativeExp(double x))(double) {
double eValue = exp(1);
return pow(eValue, -x);
}
```
Any ideas.
|
The code for the function would be:
```
double f(double x)
{
return exp(-x);
}
```
Then you can make a pointer to that function. Sample use:
```
int main(void)
{
double (*p)(double) = &f;
printf("f(1) == %f", p(1));
}
```
|
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
When trying to print a backspace("\b \b")to a file (inC), it would show up as an unicode character (0x08).
... |
If you are trying to delete characters from an existing file, you should use fseek. printing '\b' won't help.
|
This code is incorrect but it tells what I am trying to do
```
char* p = EM_ASM(
var a = new ArrayBuffer(8);
return a;
);
```
What is the correct way of getting a C pointer of that javascript arrayBuffer?I only want to read the arrayBuffer not write
|
As far as I'm aware, there's no direct way of returning an array from some inline JavaScript (although there is a way of returning read-only arrays from JavaScript wrapped C functions, seethis answer). What you can do instead is malloc space for the array in a C function, pass the address to the inline Emscripten, and... |
I'm trying to print "Hello the number 5 is correct!" in C.
The way I'm doing it now is with two printf statements:
```
printf("Hello the number %d", number);
printf(" is correct!\n");
```
How can I do this in one statement like in Java:
```
System.out.println("Hello the number "+number+" is correct!");
```
I've t... |
You can embed the format specifier into the middle of the string like so:
```
printf("Hello the number %d is correct!\n", number);
```
Alternatively, you can use another format specifier for the rest of the string:
```
printf("Hello the number %d%s\n", number, " is correct!");
```
|
I am trying to define a function pointer which calculates e^-x.
Something similar to C# equivalent:
```
Func<double, double> f = x => Math.Exp(-x);
```
I tried in vain by doing something like:
```
double(*negativeExp(double x))(double) {
double eValue = exp(1);
return pow(eValue, -x);
}
```
Any ideas.
|
The code for the function would be:
```
double f(double x)
{
return exp(-x);
}
```
Then you can make a pointer to that function. Sample use:
```
int main(void)
{
double (*p)(double) = &f;
printf("f(1) == %f", p(1));
}
```
|
This question already has answers here:Sizeof arrays and pointers(5 answers)Closed7 years ago.
```
#include<stdio.h>
#include<stdlib.h>
int main (int argc, char *argv[]) {
int* arr1 = (int*)malloc(sizeof(int)*4);
int arr2[4];
printf("%d \n", sizeof(arr1));
printf("%d \n", sizeof(arr2));
free(... |
Arrays are not pointers.
In your code,arr1is a pointer,arr2is an array.
Type ofarr1isint *, whereas,arr2is of typeint [4]. Sosizeofproduces different results. Your code is equivalent to
```
sizeof (int *);
sizeof (int [4]);
```
That said,sizeofyields the result of typesize_t, so you should be using%zuto print the ... |
I want to create a socket connected directly to the gpu.
I would like to send data from a server to the gpu without spending a copy/moving time from host to device.
Is it possible?
|
If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products.
But realistically, no.
|
When writing a program (Unix-style), can it address and manage more than one stdout and stdin channels?
|
No; there is (at most) one standard input and one standard output at any given time. Ultimately, since the question specifically mentions Unix, standard input is file descriptor 0 and standard output is file descriptor 1, and there is only one file descriptor with a given number.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.