question
stringlengths
25
894
answer
stringlengths
4
863
I downloaded atom a couple of days ago and I can't seem to find the right package or where and how you compile the program. does anyone know?
Now, it's possible to run and compile (also debug)CandC++program from within atom editor. Installgpp compilerpackage in atom editor. Prerequisites:Windows:You'll need to installMinGWand add it to yoursystem PATH. Mac:You'll need to installXCode. Linux:The GNU Compiler Collection may come with your distribution. Runwhich gcc g++to find out. To compile and run:F5To debug:F6
this is my 1st question here! On this site:Is there a kdevelop version that i can install on windows?at one of the answers it is required to "Run emerge qt, emerge kdelibs, emerge kde-baseapps, emerge kdevelop and emerge kdevelop-pg-qt". However, when i make this it tells in the cmd.exe: "The command 'emerge' is either misspelled or could not be found." How can I fix this problem?
So,emergeactually installable on Windows if you follow the guide on thehttps://community.kde.org/Guidelines_and_HOWTOs/Build_from_source/Windows#Installing_Emerge For info: emergeis a command of a Portage package manager (program to install software in the OS). Portage is an official package manager of the Gentoo Linux OS. Other examples: Ubuntu and Debian Linux use Apt package manager, Fedora Linux uses fpm, ArchLinux uses pacman, etc...
I downloaded atom a couple of days ago and I can't seem to find the right package or where and how you compile the program. does anyone know?
Now, it's possible to run and compile (also debug)CandC++program from within atom editor. Installgpp compilerpackage in atom editor. Prerequisites:Windows:You'll need to installMinGWand add it to yoursystem PATH. Mac:You'll need to installXCode. Linux:The GNU Compiler Collection may come with your distribution. Runwhich gcc g++to find out. To compile and run:F5To debug:F6
this is my 1st question here! On this site:Is there a kdevelop version that i can install on windows?at one of the answers it is required to "Run emerge qt, emerge kdelibs, emerge kde-baseapps, emerge kdevelop and emerge kdevelop-pg-qt". However, when i make this it tells in the cmd.exe: "The command 'emerge' is either misspelled or could not be found." How can I fix this problem?
So,emergeactually installable on Windows if you follow the guide on thehttps://community.kde.org/Guidelines_and_HOWTOs/Build_from_source/Windows#Installing_Emerge For info: emergeis a command of a Portage package manager (program to install software in the OS). Portage is an official package manager of the Gentoo Linux OS. Other examples: Ubuntu and Debian Linux use Apt package manager, Fedora Linux uses fpm, ArchLinux uses pacman, etc...
As for System V messageint msgget(key_t key, int msgflg);, Can syscallreadwork likemsgsndto send a message?Can syscallwritework likemsgrcvto receive a message?
No, they can't. The message queue identifier (returned bymsgget) is not a descriptor. Different sub-systems, different identifiers.
I'm a programming beginner. Please tell me that how can I concatenate two strings or more strings in [codeblocks][1]. Those strings are inputs which can be given by user. ``` #include<stdio.h> int main() { char a,b; printf("Enter your first name:-"); scanf("%s",&a); printf("Enter your middle name:-"); scanf("%s",&b); printf("%s",a+b); } ```
You are using char(i.e. char a,b;) which can hold on only one single character(e.g. 'a' or 'x' or 'm') but you want to store a name which is usually a collection of few characters. In C and other programming languages we usestringto do that. Specifically in C we have to usechar array. If you do not know about arrays yet, learn that first.
can any one tell me where can I find the header for__sync_add_and_fetchbuilt in functionwith out header how could we able to compile the code .
It is a built-in function, meaning the compiler KNOWS this function, and it doesn't have (to have) a header file. In clang, it is part of Builtins.def here:https://github.com/llvm-mirror/clang/blob/master/include/clang/Basic/Builtins.def#L524 and codegen here:https://github.com/llvm-mirror/clang/blob/master/lib/CodeGen/CGBuiltin.cpp#L1204 Other compilers will have some similar concepts in declaring "builtin functions". Of course, not all compilers support atomic builtins, so if you are seeing an error saying "__sync_add_and_fetch is not a function", it may be because the compiler doesn't have that function - it may be called something else in that compiler, or it may simply not exist, depending on what compiler it is.
I want to get the exe path of a process. I can do this fine but for elevated processes I am unable to callOpenProcess()(error is 'Access Denied'). Is it possible to determine the exe path of any process without needing elevated privileges? Maybe I don't need to open/access to the process to determine this? The followingOpenProcessfails for elevated processes: ``` HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); ... QueryFullProcessImageName(hProcess, 0, exePath, &len) ```
RemovePROCESS_VM_READaccess specificator, since it is not needed for theQueryFullProcessImageNamefunction. The documentation describes the required process handle access rights as follows: A handle to the process. This handle must be created with the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right.
My very simple tested program ``` #include<stdio.h> #include<stdlib.h> int main() { int a = 12345; printf("%d\n", a); system("PAUSE"); return 0; } ``` After compiled and connected,the EXE file is created.Then I open the EXE file in the Ollydbg: The picture shows the main() function.But I can't find out what the address of the variableais. When passing the params to theprintf()function,it push3039into the stack, then it means the value of the variableais3039? No,the value is12345. So it means the address of the variableais00003039? Anyone
Address of theavariable is[ebp-8]. You are seeing0x3039assignment, because decimal12345is hexadecimal0x3039. If you change your code to use hex value:int a = 0x12345, results would be more clear: Numeric constants are usually compiled directly into the code.
I have this array: ``` float (*probability)[4]; ``` This is 2D array but i don't know the number of first [], this can be calculate in some function after and in that function I don't know how tomalloc()this array. My code is like this: ``` int main(int argc, char ** argv){ float (*probability)[4]; some_function_to_malloc(&probability); return 0; } ```
Firstly,float (*probability)[4]is not a 2D array. It is a pointer to a 1D array containing fourfloat. They are different things. Second, an idiom to usemalloc()without introducing unintended type errors is ``` probability = malloc(sizeof (*probability) * number_desired); ``` Doing that in a function with a passed argument will be ``` void some_function_to_malloc(float (**probability)[4]) { *probability = malloc(sizeof(**probability) * number_desired); } ``` Don't forget to#include <stdlib.h>in order to usemalloc().
I'm new to pointers... While assigning values to an array using pointer we use: ``` int *arr; arr = malloc(10*sizeof(int)); for(i=0;i<10;i++) { scanf("%d",(arr + i)); } ``` But while assigning to a variable we use ``` int *arr = malloc(sizeof(int)); *arr = 10; ``` So why cant we use, ``` scanf("%d",*(arr + i)); ``` Why is it showing error?
In ``` scanf("%d",(arr + i)); ``` (arr + i)already is apointerto the i-th element of the arrayarr. Had youscanfed into a "single" variable, you would have had to pass its address (=pointer to that variable). ``` scanf("%d", &some_int_variable); ``` Why is it showing error? Dereferencing: ``` scanf("%d",*(arr + i)); ``` would be wrong, because it wouldn't pass the pointer to the i-th array member to read to, sincescanf()requiresapointerto the argument specified by theformat tag, not avalue.
Suppose there are 2 c program named abc.c and xyz.c . Now we want to work with the 2 executables at a time. So we change the name of the ./a.out using ``` gcc -g abc.c -o abc gcc -g xyz.c -o xyz ``` Evengcc -o abc abc.cworks. What does the-gand-oin the above commands specify or describe? What is the significance of-gand-oin the command for renaming ./a.out file. Thanks in advance.
-gmeans to leave debugging information in the output file, it's unrelated to renaming. -omeans to put the result in the specified file instead of the default filename (abc.ofor object files,a.outfor linked executable files).
With child windows the parent first receivesWM_DESTROYthen the child windows. With owned windows it's the opposite. The owned windows first receiveWM_DESTROYthen the owner. If I want to modify something that will affect the child windows, I can do it inWM_DESTROYof parent window, but I can't do the same with owned windows. Owned windows will receiveWM_DESTROYbefore the owner does.
Theofficial documentation forDestroyWindow()says otherwise: If the specified window is a parent or owner window,DestroyWindowautomatically destroys the associated child or owned windows when it destroys the parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window. Are you sendingWM_DESTROYby hand instead of callingDestroyWindow()?
If I only want the user to enter one char, how would I go about doing that in the c language. My attempt at this is below but it failed horribly. From what i read online I heard you could use the function gets or fgets to accomplish this, but I could not figure out how. ``` do { geussNumber += 1; printf("Enter guess number %d\n", geussNumber); scanf(" %c", &geussLetter); scanf ("%c", &inputViolation); if (isalpha(geussLetter) == 0) { printf("You did not enter a letter\n"); } else if (inputViolation == true) { printf("You eneterd more than one letter\n"); } else { inputLoopEnd = 1; } } while( inputLoopEnd == false ); ```
You could use thegetcfamily of functions. Have a look athttp://quiz.geeksforgeeks.org/difference-getchar-getch-getc-getche/for example.
I've come across some code that I'd assumed was broken, but works due to something that I can't understand, or find explanation to. I'd be very grateful if someone could put me straight. It is demonstrated in the following snippet: ``` #include <stdio.h> typedef char char_block[16]; void f(char_block *b) { printf("block 0x%p - b\n", b); printf("block 0x%p - *b\n", *b); } main() { char_block b = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 }; f(&b); } ``` Compiled using g+ and executed, this prints: ``` block 0x0x7fff4794b4e0 - b block 0x0x7fff4794b4e0 - *b ``` I had naively assumed that A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’ Would mean that the function would be equivilent to ``` void f(char ** b) ``` But something else is going on here?
char_block *ischar (*)[16].
I'm making a HashMap in C but am having trouble detecting when a Node has been initialized or not. Excerpts from my code below: ``` static struct Node { void *key, *value; struct Node *next; }; struct Node **table; int capacity = 4; table = malloc(capacity * sizeof(struct Node)); // At this point I should have a pointer to an empty Node array of size 4. if (table[0] != NULL) { // This passes } ``` I don't see what I can do here. I've read tons of other posts of this nature and none of their solutions make any sense to me.
mallocdoes not initialize the memory allocated. You can usecallocto zero-initialize the memory. ``` // Not sizeof(struct Node) // table = calloc(capacity, sizeof(struct Node)); table = calloc(capacity, sizeof(*table)); ``` After that, it will make sense to use: ``` if (table[0] != NULL) { ... } ```
``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]){ int i=0; for (i=1; i<argc;i++){ ``` Counting string length. ``` int l = strlen(argv[i]); int a=1; int start = 0; int end = l-1; ``` I think i have problem in looping. ``` for (a=start;a>=end;a--) printf ("%c",argv[a][i]); printf("\n"); } return 0; } ```
I think you want this: ``` for (a=end;a>=start;a--) printf ("%c",argv[i][a]); ``` Your code hadstartandendswapped and alsoaandi.
I am having problems with fscanf getting stuck in an infinite loop. { ``` char num; FILE *filePtr; if ((filePtr = fopen("filename.txt", "r")) == NULL) { printf("File could not be opened"); } else { while (fscanf(filePtr, "%20[^ ,]", &num) != EOF) { displayFun(num); } } return 0; ``` The file input that I need it to read is: 0, 1, 2, 3, 16, 17, 1234, 5678, -201, 65534, 65535, 65536, -1 For some reason the code gets stuck in a loop and the first zero and wont continue on to the other numbers.
"%20[^ ,]"never consumes a,or space. They stay infilePtrfor the nextfscanf()call. Code needs to somehow read the,and space. As@melpomenecommented, reading text as a string into acharwill not work, Recommend to read anintand,instead. ``` int number; while (fscanf(filePtr, "%d,", &number) == 1) { displayFun(num); } ```
I'm making a HashMap in C but am having trouble detecting when a Node has been initialized or not. Excerpts from my code below: ``` static struct Node { void *key, *value; struct Node *next; }; struct Node **table; int capacity = 4; table = malloc(capacity * sizeof(struct Node)); // At this point I should have a pointer to an empty Node array of size 4. if (table[0] != NULL) { // This passes } ``` I don't see what I can do here. I've read tons of other posts of this nature and none of their solutions make any sense to me.
mallocdoes not initialize the memory allocated. You can usecallocto zero-initialize the memory. ``` // Not sizeof(struct Node) // table = calloc(capacity, sizeof(struct Node)); table = calloc(capacity, sizeof(*table)); ``` After that, it will make sense to use: ``` if (table[0] != NULL) { ... } ```
``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]){ int i=0; for (i=1; i<argc;i++){ ``` Counting string length. ``` int l = strlen(argv[i]); int a=1; int start = 0; int end = l-1; ``` I think i have problem in looping. ``` for (a=start;a>=end;a--) printf ("%c",argv[a][i]); printf("\n"); } return 0; } ```
I think you want this: ``` for (a=end;a>=start;a--) printf ("%c",argv[i][a]); ``` Your code hadstartandendswapped and alsoaandi.
I am having problems with fscanf getting stuck in an infinite loop. { ``` char num; FILE *filePtr; if ((filePtr = fopen("filename.txt", "r")) == NULL) { printf("File could not be opened"); } else { while (fscanf(filePtr, "%20[^ ,]", &num) != EOF) { displayFun(num); } } return 0; ``` The file input that I need it to read is: 0, 1, 2, 3, 16, 17, 1234, 5678, -201, 65534, 65535, 65536, -1 For some reason the code gets stuck in a loop and the first zero and wont continue on to the other numbers.
"%20[^ ,]"never consumes a,or space. They stay infilePtrfor the nextfscanf()call. Code needs to somehow read the,and space. As@melpomenecommented, reading text as a string into acharwill not work, Recommend to read anintand,instead. ``` int number; while (fscanf(filePtr, "%d,", &number) == 1) { displayFun(num); } ```
This program does not terminate nor does it let me input any values, simply a black screen with no output. ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { int size; printf("Enter number of elements in array:"); scanf("%d", &size); printf("\n%d\n", size); return 0; } ```
Sounds like you're suffering from buffering. Add ``` fflush(stdout); ``` after theprintfline. By default, if stdout goes to a terminal, it is line buffered, meaning output is only actually written when the buffer is full or when you output a newline (\n). Terminating the program (viaexit()or returning frommain) closes all open file handles and also forces a flush. To make sure output is generated right then and there, callfflush.
In my program, there would be a chance edit box, which changes the "drop rate" or "win rate" But I would like to change it in such a way that if the user inputs a number higher than 100 and clicks out of the edit box, it the edit box text would change back into 100. I have no idea how to implement this.
Have a look at the followingtutorial You will have to use WM_COMMAND in your callback function to catch the messages/notifications that your edit box sends (for instance EN_CHANGE). Then you can check the value inside the callback and revert to 100 if it's too high. For further reference all edit control notifications are listed onMSDN.
In my program, there would be a chance edit box, which changes the "drop rate" or "win rate" But I would like to change it in such a way that if the user inputs a number higher than 100 and clicks out of the edit box, it the edit box text would change back into 100. I have no idea how to implement this.
Have a look at the followingtutorial You will have to use WM_COMMAND in your callback function to catch the messages/notifications that your edit box sends (for instance EN_CHANGE). Then you can check the value inside the callback and revert to 100 if it's too high. For further reference all edit control notifications are listed onMSDN.
if a switch case is given as ``` typedef unsigned char uint8_t; const uint8_t mask = 0x01; const uint8_t Buffer[]; switch (Buffer[4] & mask) { case 0x01U: --- if else case 0x00U: ------ if else default: } ``` I am doing unit testing in order to get 100% coverage and also test one ureq I need to enter default case but I am not able to understand what switch(Buffer[2] & mask)means i.e what exactly the(Buffer[2] & mask)describe and&is used for what and how can I enter the default case?
Becausemaskis 1,Buffer[4] & maskwill be1ifBuffer[4]is an odd number, and0if it's even. Itcannotbe anything else. So the case label2is never used. &is the bitwise AND operator.
I wrote this piece of code ``` int main() { char a[] = "ABCD"; const char* b = a; a[1] = 'E'; printf("%s %s", a, b); getchar(); } ``` The code compiled and ran successfully. How am I able to access the memory pointed by 'const char* b' and modify it ? Does it mean that for a shared memory const definition does not matter ? Thank you
const char* bmeans that you cannot modify the thingbpoints tothroughb. But you can modify it through some other means, provided the thing isn'tconstin the first place*. Here is a simplified example: ``` int a = 0; const int* p = &a; a = 42; // OK! a is not const. *p = 43; // ERROR! Cannot modify a through p. const int b = 0; p = &b; b = 43; // ERROR! b is const. ``` * This holds for C++. The details may be slightly different in C
I wrote a simple c program to simulate a memory leak. But it crashes when i try to run it. ``` #include <stdio.h> #include <stdlib.h> void memory_leak(void); int main() { memory_leak(); return EXIT_SUCCESS; } void memory_leak() { int i = 100; memory_leak(); } ``` I use MinGW gcc compiler.
You are producing a stack overflow - by calling your functionmemory leakrecursively. Your version ofmemory_leakallocates a local ("stack") variable that will be released/destroyed/deallocated when the function exits. To actually create a memory leak, you need to allocate memory from the heap (e.g. usingnewormalloc). ``` void* memory_leak() { return malloc(10); } ``` [Don't unconditionally callmemory_leakwithinmemory_leak.]
I am using code blocks with GCC compiler. In the code below, compiler gives warning while returning local reference but no warning on returning local pointer though both are same thing. Why ? I understand these variables are local and will be destroyed as soon as control returns from the function. De-referencing these would result in undefined behavior. ``` int *check(int j) { int *q; q= &j; return q; // No warning //return &j; // Warning } ```
First, because warnings are optional. Second, this code ``` int *q ... return q; ``` doesn't return a the address of a local variable directly. You wrote the explicit code that made the pointer point to an address that becomes invalid when the function returns. No compiler can be expected to save you from that.
I wrote this piece of code ``` int main() { char a[] = "ABCD"; const char* b = a; a[1] = 'E'; printf("%s %s", a, b); getchar(); } ``` The code compiled and ran successfully. How am I able to access the memory pointed by 'const char* b' and modify it ? Does it mean that for a shared memory const definition does not matter ? Thank you
const char* bmeans that you cannot modify the thingbpoints tothroughb. But you can modify it through some other means, provided the thing isn'tconstin the first place*. Here is a simplified example: ``` int a = 0; const int* p = &a; a = 42; // OK! a is not const. *p = 43; // ERROR! Cannot modify a through p. const int b = 0; p = &b; b = 43; // ERROR! b is const. ``` * This holds for C++. The details may be slightly different in C
I am absolutely new to Perl XS. My simple testfunction gets a string and appends something. In Perl is is a scalar-string in and one out. In the function I have a malloc. Whats the correct way to free the mem? ``` SV *foo (str) SV *str CODE: unsigned char *strbuf; size_t strlen; strbuf = (unsigned char *) SvPV (str, strlen); int n = strlen + 10; unsigned char *buf = malloc (n); strncpy (buf, strbuf, strlen); strncat (buf, "0123456789", 10); RETVAL = newSVpv (buf, n); OUTPUT: RETVAL ``` thanks! Chris
newSVpvcreates an internal copy of the string, so you can simply free the memory by callingfreeafter assigning toRETVAL.
I am new to C. I saw this line in a program: ``` grid = calloc(nx,sizeof(int**)); ``` I read thatint**means a pointer to a pointer, but what is meant bysizeof(int**)??
Thesizeofoperator yields the number of bytes of storage required by its operand. The operand is either an expression or a type enclosed in parentheses. In this case, the operand is the typeint **, which is "pointer to pointer toint". Assuminggridhas been declared as ``` int ***grid; ``` then that can be rewritten as ``` grid = calloc(nx, sizeof *grid); ```
I am receiving bytes through::recv()and have a scenario where it returns zero. According to here: http://www.tutorialspoint.com/unix_system_calls/recv.htm this means: The return value will be 0 when the peer has performed an orderly shutdown. Is there any way to find out which side of the connection closed it? I do not know whether the remote client killed our connection, or some logic on our side closed it.
Is there any way to find out which side of the connection closed it? The peer closed it. The other side. I do not know whether the remote client killed our connection, or some logic on our side closed it. Yes you do. The peer closed it. If you had closed it you would get an errorEBADF.
To switch hdf5-support on, I currently have in the preprocessor ``` #define HDF5 #ifdef HDF5 #include "hdf5.h" #endif ``` This means, I have to manually active the#define HDF5line (like in the code-snippet given above) or de-activate it (by deleting it or putting comment characters in-front of it). Is there something better like#ifdef _HDF5to check for my compiler options (using gcc) ? For openmp, for example, I have ``` #ifdef _OPENMP #include <omp.h> #endif ``` which means that theomp.hfile is only included, when an appropriate compiler flag was set. I was hoping for something similar for hdf5 but could find nothing so far.
GCC has a-Doption to make processor macros outside of the code. ``` gcc -DHDF5 source.c ``` will make#ifdef HDF5true.
This question already has answers here:if statment and garbage value in C [duplicate](3 answers)Closed7 years ago. The following code printsAA: ``` #include <stdio.h> int main() { for(int i;i;i--) printf("A"); return 0; } ``` Why the initial value of variableiis2, and not some garbage value? Is the lifetime of variableistatic or automatic?
Apparently the variableiis not initialized. This means that the behavior of the implementation is undefined. And value ofiis garbage value only. Here it is2.
I have some operation like this C++ code that I want to convert in C89: return reinterpret_cast<uint8_t *>(stream.buffer) - buffer; How can I replace the reinterpret cast in C?
Nothing very exciting, you've seen this before: ``` (uint8_t *)(stream.buffer) ``` That's the only way to cast something in C.
I have 2 4-bit numbers (X0X1X2X3 and Y0Y1Y2Y3) and I want to combine them so that I would create an 8-bit number like that: ``` X0X1X2X3 Y0Y1Y2Y3 => X0Y0X1Y1X2Y2X3Y3 ``` I know how to concatenate them in order to create theX0X1X1X3Y0Y1Y2Y3but I am stuck on how to compose them in the pattern explained above. Any hints?
Here's a fairly direct way of performing this transformation: ``` uint8_t result; result |= (x & 8) << 4; result |= (y & 8) << 3; result |= (x & 4) << 3; result |= (y & 4) << 2; result |= (x & 2) << 2; result |= (y & 2) << 1; result |= (x & 1) << 1; result |= (y & 1) << 0; ```
The concept of using select after a non blocking connect is unclear to me. If the socket is nonblocking the connect would return with EINPROGRESS what is the reason behind using select after connect in this case. If select return when the socket is ready, don't we need another call to connect to make that work ?what-are-possible-reason-for-socket-error-einprogress-in-solaris
Back in the early 1990s you were indeed supposed to issue a secondconnect()after the socket showed up as writable inselect(). At some point this morphed without trace into checkingSO_ERRORinstead.
I got "Segmentation fault (core dumped)" and process was interrupted. Help to fix it please! suspicious part code here ... ``` FILE *pFile; char buffer[100]; sprintf(buffer,"/var/www/html/%s.txt",topic); pFile = fopen(buffer,"w" ); ``` This problem may occur in the above (Did not enter if-else) ``` if( NULL == pFile ){ _mosquitto_log_printf(NULL, MOSQ_LOG_DEBUG,"open failure" ); }else{ fwrite(payload,1,sizeof(payload)-1,pFile); _mosquitto_log_printf(NULL, MOSQ_LOG_INFO, "File context : %s", payload); } fclose(pFile); ``` ... OS Ubuntu 14
You callfcloseusingpFileeven when it's a null pointer. Callingfclosewith an invalid pointer (like a null pointer) or aFILE*that has already been closed isundefined. Only callfcloseis the pointer is notNULL, i.e. in theelseclause of your code.
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.Closed7 years ago.Improve this question The C11 standard Annex K defines a bunch of new safer string functions, all suffixed by_s(e.g.strcpy_s). Do you know when these new functions will become available in the GNU C library glibc? So far you have to fall back to a third party library likesafec.
Do you know when these new functions will become available in the GNU C library glibc? When someone contributes an implementation and convinces GLIBC maintainers that these functions are good to have. Relevantthreadfrom 2007.
I have a python class that has a couple performance-sensitive methods that justify being implemented in C. But it also has some methods that don't need to be fast and that would be a giant pain to write in C. Is there a standard way to have the best of both worlds, where a few core methods are defined in C but some convenience methods are defined in python? (Ideally it should work for special methods like__str__.) For example, maybe I could use inheritance. Is that the right way to do it? Are there performance costs?
TryCython. It really does a fantastic job blending the best features of both languages. No longer do you have to decide between control and performance, and efficiency and ease of development.
I guess I could use theTF_NewTensor(..., void* data,...)function (from the The Tensorflow C API) to create a new tensor from shared memory by havingdatapoint to the shared memory. If I pass that tensor totf.Vaiable(), will the Tensorflow variable store its data in, and read it from, the shared memory? If not, is it possible to get a pointer to the variable´s underlying data buffer?
At the moment, TensorFlow needs to own the Tensor buffers, because they are refcounted internally by the system based on their use. We do not have an API to transfer ownership of an existing buffer to a Tensor, though feel free to file a feature request on GitHub for this.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question I'm using codeblocks IDE and I don't know what is the problem. I tried making the variables global but it still doesn't work.
The problem is in the function name.Calculate_areahas a capital 'C' in its function declaration name, but not in the prototype declaration. Change your function declaration at line 31 with: ``` unsigned long calculate_area(unsigned long side); ```
Is there a simple way to XOR all of the bits of a single number together, i.e. a unary XOR in C? Something that has the effect of: ``` result = ^(0x45); // ( 0 ^ 1 ^ 0 ^ 0 ^ 0 ^ 1 ^ 0 ^ 1 = 1) result = ^(0x33); // ( 0 ^ 0 ^ 1 ^ 1 ^ 0 ^ 0 ^ 1 ^ 1 = 0) ```
GCC has a builtin for this: ``` int xor_bits(unsigned x) { return __builtin_parity(x); } ``` Alternatively, you can compute the parity by counting the number of set bits. The gcc builtin for this is__builtin_popcount(): ``` int xor_bits(unsigned x) { return __builtin_popcount(x) & 1; } ``` If you care to stick to only standard C,https://graphics.stanford.edu/~seander/bithacks.htmlandHow to count the number of set bits in a 32-bit integer?have some great solutions for counting the number of set bits.
I would like to know if there is an equivalent in C (for avoidfunction) to this javascript code: ``` var myFunction; myFunction = function(){ //Some code } ```
Not really equivalent (because C is a static language without support for anonymous or nested functions) but you can have a variable that is apointerto a function, and make it point to different compiled functions matching the type of the variable. Very simple and basic example: ``` #include <stdio.h> void function1(void) { printf("function1\n"); } void function2(void) { printf("function2\n"); } int main(void) { // Declare a variable that is a pointer to a function taking no arguments // and returning nothing void (*ptr_to_fun)(void); ptr_to_fun = &function2; ptr_to_fun(); ptr_to_fun = &function1; ptr_to_fun(); return 0; } ``` The above program will print out ``` function2 function1 ```
I have a python class that has a couple performance-sensitive methods that justify being implemented in C. But it also has some methods that don't need to be fast and that would be a giant pain to write in C. Is there a standard way to have the best of both worlds, where a few core methods are defined in C but some convenience methods are defined in python? (Ideally it should work for special methods like__str__.) For example, maybe I could use inheritance. Is that the right way to do it? Are there performance costs?
TryCython. It really does a fantastic job blending the best features of both languages. No longer do you have to decide between control and performance, and efficiency and ease of development.
I guess I could use theTF_NewTensor(..., void* data,...)function (from the The Tensorflow C API) to create a new tensor from shared memory by havingdatapoint to the shared memory. If I pass that tensor totf.Vaiable(), will the Tensorflow variable store its data in, and read it from, the shared memory? If not, is it possible to get a pointer to the variable´s underlying data buffer?
At the moment, TensorFlow needs to own the Tensor buffers, because they are refcounted internally by the system based on their use. We do not have an API to transfer ownership of an existing buffer to a Tensor, though feel free to file a feature request on GitHub for this.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question I'm using codeblocks IDE and I don't know what is the problem. I tried making the variables global but it still doesn't work.
The problem is in the function name.Calculate_areahas a capital 'C' in its function declaration name, but not in the prototype declaration. Change your function declaration at line 31 with: ``` unsigned long calculate_area(unsigned long side); ```
I am a newbie in C. ``` int a = 1, b = 2; int *p = &a; ``` when a threadA is changing the pointerpfrom pointingato pointing tob, at the same time another threadB is reading pointerp, what value could threadB read? Could it be a broken value (neither 1 nor 2)?
In practice, writes to a pointer will be atomic on popular modern platforms,if the pointer storage is aligned.Which it will be in your case, where the pointer is allocated on the stack. If the pointer were stored on the heap, you would need to make sure to store it with the proper alignment. In theory, no, it's not safe.
In platform file there is parameter such ascore: ``` <host id="Jupiter" speed="76.296Mf" core="2"/> ``` But this parameter doesn't affect the time of task executing. How it should be done that time of executing will give different values depending on number of cores in the host?
I think that this parameter allows two tasks to run concurrently on the host. So, one task cannot be multithreaded in SimGrid and you need 2 of them to take advantage of a multi-core host. Note that I'm not completely sure that this area is perfectly bug free...
``` #include <stdio.h> void change(char *str) { (*str++); return; } int main() { char *str = "ABC"; printf("before change %s \n",str); change(str); printf("after change %s \n",str); return 0; } ``` Output of the program is ``` ABC ABC ``` I want output to be ``` ABC BC ``` I don't want to return string, str needs to be modified in change function; return type of change function should remain void. I don't know how to do this. I did try to google it but i didn't find the solution.
In C if you want to change the value of an argument to a function, you need to take that argument by pointer. And since here you are trying to change a pointer, it needs to be a pointer to a pointer: ``` void change(char **str) { (*str)++; } ``` Then: ``` change(&str); ```
In function with variable number of arguments, the "first argument" is "total number of arguments" being passed. But inprintf()we never mention argument count. So how does it get to know about the total argument list ? How doesprintf()works ?
Let's look onprintfdeclaration structure: ``` int printf(const char *format, ...) ``` formatis actually the string that contains the text to be written tostdout. The contained embedded format tags are later replaced by the values specified in subsequent additional arguments, and format is set accordingly as required.
Following function prints garbage on console. Cannot understand the issue. Below is a test code fragment. ``` void format( const char* pcszFormat, ... ) { va_list VarArglist; va_start(VarArglist, pcszFormat); printf(pcszFormat, VarArglist); va_end(VarArglist); } int wmain(int argc, wchar_t *argv[]) { string strTest; const char *pcszFormatted; format("%x %S", 10, "Test"); //printf("\nFormatted string: %s", pcszFormatted); getchar(); return 0; } ```
You invokedundefined behaviorby passing data having wrong type toprintf(). You should usevprintf()to work withva_list. Also don't forget to change%Sto%sin order to work with normal string or change"Test"toL"Test"in order to work with wide string, or you will invokeundefined behaviorby passing data having wrong type toprintf()family again.
Is anyone aware of an equivalent to setsockopt() that works on non-socket based file descriptors? Specifically, consider this block of code: ``` int on = 1; setsockopt(socketfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(int)); ``` All fine and dandy, and now we can avoid SIGPIPE and refer to EPIPE when writing instead. But this only works on socket file descriptors opened with accept(), socket(), etc. I'm trying to gain similar functionality for a file descriptor opened by a pipe() call, which setsockopt() promptly rejects as being a non-socket file descriptor. Is there an equivalent to the above (setsockopt()) for descriptors opened by pipe() or open()?
There is no equivalent, but you could usesocketpairto create a Unix socket instead.
I'm new to C and have spent a good amount of time trying to find this answer to avail so I thought I would turn to the brain trust. I need to print out two values int and hex and there should be no comma in between went sent to the screen. This may be a case of the answer being so obvious that I'm just not looking at it right but here we go. I have the code ``` printf(" %10d, 0x%X\n", answer, answer); ``` and it prints out as ``` 5214, 0x145E ``` but I need it with no comma, just ``` 5214 0x145E ``` Thanks in advance.
It is very simple. Just remove the comma from between. ``` printf(" %10d 0x%X\n", answer, answer); ``` This should do it.
``` int findMax(int*sums){ int t = 0; int max = sums[0]; while (sums[t] != '\0'){ printf("current max: %d %d\n", max, sums[t]); if (sums[t] > max ){ max = sums[t]; } t ++; } return max; } ``` This outputs: ``` current max: 7 7 current max: 7 4 current max: 7 2 ``` And its ignoring the rest of the list,sums. I think this is because the next element insumsis0. But I can't see why it would treat0as'\0'(null).
sumsis an array of integers (technically a pointer to integer).'\0'(the null byte) and 0 are the same value, so your loop will stop when it encounters a 0. There is no such thing as a null value as far as integers are concerned. The term "null" is used to refer to the valueNULL, which is a pointer usually with the value 0 (i.e., a pointer that doesn't point to anything), and also the null (0) byte, such as the one that occurs at the end of a null-terminated string.
I am making a loop and I want each time it enters the loop it will store my variable into a separatearray. Example: loop 1, variable stored ini[1]; loop 2, variable stored ini[2]; and so on. ``` for (i1 = 0; i1 < size; i1++) { printf("%d ", i1); y1[] = i1; } ``` Basically, apart from printing outi1I wanti1to be stored inarrays for later use.
``` int y1[size]; for (i1 = 0; i1 < size; i1++) { printf("%d ", i1); y1[i1] = i1; // indexing } ``` Now it is stored in arrayy1for future use.
I cannot figure out how to take away a letter dependent on user input. For example, if I enterbthe code should outputcdefghijklmno...If I entercthe code should outputdefghijklmno...I just don't know where to do the math? ``` #include <stdio.h> int main(void) { char letter; printf("Type one letter of alphabet and following letters will appear (lowercase): "); scanf_s("%c", &letter); if (letter >= 'a' && letter <= 'z'){ printf("%c, valid entry!\n\n", letter); for (letter = 'a'; letter <= 'z'; ++letter){ printf("%c ", letter); } } else { printf("%c, invalid entry.\n\n", letter); } return 0; } ```
In this line: ``` for (letter = 'a'; letter <= 'z'; ++letter){ ``` why do you start ata? Dont you want to start one after the user input letter, which is stored inletter? So do that: ``` for (++letter; letter <= 'z'; ++letter){ ```
why when we write address for register we add offset to the the base address? Also why do we write the syntax like this below ``` #define CGPIO (*((volatile unsigned long*)0x400FE608)); ``` I mean the pointer part syntax only
The(volatile unsigned long*)0x400FE608syntax casts a hardware-specific address in memory, presumably of a register, to pointer tovolatile unsigned long. The type of the pointer,volatile unsigned long, is based on the size of the register, and the need to treat it as unsigned. The pointer is defined to point tovolatileto ensure that the compiler does not optimize multiple reads and writes, performing an operation each time your code requires it. The asterisk in front and parentheses around the whole expression is so that you can treatCGPIOas if it were an assignable global variable, and write ``` CGPIO = 123; ``` and ``` unsigned long val = CGPIO; ``` without adding an asterisk in front ofCGPIO.
Is it possible to run a c macro function at compile time. for example writing something in a file each time code is compiled.
Yes; No. The macrosdoexecute at compile time but there isn't much you can do directly with them other than mix text into the code. Now, taking thesoftware toolsapproach that unix pioneered (after all) you could conditionally generate output with#warningand then catch this with some script via a pipe. Then that script could do stuff. But, you probably wouldn't want to do that. Once you are running a script you could just have that script do whatever you want. Also,#errorand#warningdon't macro-expand the error or warning text, so using them for I/O is problematic. This is obvious, I suppose, but how about using Ruby, Python, or the shell to script some macro processing?
``` int findMax(int*sums){ int t = 0; int max = sums[0]; while (sums[t] != '\0'){ printf("current max: %d %d\n", max, sums[t]); if (sums[t] > max ){ max = sums[t]; } t ++; } return max; } ``` This outputs: ``` current max: 7 7 current max: 7 4 current max: 7 2 ``` And its ignoring the rest of the list,sums. I think this is because the next element insumsis0. But I can't see why it would treat0as'\0'(null).
sumsis an array of integers (technically a pointer to integer).'\0'(the null byte) and 0 are the same value, so your loop will stop when it encounters a 0. There is no such thing as a null value as far as integers are concerned. The term "null" is used to refer to the valueNULL, which is a pointer usually with the value 0 (i.e., a pointer that doesn't point to anything), and also the null (0) byte, such as the one that occurs at the end of a null-terminated string.
I am making a loop and I want each time it enters the loop it will store my variable into a separatearray. Example: loop 1, variable stored ini[1]; loop 2, variable stored ini[2]; and so on. ``` for (i1 = 0; i1 < size; i1++) { printf("%d ", i1); y1[] = i1; } ``` Basically, apart from printing outi1I wanti1to be stored inarrays for later use.
``` int y1[size]; for (i1 = 0; i1 < size; i1++) { printf("%d ", i1); y1[i1] = i1; // indexing } ``` Now it is stored in arrayy1for future use.
I cannot figure out how to take away a letter dependent on user input. For example, if I enterbthe code should outputcdefghijklmno...If I entercthe code should outputdefghijklmno...I just don't know where to do the math? ``` #include <stdio.h> int main(void) { char letter; printf("Type one letter of alphabet and following letters will appear (lowercase): "); scanf_s("%c", &letter); if (letter >= 'a' && letter <= 'z'){ printf("%c, valid entry!\n\n", letter); for (letter = 'a'; letter <= 'z'; ++letter){ printf("%c ", letter); } } else { printf("%c, invalid entry.\n\n", letter); } return 0; } ```
In this line: ``` for (letter = 'a'; letter <= 'z'; ++letter){ ``` why do you start ata? Dont you want to start one after the user input letter, which is stored inletter? So do that: ``` for (++letter; letter <= 'z'; ++letter){ ```
why when we write address for register we add offset to the the base address? Also why do we write the syntax like this below ``` #define CGPIO (*((volatile unsigned long*)0x400FE608)); ``` I mean the pointer part syntax only
The(volatile unsigned long*)0x400FE608syntax casts a hardware-specific address in memory, presumably of a register, to pointer tovolatile unsigned long. The type of the pointer,volatile unsigned long, is based on the size of the register, and the need to treat it as unsigned. The pointer is defined to point tovolatileto ensure that the compiler does not optimize multiple reads and writes, performing an operation each time your code requires it. The asterisk in front and parentheses around the whole expression is so that you can treatCGPIOas if it were an assignable global variable, and write ``` CGPIO = 123; ``` and ``` unsigned long val = CGPIO; ``` without adding an asterisk in front ofCGPIO.
Is it possible to run a c macro function at compile time. for example writing something in a file each time code is compiled.
Yes; No. The macrosdoexecute at compile time but there isn't much you can do directly with them other than mix text into the code. Now, taking thesoftware toolsapproach that unix pioneered (after all) you could conditionally generate output with#warningand then catch this with some script via a pipe. Then that script could do stuff. But, you probably wouldn't want to do that. Once you are running a script you could just have that script do whatever you want. Also,#errorand#warningdon't macro-expand the error or warning text, so using them for I/O is problematic. This is obvious, I suppose, but how about using Ruby, Python, or the shell to script some macro processing?
Is there a portable way that only relies on what the C99 standard provides to find out the maximum required alignment that is needed for any data type. Likemaxalign_tin C++11. What I'm currently doing is calculating the least common multiple (lcm) of the alignments ofint,long int,long long int,double,void *andsize_tas best effort way of determining the alignment. Update:I currently need this for implementing a wrapper aroundmallocthat stores metadata at the beginning of the block of memory and returns a pointer with a higher address than whatmallochas returned.
There isn't really a good way to do that, which is whymaxalign_twas introduced by C11. Though, I cannot imagine an ordinary system where a type with higher alignment requirements thanintmax_texists so you might as well use that and get the right answer for 99% of the systems whenmaxalign_tis not available.
I've got some c++ code that's requiring me to cast an immediate in an assignment statement. The casting makes the code more difficult to read and I was hoping there was a way around this. ``` uint64_t shifted_val = (uint64_t)1 << 50; ``` If I write this code without the cast,shifted_valgets set to 0, I assume because it's treating the1immediate as a 32-bit value. Is there something I'm missing so that I can write this without casting?
You can do: ``` uint64_t shifted_val = 1ull << 50; ``` If you think the syntax is also close to casting then you can do: ``` uint64_t a = 1; uint64_t shifted_val = a << 50; ```
In C an array likeint a[4]creates 5 locations to store integers includinga[0]toa[4]. But in case of a 2D array likeint a[2][2]is producing only four locations and not 3*3 = 9 locations. What is the reason for this?
Your understanding of 1D array is incorrect.int a[4]reserves location for for4ints and NOT5ints. i.e.int a[4]reserves memory fora[0],a[1],a[2], anda[3]. In case of 2D array, total elements is given bynum of rows * num of columns, so yesa[2][2]contains 4 integers. So it reserves memory for 4 integers.
In glade I can give a unique id to each widget, however in the c-code, I have no idea how I can make use of these id's. The method "gtk_widget_get_name" seems to return something else. At least currently I only get the typenames from it, e.g. "GtkGrid", "GtkComboBoxText", "GtkStatusbar" ... thats probably the default if I did not set a different name in the c-code. So how can I read the id of a gtkwidget, which I typed into glade ?
The Glade ID is used withgtk_builder_get_object()to retrieve an object or widget by its ID from a Glade file. Thenameproperty whichgtk_widget_get_name()retrieves, fulfills a different function: referring to your widget from a CSS file. It's for widgets only, not objects, and moreover there's nothing that forces it to be unique.
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 I'm learning OpenGL and want to create simple program. I want to render different meshes with different shaders. Should I recreate program or I must reuse created program? (program - shader program, created by calling glCreateProgram)
You don'thaveto re-use the linked program(s), it's just usuallymuchfaster than re-compiling/linking them each frame/drawcall.
I am trying to decode some data received from Matlab and I need a struct something like this: ``` struct __attribute__((__packed__)) struct1{ int a; int b; int c; } struct __attribute__((__packed__)) struct2{ int a } struct __attribute__((__packed__)) mystruct{ int struct1.a; int struct1.b; int struct2.a; int struct1.c; } ``` What is the best way to get this packed struct so that I can decode the data from Matlab? I don't think C would let me create mystruct without objects of struct1 and struct2.
The struct you intend on using doesn't have to have other structs defined. Just define the fields you need with the types you need: ``` struct __attribute__((__packed__)) mystruct{ int struct1_a; int struct1_b; int struct2_a; int struct1_c; } ```
I want to be lazy and write some code that will break if the endianness of the target machine is different from my own, for right now. But I would like to know when it breaks of course, so I can fix it if or when it becomes necessary. Is the endianness of floats and integers a property of the compiled program, such that I can check it at compile time with an assertion somehow? Or would it be something I have to assert at runtime?
Yes, endianness is inherent to the machine in question and is known at compile time. Most OSs will have a#defineset up somewhere to tell you what the endianness is. On Linux in particular you can do the following: ``` #if __BYTE_ORDER == __LITTLE_ENDIAN ... #elif __BYTE_ORDER == __BIG_ENDIAN ... #elif __BYTE_ORDER == __PDP_ENDIAN ... #else ... #endif ```
I need to write a macro which needs to inline assembly ``` #define create_me(name) \ __asm\ mov name,#0x1021\ __endasm\ ``` The # however isn't compiling. I have tried passing it in as a parameter however that doesn't work too. It says invalid preprocessor token . I can try to use an inline function but I can't dynamically create the register name. That is I don't have access to the name variable. Does anyone have any suggestions on how to use the # operation inside a macro. I have looked atEscaping a # symbol in a #define macro?, but I have clearly explained why I need the macro here. My usecase is different.
Using an indirection through another macro should do the trick: ``` #define HASH_LIT # #define HASH() HASH_LIT #define create_me(name) \ __asm\ mov name,HASH()0x1021\ __endasm ```
Usinggetchar_unlockedand compiling with--std=c99flag gives warningas follows- warning: implicit declaration of function ‘getchar_unlocked’ [-Wimplicit-function-declaration] Does not give any warning if compiled without flag.Is there any way to work around with it ?
Starting from C99 you must have a visible function prototype before calling a function. While the earlier C standard would just stupidly assume that any function unknown to the compiler has the formatint func (params), which in turn would cause severe bugs most of the time. Properly declare a prototype forgetchar_unlockedand the bug will go away. Note that there is no such function present in any standard library. It seems you might have to include some non-standard library for the compiler to find the function.
I'm a C newbie, and I'm trying to do the pointer/memory thing right... In my case, I'm using strtol and I need to pass a **char to hold one of several return values, but allocating heap space is way overkill. The cleanest correct (I hope) way I can find, of getting space on the stack for this, is: ``` char *_ = NULL; char **endptr = &_; ret = strtol("not a number", endptr, 0); ``` I'm curious, is there a more succinct or idiomatic way to get this effect? I feel dirty naming things I will never use... EDIT: to clarify, I DO intend to use endptr, just not _
strtolacceptsNULLas the second argument. Seehttp://www.cplusplus.com/reference/cstdlib/strtol/ So you can write your code like this: ``` ret = strtol("not a number", NULL, 0); ``` If it didn't accept NULL, you can avoid one line of code like this: ``` char *unused; ret = strtol("not a number", &unused, 0); ```
I'm using CMake to compile this example program: CMakeLists.txt: ``` cmake_minimum_required (VERSION 3.0.0) set(PROJECT_NAME Main) project(${PROJECT_NAME}) add_definitions(-DSTRING=“test”) add_executable(${PROJECT_NAME} main.c) ``` main.c: ``` #include <stdio.h> int main(void) { puts(STRING); } ``` Compiling gives me the following error: error: expected expression puts(STRING); ^ <command line>:1:16: note: expanded from here #define STRING "test" How can I stringify this preprocessor tokenwithout modifyingmain.c?
You are using the characters“and”that are not valid in C: ``` error: expected expression puts(STRING); ^ <command line>:1:16: note: expanded from here #define STRING “test” ^ 1 error generated. ``` You must change“and”for"in your CMakeLists.txt and your program will compile.
I have started C recently and am having trouble make the computer think of a random number. This is the code so far. I need help! ``` #include <stdio.h> #include <stdlib.h> int main () { time_t t; int userin; printf("Guess a number from 1 to 10\n"); scanf("%d", userin); int r = rand() % 11; if (r == userin) { printf ("you are right"); } else { printf("Try again"); } return 0; } ``` Thx a lot guys it worked out!!!!
In your code,rwill be a random number from 0 to 10. For a random number between 1 and 10, do this: ``` int r = rand() % 10 + 1; ``` Also, you should call ``` srand(time(NULL)); ``` at the beginning ofmainto seed the random number generator. If you don't seed the generator, it always generates the same sequence.
How can I achieve behavior equivalent to numpy'snumpy.nan_to_numfunction in C/C++? Specificiation for non-python programmers: Replace nan with zero and inf with finite numbers.Returns an array or scalar replacing Not a Number (NaN) with zero, (positive) infinity with a very large number and negative infinity with a very small (or negative) number. ... NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype.
I ended up using this, since I want to maintain continuity. It works with opencl as well, and doesn't require any C99 stuff. ``` float nan_to_num(float num){ if (isinf(num)){ if (signbit(num)) return -MAXFLOAT; else return MAXFLOAT; } else { return num; } } ```
If I have a file loaded in a buffer, how can I discard the last line if it is uncompleted (does not end with"\n") I think of poppulating the buffer usinggetline()line by line until the buffer is full. There is a simpler way to do it?
... have a file loaded in a buffer Find the last'\n': ``` char *end = strrchr(buffer, '\n'); // If \n found if (end) { // Insure next char is the null character *(end + 1) = '\0'; } } else { buffer[0] = '\0'; } ```
This question already has answers here:C/C++ include header file order(11 answers)Closed7 years ago. Is there any standard order of inclusion to avoid hidden dependencies? if yes,is this correct order? C library headersC++ library headersOther library headersRelated headersour projects headers
There is no standard order, but if you want to avoid hidden dependencies, you have to go in the exact opposite order: include the most project-specific headers first, then specific library headers, then more generic library headers (such as e.g. Qt and boost), and eventually standard library headers last. This way, you will be certain that missing dependencies of your project's headers are not accidentally satisfied by the headers which you've included earlier.
I've been programming in C for a while and i wondered why is important to separate this processes (Compile and Linking)? Can someone explain please?
It is useful in order to decrease rebuilt time. If you change just one source file - it is often no need to recompile whole project but only one or few files.
I'm trying to implementgecthar, usingread, the problem is when I usemy_getchar()withprintfmy function executes beforeprintf. ``` #ifndef BUFF_SIZE #define BUFF_SIZE 1023 #endif int my_getchar(void) { static char buff[BUFF_SIZE]; static char *chr; int ret; if ((ret = read(STDIN_FILENO, buff, BUFF_SIZE)) > 0) { chr = buff; return (*chr); } return (EOF); } ``` in mymain() ``` char c; printf("Enter character: "); // if I put '\n' line here, it works fine c = my_getchar(); printf("Character entered: "); putchar(c); ``` How can I solve this issue?
You will need to flush the output to stdout: ``` fflush(stdout); ``` https://bytes.com/topic/c/answers/629409-fflush-stdoutis a similar question printfwill typically do this for you if you have a newline (as you've found) but not if you don't.
This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago. Does a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored? ``` #define NUMBER 10 ```
No, macros don't work like that. They are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10. In this respect, C and C++ are identical.
This is a code that has to take an input array from the user and input the same after removing the duplicates. However, I am unsure on how to incorporate an input array in this, and right now it has the elements hardcoded. This is my first week of programming so I apologize if this is a silly question. This is the code: ``` #include <stdio.h> #include <stdbool.h> #define nelems 8 int main() { int l[nelems] = {1,2,3,1,4,4,5,6}; for(int m=0;m<nelems;m++) { bool wase = 0; for(int n=0;n<nelems && m>n;n++) { if (l[m] == l[n] && m != n) wase = 1; } if (wase == 0){ printf("%d\n", l[m]); } } return 0; } ```
Try using a for loop and scanf. ``` int i; for(i=0;i<nelems;i++){ scanf("%d",&l[i]); } ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question Say if I compile this into./COMP. If I write./COMP "biscuits" "gravy"then the answer is two. I've been trying to figure this out for a while now and I'm completely out of ideas.
``` int num_args = argc - 1; ``` Because the argc consists of the actual destination as its first char array (which is *argv[]). So you just subtract 1, eliminating the actual destination of the file you're running, and yup you got your num of args.
This question already has answers here:Is it possible to tell the branch predictor how likely it is to follow the branch?(7 answers)How do the likely/unlikely macros in the Linux kernel work and what is their benefit?(10 answers)Closed3 months ago. Can you intentionally write code in a specific way so that the branch predictor will choose the option that will be the case most of the times. For example error checks whether a resource was loaded. If this is possible how can you use this to your advantage?
If you are using GCC you can use the macroslikely()/unlikely().
For example there could be a bit of java byte code mixed together with some C. Jvm will execute java byte code and turns execution over to OS if a C part is hit. Is this technically possible or in practice?
Generally you can write C code which creates JVM, executing (execve) provided bytecode and either run them in separate threads with some IPC between or using JNA/JNI to exchange the data, or make operations and wait for completion. I met some projects using this approach (for example part of Android system, Cloudera Impala and some others), but the code there is overcomplicated and hardly traceable. For sure it's took too much effort to make it work properly. Sometimes it's better either run 2 processes using different technologies with good IPC with data serialization (thrift, protobuf) or use only one of them. If you still need to run both, I'd prefer to build a system in Java calling native functions with JNI rather than opposite.
This question already has an answer here:C preprocessor Literal Construction(1 answer)Closed7 years ago. I have ``` #define STRING "string" ``` I want to add L prefix to STRING macro later in my code (I can't do it in definition). How to do it?
This should do: ``` #include <stdio.h> #define CONCATENATE(e1, e2) e1 ## e2 #define PREFIX_L(s) CONCATENATE(L, s) #define STRING "string" int main(void) { printf("%ls\n", PREFIX_L(STRING)); } ``` These standard C pre-processor's concatenation capabilities are also covered by the documentation coming with GCC:https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html
I would like to close a socket but before notify all threads blocking onaccept/connect, therefore I am sending a user specific signal, however not knowing the tid of the signal receiving threads. I cannot use syscallkill(pid, signal)
Why not just shutdown the socket without notifying? Each thread that is blocked on accept or read from that socket will return with the corresponding error that you can parse to take the necessary actions
While modifying MFC form written by others, with Visual Studio 2012, I encountered a problem. In the form, there is a input box which takes the entire path of the file. ex)C:\folder1\test_file.wavAnd in the code,this->tb_path->Textcontains this. First problem is that I cannot find a method to deal withthis->tb_path->Textaschar*orchartype array to use methods instring.h In status quo, code uses system:: String ^fileName = this->tb_path->Text + "_re"; to modify the text, but this actually hampers various modifications of file path. How can I solve this problem?
Try ``` System::String ^fileName = gcnew System::String(this->tb_path->Text + "_re"); ``` or may be ``` System::String ^fileName = gcnew System::String(this->tb_path->Text + _T("_re")); ``` It seems to me you are not doing a required allocation in memory with gcnew, an then you get garbage inside your string from uninitialized memory.
I'm trying to implementgecthar, usingread, the problem is when I usemy_getchar()withprintfmy function executes beforeprintf. ``` #ifndef BUFF_SIZE #define BUFF_SIZE 1023 #endif int my_getchar(void) { static char buff[BUFF_SIZE]; static char *chr; int ret; if ((ret = read(STDIN_FILENO, buff, BUFF_SIZE)) > 0) { chr = buff; return (*chr); } return (EOF); } ``` in mymain() ``` char c; printf("Enter character: "); // if I put '\n' line here, it works fine c = my_getchar(); printf("Character entered: "); putchar(c); ``` How can I solve this issue?
You will need to flush the output to stdout: ``` fflush(stdout); ``` https://bytes.com/topic/c/answers/629409-fflush-stdoutis a similar question printfwill typically do this for you if you have a newline (as you've found) but not if you don't.
This question already has answers here:How memory is allocated to macros in c?(4 answers)Closed7 years ago. Does a macro allocate memory in a segment? If yes, in which memory segmentNUMBERis stored? ``` #define NUMBER 10 ```
No, macros don't work like that. They are substituted by thepreprocessor. Thecompilerdoesn't get to seeNUMBER. All it will see is the literal10. In this respect, C and C++ are identical.
This is a code that has to take an input array from the user and input the same after removing the duplicates. However, I am unsure on how to incorporate an input array in this, and right now it has the elements hardcoded. This is my first week of programming so I apologize if this is a silly question. This is the code: ``` #include <stdio.h> #include <stdbool.h> #define nelems 8 int main() { int l[nelems] = {1,2,3,1,4,4,5,6}; for(int m=0;m<nelems;m++) { bool wase = 0; for(int n=0;n<nelems && m>n;n++) { if (l[m] == l[n] && m != n) wase = 1; } if (wase == 0){ printf("%d\n", l[m]); } } return 0; } ```
Try using a for loop and scanf. ``` int i; for(i=0;i<nelems;i++){ scanf("%d",&l[i]); } ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question Say if I compile this into./COMP. If I write./COMP "biscuits" "gravy"then the answer is two. I've been trying to figure this out for a while now and I'm completely out of ideas.
``` int num_args = argc - 1; ``` Because the argc consists of the actual destination as its first char array (which is *argv[]). So you just subtract 1, eliminating the actual destination of the file you're running, and yup you got your num of args.
This question already has answers here:Is it possible to tell the branch predictor how likely it is to follow the branch?(7 answers)How do the likely/unlikely macros in the Linux kernel work and what is their benefit?(10 answers)Closed3 months ago. Can you intentionally write code in a specific way so that the branch predictor will choose the option that will be the case most of the times. For example error checks whether a resource was loaded. If this is possible how can you use this to your advantage?
If you are using GCC you can use the macroslikely()/unlikely().
For example there could be a bit of java byte code mixed together with some C. Jvm will execute java byte code and turns execution over to OS if a C part is hit. Is this technically possible or in practice?
Generally you can write C code which creates JVM, executing (execve) provided bytecode and either run them in separate threads with some IPC between or using JNA/JNI to exchange the data, or make operations and wait for completion. I met some projects using this approach (for example part of Android system, Cloudera Impala and some others), but the code there is overcomplicated and hardly traceable. For sure it's took too much effort to make it work properly. Sometimes it's better either run 2 processes using different technologies with good IPC with data serialization (thrift, protobuf) or use only one of them. If you still need to run both, I'd prefer to build a system in Java calling native functions with JNI rather than opposite.
In the below code,since the bitwise complement of x is -1(using 2's Complement) and y is 2, I am expecting the value of z to be zero but I am getting the value of z as 2 when I run the program.Can anyone please explain me where I am going Wrong? CODE ``` #include <stdio.h> int main() { int x = 0, y = 2; int z = ~x & y; printf("%d\n", z); } ```
The bitwise compliment of0is all1s soANDing with it gives you exactly the other input to theAND, in this case2. Assuming 8 bits to save space: ``` 0 = 00000000 ~0 = 11111111 2 = 00000010 ~0&2 = 00000010 ```
This is the solution ofProgramming Pearlsin column 1.6_1: ``` > #include <stdio.h> int intcomp(int *x, int *y) { return *x-*y; } int a[1000000]; int main(void) { // insert code here... int i,n=0; while (scanf("%d",&a[n])!=EOF) { n++; } qsort(a,n,sizeof(a[0]),intcomp); for(i=0;i<n;i++) { printf("%d\n",a[i]); } return 0; } ``` Error message: conflicting types for "qsort" Can you tell me why could that happen? Isn't it defined by default? My compiler isXcode(MacOS).
Comment (which turned out to be a correct guess) promoted to answer: It's unclear if the source code above was from typed in from the book, or found online. The code above has a few differences fromthis github copy of p1c1quicksort, i.e. the code above is missing: ``` #include <stdlib.h>. ```
I know that Guile has ascm_assert_smob_typefunction, but I do not believe that it returns a boolean. I want to be able to do something like: ``` if (type(smob) == int_smob) { int_foo(smob); } else if (type(smob) == string_smob) { string_foo(smob); } ```
You can checkscm_assert_smob_type'sdefinitionfor hints: ``` void scm_assert_smob_type (scm_t_bits tag, SCM val) { if (!SCM_SMOB_PREDICATE (tag, val)) scm_wrong_type_arg_msg (NULL, 0, val, scm_smobs[SCM_TC2SMOBNUM(tag)].name); } ``` As you can see, it utilizesSCM_SMOB_PREDICATEwhich does return a boolean. The macro is for public use and is defined in<smob.h>.
Novice in c programming. Could someone help me understand what the while loop is doing in this code snippet? I've never seen a while loop of this type. However, I do understand that it is performing pointer arithmetic, but what is it actually saying broken down in terms of pseudocode or plain English? :) ``` char* cpy (char* s) { char *dest, *d; d = dest = malloc(strlen(s) * sizeof(char) + 1); if (d) while ((*d++ = *s++)); return dest; } ```
In C a value of 0 means false and any other means true. Strings end in a null character with a value of 0. This while loop copies all the characters from s to d until the null (end of string) is reached. The assignment*d++ = *s++returns the same value as*s++is assigned to*d After the loop bothsanddwill be pointing after the null character. Note that the null is also copied.
I'm trying to dynamically link a Rust .so library with a C program in Linux with gcc. Using onlydlopenanddlcloseresults in no errors, but I get a segmentation fault with the following code: ``` char * (*my_function)(char *); char *my_input_string = "foo"; //...abbreviated code... my_function = dlsym(handle, "my_function"); char *my_output_string = (*my_function)(my_input_string); ``` I'm usinggcc -g foo.c -ldl -o footo compile, if that matters. I know that it's finding the symbol because I used#[no_mangle]in the rust library and themy_functionpointer is not null
I ran it throughgdband it turns out the library was trying to call a function in the calling program that didn't exist.