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 use thetime()function to get the number of seconds from a date I entered?
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_to_jd(int y, int m, int d) { y+=8000; if(m<3) { y--; m+=12; } return (y*365) +(y/4) -(y/100) +(y/400) -1200820 +(m*153+3)/5-92 +d-1; } ```
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 to a macro? Is a macro ALWAYS preferable in this case? Thanks!
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_doxygen = 'yes' However, now when I start up gvim, I get the following error message dialog: ``` Could not load the tool "cmake" (Vim(let):E117: Unknown function: mmtoolbox#make#Interface)- occurred at C:\Users\Satyendra\Vim\vimfiles\autoload\mmtoolbox\cmake.vim, line 219 ``` My OS is Windows 10. How do I resolve this error?
(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 sure that this will be deep copy not just shallow copy of references or pointers. I know that this is maybe easy and ridiculous qustion, but I cannot find similar on stack rather memcpy() all array, but I want to copy only some elements for example every second element, or copy 1-3 elements and skip 4th element, (if i%4 == 0 skip element).
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()to connect to server. How can i manually set key for symmetric cryptography?
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)+1,sizeof(char)); strcpy(aWord->ltrs, temp); aWord->len=strlen(temp); printf("%s",aWord->ltrs); //just me bug testing free(temp); printf("%s",aWord->ltrs); //just me bug testing return aWord; } ``` This method is supposed to take a word from the file that is passed in and attach that word to a word object. For what ever reason something here is causing the program to seg fault. On a side note unless I have that free(temp) there no information about the seg fault is given.
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) end-start)/CLOCK_PER_SEC; // this would return in seconds ... ``` How do I calculate the amount of ticks used by the process, instead of the time? Do I use time used againstsysconf(_SC_CLK_TCK)orCLOCK_PER_SEC? I am trying to understand the usage of those.
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 several times and I don't understand why someone would add this to atypedef Also, since C and C++ are a bit different with theirstructkeyword, would that change anything if I typedef such a struct in C or in C++?
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_NAME, "Heinz El-Mann", COL_AGE, 51, -1); /* . . . */ /* get the length of gtk_list_store*/ ```
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 software, and trace a single path from output of a system to the input pin, registering all the gates, their outputs and inputs(taken) on the path in a reverse order. I figured out that it can be done in graph traversal algorithm but not able to implement in C. Any useful suggestions shall be helpful indeed!
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(); float flow = 1.5; } ``` The compiler throws this error: ``` ~/workspace/pset1/ $ make water clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow water.c -lcs50 -lm -o water water.c:10:11: error: unused variable 'flow' [-Werror,-Wunused-variable] float flow = 1.5; ^ 1 error generated. make: *** [water] Error 1 ```
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 == NULL) { printf("Error opening file\n"); exit(1); } printf("Press Ctrl+D to stop \n\n"); printf("Enter text: "); while( (ch=getchar()) != EOF ) { fputc(ch, fp); } fclose(fp); } ``` Let's say the input is: ``` Press Ctrl+D to stop \n\n Enter text: this is a test ^Z ``` My question is the end of file character (ASCII value 26) will be written to the file or not ?
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() { Serial.begin(9600); Serial.println("DHTxx test!"); dht11.begin(); dht22.begin(); } void loop() { delay(2000); float h11 = dht11.readHumidity(); float t11 = dht11.readTemperature(); float f11 = dht11.readTemperature(true); float h22 = dht22.readHumidity(); float t22 = dht22.readTemperature(); float f22 = dht22.readTemperature(true); //do print them.. }
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 several times and I don't understand why someone would add this to atypedef Also, since C and C++ are a bit different with theirstructkeyword, would that change anything if I typedef such a struct in C or in C++?
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_NAME, "Heinz El-Mann", COL_AGE, 51, -1); /* . . . */ /* get the length of gtk_list_store*/ ```
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 software, and trace a single path from output of a system to the input pin, registering all the gates, their outputs and inputs(taken) on the path in a reverse order. I figured out that it can be done in graph traversal algorithm but not able to implement in C. Any useful suggestions shall be helpful indeed!
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(); float flow = 1.5; } ``` The compiler throws this error: ``` ~/workspace/pset1/ $ make water clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow water.c -lcs50 -lm -o water water.c:10:11: error: unused variable 'flow' [-Werror,-Wunused-variable] float flow = 1.5; ^ 1 error generated. make: *** [water] Error 1 ```
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 == NULL) { printf("Error opening file\n"); exit(1); } printf("Press Ctrl+D to stop \n\n"); printf("Enter text: "); while( (ch=getchar()) != EOF ) { fputc(ch, fp); } fclose(fp); } ``` Let's say the input is: ``` Press Ctrl+D to stop \n\n Enter text: this is a test ^Z ``` My question is the end of file character (ASCII value 26) will be written to the file or not ?
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 at compile time that I specify exactly N elements in the initialization of an N-element array (it's an array of function pointers). Can I have the compiler warn me if I specified too few elements?
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 makes error void sccb_write_reg(uint16_t reg, uint8_t *data) { ... ... } ``` Would you please let me know how to solve this problem?
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's a memory address.
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]; arr[3] = aux; } d = atof(arr); printf("%.2f\n", d); } ``` Output: ``` 49352.56 ```
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 fd[2]; pipe(fd); ``` and a few pids ``` pid_t ID1, ID2, ID3; ``` how could I use dprintf() to write those pids to the pipe?
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 sorting an array of size n. While stack based method required only log n space. All theoretical time complexity of both of them is same.
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 particular implementation doesn't matter.
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. Question: How can I trim down a string in C? ////EDIT//// I also tried this: ``` memcpy(contentSave2, &contentSave2[6], 10); ``` Doesn't work, same problem.
``` 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 sure if I missed something when downloading gcc or something. I am on Yosemite if it's of any importance and have the 5.1.0 version of gcc.
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 written before that, even if that code used its own identifier named "dprintf". (Defining _GNU_SOURCE or _XOPEN_SOURCE would also work on Linux, but _POSIX_C_SOURCE is the best choice for general portability.)
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 fd[2]; pipe(fd); ``` and a few pids ``` pid_t ID1, ID2, ID3; ``` how could I use dprintf() to write those pids to the pipe?
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 sorting an array of size n. While stack based method required only log n space. All theoretical time complexity of both of them is same.
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 particular implementation doesn't matter.
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. Question: How can I trim down a string in C? ////EDIT//// I also tried this: ``` memcpy(contentSave2, &contentSave2[6], 10); ``` Doesn't work, same problem.
``` 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 first/. and then use backreference to print it. ``` echo $x |sed -r 's/^.*:( .*?)\/.*$/\1/' 2620:cb:0:b007::23c3 ``` Or bash variable expansion: ``` echo ${x} "inet6 addr: 2620:cb:0:b007::23c3/112 Scope:Global", x="echo ${x%%/*}" echo ${x##*addr: } 2620:cb:0:b007::23c3 ```
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 before so do not know the correct commands to do so. Is there a better way to go about this? Or if this way is valid what commands would i use to send the file via FTP.
``` ftp -u ftp://user:[email protected]/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 do that? For example, this should be controlled by: qmake ./ DEFINES+="USE_LIB_CRYPTO" So I need to somehow check isdefinepassed to qmake and link to the library I need.
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; const int analogInPin_4 = A4; const int analogInPin_5 = A5; const int analogInPin_6 = A6; const int analogInPin_7 = A7; const int analogInPin_8 = A8; ``` Every analogInPin I try to define after A8 (including it) does not work for some reason. It always gives me an error saying: 'A8 was not declared in this scope'. What is the problem?
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 fromuser10. I am getting below error: HTTP-Internal application errorThe formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'ClearCurrentUserFormApplication'. The input source is not correctly formatted.All the users are existed in that application. Is it because of the change in length of the parameter?
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 use C language as default for new projects. You must manually edit the projectCMakeLists.txtfile. With recent versions of CLion you can now create C projects as well, making this answer somewhat obsolete.
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] directly because that results in a bad access error. What is the most efficient way of replacing the beginning "A" in a0 with the value in t0?
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-hand side) to the type of the left hand side, but that's not what you're trying in the last line. I think this would work, and sort of be close: ``` data d2 = { .i = 20 }; ``` This uses C99 syntax to name the target member inside the initializer list.
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, runbashexplicitly: ``` popen("/bin/bash -c 'type -t type'", "r") ``` Live demo.
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 it will be "filled" withtrueorfalsevalue. If it is other kind of variable (for example an integer) it will be "filled" with 0 forfalseand withsomething different than 0for true (but we can't be sure what exactly).
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, chapter §6.5.8/p6,Relational operators Each of the operators<(less than),>(greater than),<=(less than or equal to), and>=(greater than or equal to) shall yield1if the specified relation istrueand0if it isfalse.107)The result has typeint.
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, chapter §6.5.8/p6,Relational operators Each of the operators<(less than),>(greater than),<=(less than or equal to), and>=(greater than or equal to) shall yield1if the specified relation istrueand0if it isfalse.107)The result has typeint.
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 you where the buffer ends as you can with C-strings, you need to know the size of the buffers in advance. Then it's as simple as bit-blitting the two into a single buffer: ``` char dest[16]; memcpy(dest, s, 5); // Copy s to the final buffer memcpy(dest + 5, m, 11); // Copy m to the final buffer just after s ```
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; printf("%4.0f", shipt); return 0; } ```
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; int shipt = (fcost / 120); shipt *=120; printf("%d", shipt); ```
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 clear. Thanks!
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 that would allow me to turn a Scheme function into a C function pointer?
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 systems use some form of copy-on-write optimisation, meaning that the processes will actually share physical memory until either of them writes the memory. This tends to make fork() a quite cheap operation. There are corner cases, as noted by Vazquez-Abrams. Perhaps the most important one is that only one thread is forked, the one that invokes the fork() system call.
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 Bytes of data. If I place the hex function in the same file as dump function it contains all of data. dec variable is local variable and not used anywhere else. Does anybody know why this is happening? If I put the hex function in file1.c, it gives the correct output. So the logic in the hex function is working.
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 in theCFRetain/CFReleasefunctions, which are very well describedhere. Basically ifCis all you want, thenCoreFoundationis a good start, as it has support for many of theCocoa/CocoaTouchtypes.
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 previous error, is it OK to use a one-cycles loop for this? Simply for being able to exit the block with a break? Like this: ``` do { //..code if (error1) break; //..code if (errorN) break; //do finally something when no errors before } while (false); ```
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, const void *pb) { const t_data *a = pa, *b = pb; if (a->key > b->key) return +1; if (a->key < b->key) return -1; return 0; } int main(void) { void *root = NULL; t_data *data; ... while (root != NULL) { data = *(t_data **)root; tdelete(data, &root, comp); free(data); } ... ```
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 variable 'var' with a message "The value of var is %d", var I tried this ``` printStr( ("The value of var is %d", var) ); ``` but it didn't work. Is there a way to accomplish this without passing the variable as argument toprintStr()? The output in this case should be The value of var is 10
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 ther[j]=s[i]assignment, output stops at it! ``` 0:c ``` Why the assignment stops the loop here?
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 works as intented. Here is example code: ``` #include <stdio.h> enum Month { JAN, FEB, MAR }; int main() { enum Month m1 = JAN; printf("%d\n", m1); } ``` By running thesplintcommand, you will obtain following messages: ``` main.c:3:19: Enum member FEB not used A member of an enum type is never used. (Use -enummemuse to inhibit warning) main.c:3:24: Enum member MAR not used ```
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 a basic question, but I'm having difficulty understanding this. Can someone please explain this to me?
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,...,9,A,B,C,D,E,F, so0x8 + 0x8 = 10.
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[] = { "Zara Ali", "Hina Ali", "Nuha Ali", "Sara Ali", }; int i = 0; for ( i = 0; i < MAX; i++) { printf("Value of names[%d] = %s\n", i, names[i] ); } return 0; } ```
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 more quickly without cleaning too much things (calls to functions registered withat_quick_exit).
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 with type 'GdkRGBA', the value has already been initialized as 'GObject' I tried many of the otherG_TYPE_*, but I get a similar error. How can I initialize aGValuewith a typeGdkRGBA?
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) alternative: ``` GdkRGBA color; gtk_style_context_get_color(style_context, GTK_STATE_FLAG_NORMAL, &color); ```
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 what I got wrong ..can you please help me? the link of the problemhttps://www.urionlinejudge.com.br/judge/en/problems/view/1759
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 <stdio.h> int main() { int i,j; scanf("%d", &i); for (j=1;j<=i;j++,printf("Ho%s",(j>i)?"!":" ")); return 0; } ```
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=(money % 1000000007)+(((2*pow(abs(a[i]-a[j]),k))%1000000007))) % 1000000007); ^ I did not understand what the error meant in this case because i did not use double.Could i get a brief explanation ?
% 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 more quickly without cleaning too much things (calls to functions registered withat_quick_exit).
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 with type 'GdkRGBA', the value has already been initialized as 'GObject' I tried many of the otherG_TYPE_*, but I get a similar error. How can I initialize aGValuewith a typeGdkRGBA?
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) alternative: ``` GdkRGBA color; gtk_style_context_get_color(style_context, GTK_STATE_FLAG_NORMAL, &color); ```
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 what I got wrong ..can you please help me? the link of the problemhttps://www.urionlinejudge.com.br/judge/en/problems/view/1759
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 <stdio.h> int main() { int i,j; scanf("%d", &i); for (j=1;j<=i;j++,printf("Ho%s",(j>i)?"!":" ")); return 0; } ```
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=(money % 1000000007)+(((2*pow(abs(a[i]-a[j]),k))%1000000007))) % 1000000007); ^ I did not understand what the error meant in this case because i did not use double.Could i get a brief explanation ?
% 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: ``` gcc tdll.c -shared -o a.dll ``` Then run python code in Python for Windows 3.5.2, python hangs onhello()with 100% cpu usage.Then I've tried running the python code in Python for MinGW 3.4.3(installed from msys2 repo), it's no problem. So What's wrong with my code? How can I workaround it?
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 are trying to include must be from another source. If there is a file calledstack.hin your project, then you need to use ``` #include "stack.h" ``` Beyond these two cases, we can't help you -stack.hsounds very much specific to your project/setup. If you know what directory it is in, you can try adding that directory as an include path to your IDE.
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 : ``` ptr->ptrxx->info; ``` But i have to do some kind of typecasting to let C know thatptr->ptrxxis a pointer to struct b. How can i do this in one expression (without the need of an extra pointer) ? PS:I'm gettingerror: request for member ***** in something not a structure or union.(gcc).
``` ((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; } ``` Of course you'll need to make sureoutputis large enough to hold the result (including the null terminator) and you'll need to decide what to do ifstrandstr2aren't the same length.
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 writing to fb) which means 6fps without any 3d rendering. Is there a way to write faster to a file like the /dev/fb0 on C? I'm currently usingfb = freopen("/dev/fb0","w",stdout);to open the file and the regularprintfto write to the file, also the display is 320x240. Thanks :)
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 for me?
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(command)]; ``` Sobufferwill point to the string terminator incommand, which is just the right place if you want to concatenate something to thecommandstring.
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_size; int result = deflate(&zs, Z_FINISH); deflateEnd(&zs); return result == Z_STREAM_END ? true : false; ``` Using valgrind I see deflateInit and memset are not entirely "free" operations, but takes considerable time. My question is, can I reusez_streamanddeflateInit?e.g. can I deflate more than once by just updating the buffers?
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 arr2[] = {'H','e','l','l','o',' ','W','o','r','l','d'}; n1 = sizeof(arr1)/sizeof(arr1[0]); n2 = sizeof(arr2)/sizeof(arr2[0]); printf("n1 = %d\nn2 = %d\n", n1, n2); return 0; } ```
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 add this path to environment variables. How can I solve this problem without adding this path to environment variables, because I'm planning to run this command from Python script.
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 and plugin.c files. I went through all of them but was not able to understand how to proceed. This is needed for both http and https request/response.
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_set_logging_outbound(ctx, stdout); ... ``` Then compile your code together withgsoap/plugin/logging.c.
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 longer eligible for expansion, so the text remainsstderr.
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 arr2[] = {'H','e','l','l','o',' ','W','o','r','l','d'}; n1 = sizeof(arr1)/sizeof(arr1[0]); n2 = sizeof(arr2)/sizeof(arr2[0]); printf("n1 = %d\nn2 = %d\n", n1, n2); return 0; } ```
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 add this path to environment variables. How can I solve this problem without adding this path to environment variables, because I'm planning to run this command from Python script.
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 and plugin.c files. I went through all of them but was not able to understand how to proceed. This is needed for both http and https request/response.
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_set_logging_outbound(ctx, stdout); ... ``` Then compile your code together withgsoap/plugin/logging.c.
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 longer eligible for expansion, so the text remainsstderr.
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). Does this have to do with the format of the file I am printing to or the emulation of the terminal? Also, on an unrelated question I am trying to find out how to read arrow key inputs fromgetch().
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 use the Emscripten JavaScript functionwriteArrayToMemoryto copy your JavaScript array into themalloced memory. Something like this... ``` char *a = malloc(4); EM_ASM_INT({ var v1 = new Uint8Array([2,4,6,8]); writeArrayToMemory(v1, $0) }, a); printf("the array is [%d, %d, %d, %d]\n", a[0], a[1], a[2], a[3]); ```
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 tried doing it this way in C: ``` printf("Hello the number %d", number, " is correct!"); ``` but the "is correct!" doesn't show up. is there a way to do this in one statement? I'm sorry I'm very new to C.
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(arr1); return 0; } ``` Output ``` 8 16 ``` Why?
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 result.
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.