question
stringlengths
24
425
answer
stringlengths
5
405
I am facing difficulty in converting a binary array to a decimal number: ``` bin[8] = {10,00,00,10}; ``` I want the equivalent of this array element as a decimal number, i.e.130.
A standard solution goes like this: ``` int f(char s[]) { int n = 0; int i; for (i = 0; i < 8; ++i) { n <<= 1; n += s[i] - '0'; } return n; } ```
I am facing difficulty in converting a binary array to a decimal number: ``` bin[8] = {10,00,00,10}; ``` I want the equivalent of this array element as a decimal number, i.e.130.
A standard solution goes like this: ``` int f(char s[]) { int n = 0; int i; for (i = 0; i < 8; ++i) { n <<= 1; n += s[i] - '0'; } return n; } ```
I'm new to C and wanted to know, what does a bitwise shift 1 << 9 in an enum definition do in this case below: ``` static enum { DEAD, LIVE } state[1 << 9]; ```
The expression1<<9is the same as 29, which is 512. So an array of 512 enums is declared.
Code to receive message like "hi i am man" and convert it to upper case "HI I AM MAN". ``` n = read(newsockfd, buffer, 255); printf("Here is the message: %s\n", buffer); ```
``` #include <stdio.h> #include <ctype.h> n = read(newsockfd, buffer, 255); for(int i = 0; i < n; i++) buffer[i] = toupper(buffer[i]); printf("Here is the message: %s\n", buffer); ```
I am confused as to how to set the "editable" property to a specific child of a GtkTreeView, instead of the entire cell renderer. ``` | Column | [+] Parent |__ Child |__ Child2 <-- Press to edit ``` I didn't seem to find a way to do that.
You add another boolean column to your ListStore. Then set your Renderer editable property to that extra column. Sorry, I don't know the C code for a short example.
The elements of an uninitialized char array in C all have the value 'Ì' (or -52 as an integer; 0xCC or 204 as char). Is this another type of null character? Or is it just a value that fills in the values of an uninitialized char array? (In case it makes any difference, I am using visual studio)
Uninitialized variables have indeterminate values. They can make the behavior of your program undefined if the value is used to be a trap representation.
For example, I have two digit bits: ``` 0b0111111 0b0000110 ``` I want to shift a state variable by 7 digits and combine them together. ``` 0b00001100111111 ``` Can I accomplish by shifting?
You do this by shifting the bottom number left 7 digits, then performing a bitwise OR of the result and the first number. ``` unsigned int a = 0x3f; unsigned int b = 0x06; unsigned int result = (b << 7) | a; ```
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work? The error I receive is: cannot open source file "pthread.h"
In Visual Studio 2017 Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work? The error I receive is: cannot open source file "pthread.h"
In Visual Studio 2017 Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]
I feel like I've been searching for hours today on how to make#include <pthread.h>work in Visual Studio 2017 on Windows 10 and haven't come across an answer that has worked. Can someone please instruct me how to get this to work? The error I receive is: cannot open source file "pthread.h"
In Visual Studio 2017 Project -> Manage Nuget PackagesIn browse Tab search for 'pthread'Select Install[Search Results in Nuget packages]
What is the meaning of the following operation in C ``` USIC2_CH0->PSR &= ~((uint32_t)USIC_CH_PSR_ASCMode_TFF_Msk); ``` I know that ifA|=BmeantA=A|Bthen what is meant by A&=~B;? Does that meantA=~(A&B)??
A &= ~BmeansA = A & (~B), notA=~(A&B). You can see those two are different if you take A=b010 and B=b110, for example. In context it's disabling the bits in that PSR bitfield that are set in the constant whose name ends in "TFF_Msk" above.
How can I use assembly instructions that contain quotation marks insideasm()? like: ``` asm( ".section .rdata,"dr"\n" ); ``` The code above gives me this error: ``` expected ')' before 'dr' ```
Any string literal, not just the ones required by anasmdeclaration, can contain double quotes if they are escaped. You escape them with a\. So when applied to your example: ``` asm( ".section .rdata,\"dr\"\n" ); ```
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks. e.g in the Image below: does he count like the first row?
It's an array of characters yes it counts the spaces, it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0.. p.s: null is a character also, that gets on the end of the array
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks. e.g in the Image below: does he count like the first row?
It's an array of characters yes it counts the spaces, it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0.. p.s: null is a character also, that gets on the end of the array
Im learning for my upcoming exam and i wanted to ask if an Array counts blanks. e.g in the Image below: does he count like the first row?
It's an array of characters yes it counts the spaces, it should be in the 9 position the first blank/space and the first (i) should be in 10 position and etc and in the end of the array should be a /0.. p.s: null is a character also, that gets on the end of the array
How can I define the type of an enum to beuint8instead ofint? ``` typedef enum { R_DIRECTION_LEFT = 1, R_DIRECTION_RIGHT = 2, R_DIRECTION_TOP = 4, R_DIRECTION_BOTTOM = 8 } R_Direction; ```
No you can't. From standard §6.4.4.3C11 standard N1570 An identifier declared as an enumeration constant has type int.
I have a program that uses dynamic allocation for a uint8_t array; can I safely assume that its length will always be one byte?
Ifuint8_texists, thensizeof(uint8_t)must be 1.uint8_tisrequiredto have width exactly 8 and no padding bits, andCHAR_BITis required to be at least 8. Ifuint8_texists, it can't have more than one char's worth of bits without violating these requirements.
How can I define the type of an enum to beuint8instead ofint? ``` typedef enum { R_DIRECTION_LEFT = 1, R_DIRECTION_RIGHT = 2, R_DIRECTION_TOP = 4, R_DIRECTION_BOTTOM = 8 } R_Direction; ```
No you can't. From standard §6.4.4.3C11 standard N1570 An identifier declared as an enumeration constant has type int.
I'm writing a user define function for Vertica and don't know how to initialize a Vstring of Vertica from a C string (char *) . Thanks for any suggestion?
Following to Vertica documentation: You cannot create instances ofVStringorVNumericyourself. You can manipulate the values of existing objects of these classes that HP Vertica passes to your UDx, and extract values from them. However, only HP Vertica can instantiate these classes.
For example, if I allocate more memory space then needed on a C string is there a way to return back the unused memory? Or is this automatically done? ``` char *x = malloc(256); strcpy(x, "Hello World"); // return back unused x memory allocation ```
You can callreallocto change the size of an allocation; this can be used to make it bigger or smaller. The computer would have no basis for automatically making your allocation smaller.
Not C# or C++, but C. Is there any C support in Visual Studio?
Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community). UnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler. Answer:by default it appears not, but you can install the Clang component and it appears you will be able to.
Not C# or C++, but C. Is there any C support in Visual Studio?
Using theVisual Studio Installerif you click on your already installed version of Visual Studio (in the image I clicked on my VS 2017 Community). UnderIndividual components-->Compilers, build tools and run-timesyou can checkClang/C2. Clang is aCcompiler. Answer:by default it appears not, but you can install the Clang component and it appears you will be able to.
``` FILE * fp = fopen ("excel.csv" , " w+ "); fprintf (fp, "%s", "hello,world"); ``` I want to printhello,worldwith comma in a single cell. How can I print the same without printing in two different cells?
Put quotes around the cell: ``` fprintf(fp, "%s", "\"hello,world\""); ``` IIRC Wikipedia hasa pretty good article on CSV.
When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?
You can view the symbols of a compiled program or object file withnm(1): ``` nm a.out ``` Displays all symbols ina.out.
When compiling a C program the compiler/linker will generate a symbol table. How can we print that symbol table and what values it will store in the terminal?
You can view the symbols of a compiled program or object file withnm(1): ``` nm a.out ``` Displays all symbols ina.out.
I would like to realize in GTK3 a text window where to redirect the stdout using the c language. Could you help me with suggestions about how to start. Thank you.
I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.
I would like to realize in GTK3 a text window where to redirect the stdout using the c language. Could you help me with suggestions about how to start. Thank you.
I think what you'll need to do is write GTK code that reads from a named pipe and writes to the text box, and when you start your other c code (assuming you're starting it from a shell command), redirect stdout to the named pipe.
I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives: Use of undeclared identifier 'byte' in the next line: ``` buf[2] = (byte)(addr & 0xff); ```
In the .c file i have declaredbytewith the next code: ``` typedef uint8_t byte ``` uint8_t is similar to byte, so it compiled
I'm trying to compile library from .c file in Xcode. (It doesn't give me any errors in Visual Studio on Windows) But Xcode gives: Use of undeclared identifier 'byte' in the next line: ``` buf[2] = (byte)(addr & 0xff); ```
In the .c file i have declaredbytewith the next code: ``` typedef uint8_t byte ``` uint8_t is similar to byte, so it compiled
What does this line mean? ``` if (strcmp(argv[0],"./lower")==0) ``` Before converting to lower or upper case why this condition is checked? What does it results to?
Comparingargv[0]is checking the name of the executable. I assume you look at code similar tobusyboxin which you check the executable that the user used so you know which action to perform.
What is the difference between the two Instruction pointers (eip)? What is the goal of each one? Frame info image: There are two different eip?
saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL). eipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).
What is the difference between the two Instruction pointers (eip)? What is the goal of each one? Frame info image: There are two different eip?
saved eipis the address that your frame willreturnto (i.e. oni*86it's the address of the next instruction after theCALL). eipis thecurrentinstruction pointer, i.e. the address of instruction that is going to be executed next (once control returns to this frame).
Is there a way to send a signal to all the processes of a process ID group except for the one that is sending it? Withkill(0, SIGUSR1)we can send it to all the processes of a group including the one calling it, but what if we wanted to send it to all except for the one calling it?
``` #include <signal.h> #include <unistd.h> ... signal(SIGUSR1, SIG_IGN); /* Ignore own signal */ killpg(getpgrp(), SIGUSR1); /* Send SIGUSR1 to pgrp */ ```
Why "strrev()" and some other inbuilt string functions in c doesn't work in terminal? ``` #include<stdio.h> main() { char c[50]; scanf("%s",c); strrev(c); printf("%s",c) } ```
strrevis not standard, but can be easily implemented ``` void strrev(char *s) { int i,n = strlen(s); for(i=n/2 ; i>=0 ; i--) { char c = s[i]; s[i] = s[n-i-1]; s[n-i-1] = c; } } ```
I need to add quotes in begging and ending of a char. ``` char *Mychar = "hello"; printf("%c\n",Mychar[0]); ``` My result ishand my desired result is'h'.
Just add them in the format string. For single quotes, you can just put them in there: ``` printf("'%c'\n",Mychar[0]); ``` For double quotes, you'll have to escape them: ``` printf("\"%c\"\n",Mychar[0]); ```
This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago. The result of the values ​of A and B is as follows.
In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.
This question already has answers here:Implicit type promotion rules(5 answers)Closed5 years ago. The result of the values ​of A and B is as follows.
In the first case, the type of the expression on the right-hand side isint, and the value is -121. In the second case, the type isuint32_t, and the value isuint32_t(-121) == 4294967175. The latter cannot be precisely represented in afloat, so it gets rounded.
Is it possible (using the CPLEX C APIs) to retrieve the variables type (CPX_CONTINUOUS, CPX_BINARY, CPX_INTEGER, ...) of a model not handled by me but directly built from an .mps file?
Yes, you can use theCPXgetctypefunction. Here's the example given in the documentation link: ``` status = CPXgetctype (env, lp, ctype, 0, cur_numcols-1); ``` To get the number of columns useCPXgetnumcols.
I have a code where am gettingPC Lint info 825, even though I'm using/* fallthrough */comment. Tell me if any of my usage is wrong. Example code: ``` case 1: case 2: case 3: { statement; } /* fallthrough */ case 4: { statement 1; statement 2; break; } default: break; ```
That's the wrong comment content. Try: ``` //lint -fallthrough ``` Seethe huge text filefor details.
I want to get a samesemIdusing same key. Although, I calledsemgetmethod using same key, and returned differentsemId. Please answer me the reason why this problem happened. Sample source : ``` int id1, id2; int semflg = IPC_CREAT | 0666; id1 = semget(0, 1, semflg); id2 = semget(0, 1, semflg); ``` Result : id1 != id2
Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.
I want to get a samesemIdusing same key. Although, I calledsemgetmethod using same key, and returned differentsemId. Please answer me the reason why this problem happened. Sample source : ``` int id1, id2; int semflg = IPC_CREAT | 0666; id1 = semget(0, 1, semflg); id2 = semget(0, 1, semflg); ``` Result : id1 != id2
Key id0isIPC_PRIVATE, and will always generate a new set of semaphores. Choose a valid key.
In Code::Blocks when i run and debug my code it says in the "Build messages section" (error: Cannot find id) I reinstalled both the coding platform (code::blocks) and the compiler individually and nothing has changed.
Try simple program first to see if installation is correct: ``` #include <stdio.h> int main() { printf("Hello World"); return 0; } ```
Can I safely usememmem()if I want it to also run on Mac? I know it requires: ``` #define _GNU_SOURCE #include <string.h> ```
Yes,memmemis available on MacOS. Seethe man pagefor details. You don't however need to#define _GNU_SOURCE. That is specific to Linux.
I'm trying to make a game program in C. How to get a char or input without displaying and pausing the screen?
You mentioned you want to make a game in C. Create your own window. Capture and Process events. This sounds a bit much for a beginner but actually it is not. Use a library like SDL2 to help you with that. Here is atutorial seriesthat walks you through some of the basics of game making.
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable. Can we get that information afterwards?
Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.
Is there a way to find which interface has been used to join an IPv6 multicast group, if the index used was 0 meaning that we leave to the kernel to choose which interface is suitable. Can we get that information afterwards?
Does the IPV6_MULTICAST_IF socket option change after the join is complete? If not you'll have to look at the interface table and see which is the default, on windows this would be done with GetAdaptersAddresses, no idea for *nix.
I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?
Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.
I am new at GTK and started out using Glade to design a UI. But whenever I run my app, I must keep the Glade file in the same directory as the executable. I would like to distribute the Glade file in a compiled form, same as the source code. Is this possible?
Yes, that's possible. Give a look to theGResourcedocumentation. Its main use is to embed resources like ui files, icons, etc. in the main binary.
I have a file and I want to make a backup file, with the same name as file but with "aux" at the end. How do I do this? I tried: ``` char *nameFile, *nameAux; char *aux = aux; nameAux = nameFile + aux; ``` Which didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile
You can't just "add" C strings. effectively you've summed pointers. SeeHow do I concatenate const/literal strings in C?
I have a file and I want to make a backup file, with the same name as file but with "aux" at the end. How do I do this? I tried: ``` char *nameFile, *nameAux; char *aux = aux; nameAux = nameFile + aux; ``` Which didn't work.. nameFile is given to me by the user, and it's right because I can open/ceate the file with nameFile
You can't just "add" C strings. effectively you've summed pointers. SeeHow do I concatenate const/literal strings in C?
I am working on an implementation of named pipes client/server for school. I have asked my teacher what happens if i use unlink while either of the pipes end is still opened. He had no answer for me. Anyone know?
Nothing in particular happens, except the name is removed from the file system so no future processes can open the same named pipe. The processes that has the pipe open will continue as normal.
how to get bluetooth address of same device either through command line or program
Two problems: First is that you never check for errors from any of the system calls. The second is that the child process shouldterminatewhich yours doesn't. Instead your child process continues in the loop and callaccepton the listening socket and so on, fighting with the parent process about connections. When the child process is done it should callexitto terminate.
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I'm imagining readingbyte by bytewould be very inefficient, but reading in bulks would almost always read more than needed, requiring to store the rest of the read input in a global context for all subsequent read operations to find. What am I missing?
The prototype is: ``` ssize_t getline(char **lineptr, size_t *n, FILE *stream); ``` So it's clearly usingFILE, which is already buffered. So reading character-by-character is not inefficient at all.
I want to know whether threads created usingpthread.hlibrary are using one core, or they are running in multiple cores.
A newly created thread has no affinity, and will be shuffled around the process as deemed best by the system. If you need to pin it to a specific core,this answer provides detailsfor setting affinity to a specific pthread.
I've found out where caused SEGSEV, but only happens when that function be called hundreds of thousands times to trigger some rare case, is it possible to set breakpoint there when something is true? either on the gdb command line or c source file
Try like this: ``` (gdb) break file.c:15 if some_variable == some_value ```
Let's say here is a char with unknown digit number in C: ``` char char_id[1000] = {'1', '2', '3', ..., '8', '9', '\0'}; ``` If I want the last two digit to form an integer i.e. '89'. What is the easiest way?
may be this ``` char char_id[1000] = {'1', '2', '3', /*..., */ '8', '9', '\0'}; int what_i_want = atoi( char_id + ( strlen(char_id) - 2 ) ); ``` by the way those dots are a bit of rubbish, comment them
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
For example, if I had amakefilethat contains this: ``` dynArray.o: dynArray.c dynArray.h type.h gcc -Wall -ansi -c dynArray.c ``` How would I translate that into aCMakeLists.txtfile?
ProbablyCMake's object librarieswould do that, that mean compile objects but not archive them like normal library would. ``` add_library(<name> OBJECT <src>...) ```
I have the following code: ``` struct coord { float x; float y; }; struct coord vertices[4]; ``` But when I do the following, an error occurs: ``` void setVertices(float x, float y) { vertices[0] = (struct coord) { x, y }; } ``` Why isn't this allowed in C? Is there another way to do this? Thank you.
I can initialize structs that way, actually. The IDE just lagged on its error-checking for several minutes, for some reason.
When we create temporary files using tmpfile, in most cases we cannot easily predict the name. Coverity scan also complains about its vulnerability. So is there any function to create a temporary file which cannot be guessed easily?
If you using Linux, thenmkstemp Or usetmpnam
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed5 years ago. I was going through the logger code and came across a function ``` bool LogMessage(const char *szFor, ...) ``` What does...indicates here?
This is called anellipsis notation. This means, the function is avariadic function. It canlegallyaccept any number and type of incoming arguments.
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed5 years ago. I was going through the logger code and came across a function ``` bool LogMessage(const char *szFor, ...) ``` What does...indicates here?
This is called anellipsis notation. This means, the function is avariadic function. It canlegallyaccept any number and type of incoming arguments.
I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?
If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"
I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?
If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"
I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?
If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"
This question already has answers here:What should main() return in C and C++?(19 answers)Closed5 years ago. What will happen if we don't use it? will the compiler automatically add it like it does in C++?
It will return0automatically in C99-compliant compilers (and later). In pre-C99 compilers the return value is undefined in such cases. In other words, inmodernC you don't need an explicitreturn 0at the end ofmain.
Given achar *str = "something %s something2 %d", how can I format it and produce a new string without printing out? I know of "printf" which prints out a result, but I don't need a result to be printed out.
The answer issprintf: it's exactlyprintfto a buffer.
I'm trying to learn RDMA. My question is, when doingibv_post_send, I should get a completion event on a completion queue. But how does theibv_post_sendknow to which completion queue? From what I see here, I could have createdmany.
Turns outwhen initiating a QP, it can be assigned to a send CQ and recv CQ in its init attributes.
A runtime I'ld like to to know if an stack defined struct sockaddr_storage was assigned to any IP address (IPv4 or IPv6) Any idea?
Check thess_familyfield. It will beAF_INETfor an IPv4 address, orAF_INET6for an IPv6 address. You can then type-cast thesockaddr_storageaccordingly to eithersockaddr_inorsockaddr_in6in order to access thesockaddr_in::sin_addrorsockaddr_in6::sin6_addrfield, respectively, to make sure it is not set to zeros.
I want to open terminal and cat a file (show its content) using c; i got error from code below: ``` char * com = "xterm cat /home/user/Desktop/file.c"; system(com); ``` or even: ``` char * com = "/usr/bin/xterm /bin/cat /home/user/Desktop/file.c"; system(com); ``` thanks for any help;
You could change your command to: ``` xterm -e less file.c ```
I want to open terminal and cat a file (show its content) using c; i got error from code below: ``` char * com = "xterm cat /home/user/Desktop/file.c"; system(com); ``` or even: ``` char * com = "/usr/bin/xterm /bin/cat /home/user/Desktop/file.c"; system(com); ``` thanks for any help;
You could change your command to: ``` xterm -e less file.c ```
i have array of strings. ``` char strings[][30]={"word1","word2",......,""}; ``` Iterated over them but at the end i got messageSegmentation fault (core dumped) Tried with following code : ``` for(int i=0;strings[i] != "";i++){printing items...} ``` I think the problem is with!= ""but why isn't it working?
Usestrcmpto compare strings in C.==or!=doesn't work for strings in C.
Is this possible? I need to make a 2d array and each element is supposed to have an int array of size 2. So if I make a 10x10 array I need each index to have a [x, y] where x and y are ints.
``` int array[10][10][2]; ``` Here you have a 3D array. Where the 2D array : array[..][..] has 2 elements inside it. Or you can use structure. ``` struct number { int x; int y; }; ``` then : ``` struct number array[10][10]; ```
Does anyone know how to enable the use of OpenMP in Xcode 9.0? In Xcode 8, I procide as described inthis tutorialbut it doesn't work anymore in Xcode 9.0 ... The error is :clang-5.0: error: cannot specify -o when generating multiple output files Thanks in advance for help
I think the problem is in flag -index-store-path In build settings > build options set Enable Index-While-Building Functionality to No
I'm new embedded electronics and am learning via online tutorials. I built and downloaded a code (with the uVision IDE) which made the blue and orange LEDs flash. I want these LEDs to stop flashing, and I want the MCU to go back to the state it was at before I downloaded the code. How would I do that?
How to return: Write FLASH mass erase functionCopy mass flash erase function to the RAM.Jump to itDo the software reset
I installed the MJPG-Streamer and i want to run this from a C program. I start the MJPG-Streamer entering the following code in the pi terminal: ``` LD_LIBRARY_PATH=/usr/local/lib mjpg_streamer -i "input_file.so -f /tmp/stream -n pic.jpg" -o "output_http.so -w /usr/local/www" ``` I want to run mjpg streamer from a C program, how do I do this? Thanks!
You can usesystem()function inside stdlib header.
This question already has answers here:What happens when I use the wrong format specifier?(2 answers)Closed5 years ago. i have used the code. ``` char *y; y="hello world"; printf("%c",y); ``` it just shows something useless. What mistake i am making.
Change : ``` printf("%c",y); ``` to : ``` printf("%s",y); ``` as%cspecifier indicates achar. To identify a string, you need the specifier%s.
``` #include <stdio.h> int a = printf("cs136/n"); int main(){ printf("%d\n", a); } ``` Error: (initializer element is not a compile-time constant)
You can't use printf outside of an function. Move the line "int a = printf..." inside main. You variable "a" is an global variable. You can only initialize "a" with an constant. For example: ``` int a = 42; int main() { a = printf(... ```
I saw the following line of codeherein C. ``` int mask = ~0; ``` I have printed the value ofmaskin C and C++. It always prints-1. So I do have some questions: Why assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?
It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.
I saw the following line of codeherein C. ``` int mask = ~0; ``` I have printed the value ofmaskin C and C++. It always prints-1. So I do have some questions: Why assigning value~0to themaskvariable?What is the purpose of~0?Can we use-1instead of~0?
It's a portable way to set all the binary bits in an integer to 1 bits without having to know how many bits are in the integer on the current architecture.
Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?
Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address. llvm::Function Documentation
I need to print.5as0.5using theprintfstatement in C language. It can be done easily using the following code. ``` printf("%03f", myfloatvalue); ``` But the situation ismyfloatvalueis dynamic. So i am not sure whether it is a 3 character number, it could be.5or.56or.567. In the above cases i need to print as0.5,0.56, and0.567.
%gdoes print the shortest possible representation of a float. ``` printf("%g",myfloatvalue); ```
Is there a way to get the static address of a function pointed byllvm::Functionobject in a C code using the LLVM IR API?
Sincellvm::Function*is a subclass ofllvm::Value*you can just treat as anllvm::Value*and LLVM will substitute the correct address. llvm::Function Documentation
Is this statement correct in C-language? ``` a && b && c ``` I want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?
Yes, the usage is correct. You can AND as many expressions as you want.
Is this statement correct in C-language? ``` a && b && c ``` I want to check((a==2) && (b==3) && (c==4)).Is this usage of logicalANDcorrect?
Yes, the usage is correct. You can AND as many expressions as you want.
In my driver module data is coming in callback function. I want to add data to read callback but not able to find read callback in tty structure
There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3
I'm new to Linux and C and when trying to run a basic "Hello World" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code
You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents. Either navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.
In my driver module data is coming in callback function. I want to add data to read callback but not able to find read callback in tty structure
There is no read callback. The tty core buffers the data received by the tty drivers in a structure called struct tty_flip_buffer. ReadChapter 18of LDD3
I'm new to Linux and C and when trying to run a basic "Hello World" script, i kept getting the same two errors. I have confirmed that everything in the program is correct.errors gotten when trying to compile code
You are running thegcccommand from the home directory (~) when thehello.cfile is in~/Documents. Either navigate toDocumentsusingcdbefore runninggccor placehello.cin the home directory.
This question already has answers here:hello world in C without semicolons and without IF/WHILE/FOR statements [closed](7 answers)Closed6 years ago. I want to display hello world message in c without using semicolon. how can I do that? Is it possible?
Yes, It is possible. ``` #include<stdio.h> int main(){ if(printf("hello world")){} } ```
I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?
There is a checkbox in Menue "Settings""Editor..."General SettingsEditor SettingsEnd of Line options"show end of line chars"
I am new in the IDE Code::Blocks, and I accidentally inserted this mark in every line of the code (CR LF), and I want to remove, I'm sure to be a pretty simple thing to fix but I found nothing in the Settings. By the way, what does it mean?
There is a checkbox in Menue "Settings""Editor..."General SettingsEditor SettingsEnd of Line options"show end of line chars"
I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C. ``` set_title(uint16_t *title) ``` Any idea how can I do this ?
You need some form of interprocess communication to be able to do that. There are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.
What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?
No, there is not. You will have to use pointers.
I have a NodeJS server running on the same server with a C program. I need to sent a byte array from my NodeJS server to my C program. I have a set_title function in C. ``` set_title(uint16_t *title) ``` Any idea how can I do this ?
You need some form of interprocess communication to be able to do that. There are libraries out there which can facilitate that work for you, have a look atnanomsgandzmqwhich both have both C and JS bindings.
What's the best way to allocate an array on the stack that will be used by several helper functions/macros. Is there anyway to avoid passing pointers around?
No, there is not. You will have to use pointers.
If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?
Use this: #define DOSTUFF(X) dostuff_##X() The preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x(). On the other hand, consider renaming your methods to something meaningful.