question
stringlengths
25
894
answer
stringlengths
4
863
This images below are from a header.hfile. As seen, If I am in the scope of a function, typingRCC->pops up the options, however, if I am not in the scope of any function, then it does not show them. What's the reason for that?
You can only place the code in the function body. You try to do it outside the function. That is the reason. Intellisense knows it and does not suggest it. Same is with macros. Preprocessor does not know anything about the C language. In the macro definition it acts exactly the same way. I personally do not like this kind of macros. Use normal inline functions for that. If you enable optimisations (even -Og) the function will be inlined https://godbolt.org/z/yd75jH
I just restart the C programming study. Now, I'm studying the memory storage capacity and the difference between bit and byte. I came across tothis definition. There is a calculation to a 32 bits system. I'm very confused, because in this calculation 2^32 = 4294967296 bytes and it means about 4 Gigabyte. My question is: Why 2 raised to 32 power results in a number in bytes instead of bits ? Thanks for helping me.
Because the memory is byte-addressable (that is, each byte has its own address).
I was wondering if anybody here is familiar with the "libelf by example" book.https://www.dbooks.org/libelf-by-example-1587/read/I was trying to run prog2.c but I couldn't find the header vis.h (header it's used in chapter 3 and 5) I downloaded the libelf library from the sourceforge linkhttps://sourceforge.net/p/elftoolchain/wiki/Home/I also tried to googled it up but I couldn't find anything relevant. I was wondering if it's been substituted by another header in future versions.
I couldn't find the header vis.h The author appears to be usingthisvisfunction. Try changing#include <vis.h>to#include <bsd/vis.h>. On my system, this file comes fromlibbsd-devpackage. It is likely that you'll need to link againstlibbsd.soto get the definition ofvis.
Where are the string and char array stored? ``` int main () { int a = 0; //This should be stack char* p = "hello"; // why this is on the static? char k[10] = "hello"; //on the stack? } ``` A textbook says that the char pointer (Char* a) will be stored on the static, from my understanding of "static memory", only these 2 will be stored on the static memory: ``` int a=0;// will on the static int main() { static xxxxx; //will on the static. } ```
By6.7.8.2, the string"hello"inchar *p = "hello"is string literal.String literals are generally located in.rodata, to prevent modification. Also, global variable are located in.datasection.
Yesterday I wanted to fix an issue I was having with format identifier%Lf, and went ahead and added flags to Dev-C++:-std=c11and-D__USE_MINGW_ANSI_STDIO=1. This actually fixed the issue. For further reference, you can read the actual issue I was having here:Format specifier %Lf is giving errors for `long double` variables However, when I switched on my computer today, I found that the compiler was not available any more: How could I fix this so that I can compile code again? N.b.I was using DEV-C++ with compilerTDM-GCC 4.9.2 64-bit Release. N.b.1I am using Parallels in a MacBook Pro to be able to run Dev-C++ on Windows. N.b.2I am programming in C.
Best thing I could do is reset the Dev-C++ settings: ``` Tool > Environment Options > Directories > Remove Settings and Exit ``` Then just reopen the program and adjust the settings as you prefer.
I am reviewing a code which I believe runs based on probability. I would like to verify that if it is true. Does the following code snippet runs 80% of the time? I dont quite get why use 1000 then if our job is to merely run a code 80% of the time. ``` if(rand()%1000<1000*0.8){ ... } ```
It will run approximately 80% of the time. rand()returns a number between 0 andRAND_MAXwhich is probably 2,147,483,647rand() % 1000reduces that range to 0-999, although some numbers in the first half or so of the range will be slightly more common becauseRAND_MAXis not evenly divisible by 1,0001000 * 0.8is just 800 The use of 1,000 here is arbitrary. A clearer way of representing 80% would be: ``` if (rand() % 100 < 80) ``` or just: ``` if (rand() < RAND_MAX * 0.8) ```
I am reviewing a code which I believe runs based on probability. I would like to verify that if it is true. Does the following code snippet runs 80% of the time? I dont quite get why use 1000 then if our job is to merely run a code 80% of the time. ``` if(rand()%1000<1000*0.8){ ... } ```
It will run approximately 80% of the time. rand()returns a number between 0 andRAND_MAXwhich is probably 2,147,483,647rand() % 1000reduces that range to 0-999, although some numbers in the first half or so of the range will be slightly more common becauseRAND_MAXis not evenly divisible by 1,0001000 * 0.8is just 800 The use of 1,000 here is arbitrary. A clearer way of representing 80% would be: ``` if (rand() % 100 < 80) ``` or just: ``` if (rand() < RAND_MAX * 0.8) ```
In C/C++, argc is the count of command line arguments and argv is char** or pointer to pointer of characters. I get that argc can be used to get number of arguments, but how does the compiler know the length of the first argument or the second?
Thecompilerdoesn't know anything about the contents ofargv. Theruntime librarythat is provided by your compiler vendor and linked to your executable will get the command-line arguments from the OS when the process is created, and that library will then allocate its own array ofchar*pointers tonull-terminated stringsthat are copied from the OS-provided data. That array is then passed to yourmain()viaargv, andargcis set to the number of validchar*pointers in the array. The runtime will free memory for that array aftermain()exits.
I'm trying to send message to all terminals for my user. ``` echo -e "\nHello" > /dev/pts/1 ``` works fine, but ``` echo -e "\nHello" > /dev/pts/* ``` doesn't work And I need to realize it via C code. like that: ``` if(fork() == 0){ execl("echo -e '\nHello' > /dev/pts/*", NULL); return 0; } ```
You could simply use a bash loop : ``` for f in /dev/pts/*; do echo -e "\nHello" > $f; done ``` Also, you should use "system" to call a shell command. ``` #include <stdlib.h> void main(void) { system("for f in /dev/pts/*; do echo -e '\nHello' > $f; done"); } ```
In C/C++, argc is the count of command line arguments and argv is char** or pointer to pointer of characters. I get that argc can be used to get number of arguments, but how does the compiler know the length of the first argument or the second?
Thecompilerdoesn't know anything about the contents ofargv. Theruntime librarythat is provided by your compiler vendor and linked to your executable will get the command-line arguments from the OS when the process is created, and that library will then allocate its own array ofchar*pointers tonull-terminated stringsthat are copied from the OS-provided data. That array is then passed to yourmain()viaargv, andargcis set to the number of validchar*pointers in the array. The runtime will free memory for that array aftermain()exits.
I'm trying to send message to all terminals for my user. ``` echo -e "\nHello" > /dev/pts/1 ``` works fine, but ``` echo -e "\nHello" > /dev/pts/* ``` doesn't work And I need to realize it via C code. like that: ``` if(fork() == 0){ execl("echo -e '\nHello' > /dev/pts/*", NULL); return 0; } ```
You could simply use a bash loop : ``` for f in /dev/pts/*; do echo -e "\nHello" > $f; done ``` Also, you should use "system" to call a shell command. ``` #include <stdlib.h> void main(void) { system("for f in /dev/pts/*; do echo -e '\nHello' > $f; done"); } ```
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.Closed3 years ago.Improve this question ``` double fracsum (int a, int b, int c, int d){ float sum = 0; int i; for (i = 0; i < a; i++) { sum += a; } return sum; } int main(void) { printf("%.3f %.3f %.3f\n", fracsum(1,2,2,4), fracsum(1,4,1,8), fracsum(4,3,5,6)); return 0; } ```
Did you mean: ``` float fracsum (float a, float b, float c, float d) { return (a / b + c / d); } ``` However the problem was maybe that you cannot divide int variables, you have to use float as argument type..
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.Closed3 years ago.Improve this question ``` double fracsum (int a, int b, int c, int d){ float sum = 0; int i; for (i = 0; i < a; i++) { sum += a; } return sum; } int main(void) { printf("%.3f %.3f %.3f\n", fracsum(1,2,2,4), fracsum(1,4,1,8), fracsum(4,3,5,6)); return 0; } ```
Did you mean: ``` float fracsum (float a, float b, float c, float d) { return (a / b + c / d); } ``` However the problem was maybe that you cannot divide int variables, you have to use float as argument type..
``` #include <stdio.h> struct node { int data; struct node* next; }; typedef struct node Node; int main() { Node a; a.data = 1; if (!a.next) { printf("hello world"); } } ``` I'm writing a little linked list program to start learning c, and I'm confused as to why a.next is not null.
In short, whenever you allocate some memory in C (either explicitly or implicitly), the memory is initialized with whatever was there when the stack frame for your main function was created (ie. garbage). This is true of yourintvalue as well (remove thea.data = 1and print the value ofa.data). C doesn't zero the memory it allocates for you (which makes C more efficient). As Anandha suggested, just set the pointer toNULLto avoid this problem.
The original code is as follows: ``` #include <stdio.h> int main(void) { int n = 0; while (n++ < 3); printf("n is %d\n", n); return 0; } ``` I wonder why the result is "n is 4" not "n is 3"?
what happens here is that you compare to a good value, lets say 2 < 3, then the postincrement happens and you end up with 3 inside the loop An example: ``` // you probably want to remove the ; at the end of the while like this: while (n++ < 3) { // the posticrement will update the value n printf("n is %d\n", n); // here n will have an updated value } ``` It is also a good practive to use {} instead of indentation.
gcc has the __int128 type natively. However, it’s not defined in limits.h. I’m mean there’re no such things asINT128_MAXorINT128_MIN… And gcc is interpreting literal constants as 64 bits integers. This means that if I write#define INT128_MIN −170141183460469231731687303715884105728it will complain about the type telling it has truncated the value. This is especially annoying for shifting on arrays. How to overcome this ?
``` static const __uint128_t UINT128_MAX =__uint128_t(__int128_t(-1L)); static const __int128_t INT128_MAX = UINT128_MAX >> 1; static const __int128_t INT128_MIN = -INT128_MAX - 1; ```
How to configure the library function node parameter in LabView for a C function declared like this: ``` char listPorts(cust_struct *cust, unsigned char *pPort, char (*pSer)[16]) ``` I don't know how to configure the parameterchar (*pSer)[16]. I've tried it as TypeAdapt to Type(with a cluster consisting of strings). But this will raiseError 1097. This pointer will write strings to an array. How do I have to configure this parameter?
There is no mechanism in LabVIEW to directly pass a LabVIEW array of strings to a C-style array of strings parameter, particularly not one with fixed size. You will need to write a wrapper DLL around that function that can translate the LabVIEW data structure into a C data structure (or vice versa), managing the memory transformation along the way. This document will help you understand the memory layout. Using Arrays and Strings in the Call Library Function Node
I am trying to terminate my app on some particular event. Why would one use exit(0) or raise(SIGTERM) over the other? Also since exit(0) returns EXIT_SUCCESS to the host, what does SIGTERM do? Is it always failure?
exitcauses the program to terminate with normal exit status, with value given by the argument toexit, in your case 0. raiseraises a signal, which may be caught. If it's not caught or blocked then the default action is carried out. ForSIGTERM, the default action isabnormaltermination, and the signal that caused it is visible in the program's exit status. What consequences this has for iOS applications, I'm not sure.
gcc has the __int128 type natively. However, it’s not defined in limits.h. I’m mean there’re no such things asINT128_MAXorINT128_MIN… And gcc is interpreting literal constants as 64 bits integers. This means that if I write#define INT128_MIN −170141183460469231731687303715884105728it will complain about the type telling it has truncated the value. This is especially annoying for shifting on arrays. How to overcome this ?
``` static const __uint128_t UINT128_MAX =__uint128_t(__int128_t(-1L)); static const __int128_t INT128_MAX = UINT128_MAX >> 1; static const __int128_t INT128_MIN = -INT128_MAX - 1; ```
How to configure the library function node parameter in LabView for a C function declared like this: ``` char listPorts(cust_struct *cust, unsigned char *pPort, char (*pSer)[16]) ``` I don't know how to configure the parameterchar (*pSer)[16]. I've tried it as TypeAdapt to Type(with a cluster consisting of strings). But this will raiseError 1097. This pointer will write strings to an array. How do I have to configure this parameter?
There is no mechanism in LabVIEW to directly pass a LabVIEW array of strings to a C-style array of strings parameter, particularly not one with fixed size. You will need to write a wrapper DLL around that function that can translate the LabVIEW data structure into a C data structure (or vice versa), managing the memory transformation along the way. This document will help you understand the memory layout. Using Arrays and Strings in the Call Library Function Node
I cannot compile a program using the mongodb c driver. I am using the CodeBlocks IDE. In Build options-> Other Compiler Options, I have:pkg-config --libs --cflags libmongoc-1.0This produces an error: mongoc.h, no such file or directory. The documentation shows: $(pkg-config --libs --cflags libmongoc-1.0) This produces an error if placed in Build Options -> Other Compiler Options. Error: expected ")" Please advise.
I found my answer on another post, here:Problem installing Mongo C Driver on ubuntu 16.04 Basically, you need to also install the dev package, the documentation doesn't mention that.
This question already has answers here:Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?(19 answers)Closed3 years ago. ``` char *c = "H'eLo"; for (int i = 0; i < 5; i++) { if (isupper(c[i])) { c[i] = tolower(c[i]); printf("%c \n", c[i]); } } ``` So I am running this code, and trying to figure out what I am doing wrong. What is the reason for the segmentation fault?
If you want to modify the string, you should allocate it dinamically just like this ``` char *c = malloc(5*sizeof(char)); ``` Then, pass the string with strcpy ``` strcpy(c, "H'eLo"); ``` Or you also can do it with the function strdup, which is the easiest option ``` char *c = strdup("H'eLo"); ``` These examples should work, because C doesn't let you modify strings literals
There are many "Makefile" examples for multiple executables. After a lot of trials and errors, I found this is following as the simplest one. ``` CC = gcc SOURCES = $(wildcard *.c) EXECS = $(SOURCES:%.c=%) .PHONY: all clean all: $(EXECS) clean: rm -f $(EXECS) ``` However, I could not find any simple example for including one "include.h" dependency for all those programs. Please, could anybody show me? JW. PS: I have no idea about thisexample.Thanks to @MadScientist, the answer is: ``` CC = gcc SOURCES = $(wildcard *.c) EXECS = $(SOURCES:%.c=%) .PHONY: all clean all: $(EXECS) $(EXECS): include.h clean: rm -f $(EXECS) ```
This makefile is fine if you have a set of executables, each of which is built from exactly one source file. In this situation you can just write: ``` $(EXECS): include.h ``` and you're done.
I was wondering if there's a way to store multiple variable data in a string. I am trying to store the date, month and year that I am taking from user as an input to store in a single string/array. ``` scanf("%d/%d/%d",&getDate.dd,&getDate.mm,&getDate.yyyy); ``` Assuming that the value entered above is a valid input, How can I storegetDate.dd,getDate.mm,getDate.yyyyin a single string/array in aDD-MM-YYYYformat?
You can use thesprintffunction to write data to a character string: ``` //... char dataString[11]; // Enough space for DD-MM-YYYY plus the required nul-terminator sprintf(dateString, "%02d-%02d-%04d", getDate.dd, getDate.mm, getDate.yyyy); ``` The%02dformat specifies that 2 digits should be printed, adding a leading zero if the value is < 10.
There are many "Makefile" examples for multiple executables. After a lot of trials and errors, I found this is following as the simplest one. ``` CC = gcc SOURCES = $(wildcard *.c) EXECS = $(SOURCES:%.c=%) .PHONY: all clean all: $(EXECS) clean: rm -f $(EXECS) ``` However, I could not find any simple example for including one "include.h" dependency for all those programs. Please, could anybody show me? JW. PS: I have no idea about thisexample.Thanks to @MadScientist, the answer is: ``` CC = gcc SOURCES = $(wildcard *.c) EXECS = $(SOURCES:%.c=%) .PHONY: all clean all: $(EXECS) $(EXECS): include.h clean: rm -f $(EXECS) ```
This makefile is fine if you have a set of executables, each of which is built from exactly one source file. In this situation you can just write: ``` $(EXECS): include.h ``` and you're done.
I was wondering if there's a way to store multiple variable data in a string. I am trying to store the date, month and year that I am taking from user as an input to store in a single string/array. ``` scanf("%d/%d/%d",&getDate.dd,&getDate.mm,&getDate.yyyy); ``` Assuming that the value entered above is a valid input, How can I storegetDate.dd,getDate.mm,getDate.yyyyin a single string/array in aDD-MM-YYYYformat?
You can use thesprintffunction to write data to a character string: ``` //... char dataString[11]; // Enough space for DD-MM-YYYY plus the required nul-terminator sprintf(dateString, "%02d-%02d-%04d", getDate.dd, getDate.mm, getDate.yyyy); ``` The%02dformat specifies that 2 digits should be printed, adding a leading zero if the value is < 10.
MSVC emits warningC4090about const correctness while both GCC and Clang accept it :Compiler Explorer. ``` void dummy(void) { int i[42]; int *pi[42]; int const *pci[42]; memset(i, 0, sizeof i); memset(pi, 0, sizeof pi); memset(pci, 0, sizeof pci); // warning C4090: 'function': different 'const' qualifiers } ``` It seems MSVC treatspcias constant when it's not. This bug is apparentlyawfully old. Any idea how to fix this without turningC4090off ?
You can disable this warning right before the line which invokes it and restore it back afterwardshttps://godbolt.org/z/W-XR-Q: ``` #include <string.h> void dummy(void) { int i[42]; int *pi[42]; const int *pci[42]; memset(i, 0, sizeof i); memset(pi, 0, sizeof pi); #pragma warning( push ) #pragma warning( disable : 4090) memset(pci, 0, sizeof pci); // NO warning C4090 #pragma warning( pop ) } ```
MSVC emits warningC4090about const correctness while both GCC and Clang accept it :Compiler Explorer. ``` void dummy(void) { int i[42]; int *pi[42]; int const *pci[42]; memset(i, 0, sizeof i); memset(pi, 0, sizeof pi); memset(pci, 0, sizeof pci); // warning C4090: 'function': different 'const' qualifiers } ``` It seems MSVC treatspcias constant when it's not. This bug is apparentlyawfully old. Any idea how to fix this without turningC4090off ?
You can disable this warning right before the line which invokes it and restore it back afterwardshttps://godbolt.org/z/W-XR-Q: ``` #include <string.h> void dummy(void) { int i[42]; int *pi[42]; const int *pci[42]; memset(i, 0, sizeof i); memset(pi, 0, sizeof pi); #pragma warning( push ) #pragma warning( disable : 4090) memset(pci, 0, sizeof pci); // NO warning C4090 #pragma warning( pop ) } ```
I'm using blocking socket with SSL_read on server side.In some un expected conditions if the client die i need to disconnect that specific client connection on server side with SO_KEEPALIVE.How can i setsockopt with 5 minutes SO_KEEPALIVE ? Thanks in advance.
In Linux, you can adjust the timeout on a socket that's hadSO_KEEPALIVEturned on with theTCP_KEEPIDLEoption. It takes a time in seconds: ``` int timeout = 300; setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &timeout, sizeof timeout); ```
Why *pointer is an integer but not the string content "Hello from pointer" Thanks! ``` int main(void) { char *pointer; pointer = "Hello from pointer"; printf("*pointer is %d\n", *pointer); printf("\n"); } ``` the output is *pointer is 72
It's because the ASCII code for'H'(which is the first element of the array) is72. It is completely normal. Here is the ASCII Code table
``` #define len(a) if (a == 8) 1 \ else if (a == 3) 0 \ else -1 ``` this code is just an example how do we use nested if else. I don't want to use ternary operator as in that case i can't use else if statement.
Don't abuse the preprocessor. Use a real function: ``` constexpr auto len(int const a) { if (a == 8) return 1; if (a == 3) return 0; return -1; } ```
``` long number = 12501; unsigned char mask = 1 << 7; // create a mask 10000000 for (size_t i=0; i<(sizeof(long)*8); ++i){ // iteration for all bits of long type if (mask & number){ putchar('1'); } else { putchar('0'); } number <<=1; // I shift the most significant bit after every comparison } ``` Is it possible to do a binary conversion using a char mask? My current output is:0110100000000000000000000000000000000000000000000000000000000000 Expected output:0000000000000000000000000000000000000000000000000011000011010101
Here you have a correct version ``` void printbin(long number) { unsigned long mask = 1LU << (sizeof(unsigned long) * CHAR_BIT - 1); // create a mask 10000000 for (; mask; mask >>= 1){ // iteration for all bits of long type putchar((number & mask) ? '1' : '0'); } } ``` https://godbolt.org/z/Qm8Uqs
I am sure this question has been asked before. But I am wondering what does thetypedefmean in this code: ``` typedef long (*HASH_CONS_HASH)(void *); typedef bool (*HASH_CONS_EQUAL(void *, void *)); ``` So far I understand: HASH_CONS_HASHis a function that takes avoid*and returnslongHASH_CONS_EQUALis a function that takes two arguments of typevoid*and returnsbool But what doestypedefmean here? is it necessary?
It declares the function pointertype. now you can defineHASH_CONS_HASH func1;where func1 is a pointer to the function returning long and not taking any parameters orHASH_CONS_EQUAL func2;wherefunc2is a pointer to function returningbooland taking two void pointer as parameters.
``` long number = 12501; unsigned char mask = 1 << 7; // create a mask 10000000 for (size_t i=0; i<(sizeof(long)*8); ++i){ // iteration for all bits of long type if (mask & number){ putchar('1'); } else { putchar('0'); } number <<=1; // I shift the most significant bit after every comparison } ``` Is it possible to do a binary conversion using a char mask? My current output is:0110100000000000000000000000000000000000000000000000000000000000 Expected output:0000000000000000000000000000000000000000000000000011000011010101
Here you have a correct version ``` void printbin(long number) { unsigned long mask = 1LU << (sizeof(unsigned long) * CHAR_BIT - 1); // create a mask 10000000 for (; mask; mask >>= 1){ // iteration for all bits of long type putchar((number & mask) ? '1' : '0'); } } ``` https://godbolt.org/z/Qm8Uqs
I am sure this question has been asked before. But I am wondering what does thetypedefmean in this code: ``` typedef long (*HASH_CONS_HASH)(void *); typedef bool (*HASH_CONS_EQUAL(void *, void *)); ``` So far I understand: HASH_CONS_HASHis a function that takes avoid*and returnslongHASH_CONS_EQUALis a function that takes two arguments of typevoid*and returnsbool But what doestypedefmean here? is it necessary?
It declares the function pointertype. now you can defineHASH_CONS_HASH func1;where func1 is a pointer to the function returning long and not taking any parameters orHASH_CONS_EQUAL func2;wherefunc2is a pointer to function returningbooland taking two void pointer as parameters.
Help!!!! How can I castargs.tab1to(void *)and pass it as anargumentofpthread? Thanks //struct ``` typedef struct args args; struct args { int *tab1; int *tab2; int *tab3; int *tab4; }; ``` //pthread ``` args args; //define struct pthread_t tid; pthread_create(&tid, NULL, function1, (void *)args.tab1); pthread_join(tid, NULL); ``` //function1 ``` void *function1(void *input) { int *arr = (int*)input; function2(arr); } //function2 void function2(int *arr) { ... } ```
There is no need to cast. The compiler will not complain when casting any pointer tovoid *. Just do ``` args a; pthread_create(&tid, NULL, function1, a.tab1); ```
``` #include <stdio.h> #include <string.h> int main() { char a; char s[100]; char sen[100]; scanf("%c",&a); // take character printf("%c",a); //print character scanf("%s",s); //take input as a word printf("\n%s",s); //print the word if((gets(sen))=='\n') gets(sen);// take input as a string puts(sen); //print that string } ``` Asgets()takes input from buffer so it will take '\n' as input after that anothergets()command should work but that is not working. It doesn't take any input. Why?
gets(sen)returnssen, which is the address of the char array. Therefore, what you are trying to do should be ``` if(strcmp(gets(sen), "\n") == 0) gets(sen);// take input as a string ``` However, this is error-prone becausesencan be a space with a newline, which is not "\n" or so.
I compiled c program with this code printf("|%5c|", '\0');width 5 is just for example then used cat -e on a.out ./a.out | cat -e and have this on the output | ^@|$ Am i right that it is '\0' represented as ^@? What is it and how does it work?
The^(control) symbol represents subtraction of 64 from an ASCII value (or maybe more accurately, clearing of the sixth and seventh bits, but it's the same thing for values between 64 and 95). For example, "A" is 65, and ^A is 1. M is 77, and ^M is 13. "@" is 64, so ^@ is a way of writing character 0.
I get the warning: passing argument 2 of ‘accept’ from incompatible pointer type [-Wincompatible-pointer-types] Why am I getting this error? ``` if(s = accept(ls, &client_address, &client_address_len)<0); { perror("Error: accepting failed!!"); exit(1); } ```
According tohttps://pubs.opengroup.org/onlinepubs/009695399/functions/accept.html, the second argument ofacceptfunction receives a type ofstruct sockaddr *. You might want to do a conversion:&client_addressto(struct sockaddr *)&client_address
May I ask in C what does the following byte mean here? I thought it should be something like float foo(void), what does the byte mean? Does it mean if the required number is 100 in percent, it will return 1111 1111?I am confused with the byte here. ``` byte foo(void): //return required number in percent ```
In that context the function is prototyped to return a type calledbyte. BecauseC does not have a native typebyte, it must be atypedef, for example: ``` typedef unsigned char byte; ``` The likely reason for this type is in the comment: ``` //return required number in percent ``` where because the function will return a integer value somewhere is the range of0to100, 8 bits is more than sufficient. (in hex:0x0to0x64, so if 100 is indeed the maximum needed value for the application the MSB will never be used.) If however the full range of 8 bits is desired then return value could be up to 255.
I had tried running a program which I solved in codeblocks and using math.h library in cs50 ide by Harvard University(which is Ubuntu based). Its giving me an error that library is not included. How to include to my cs50 ide..?
Are you including it in the compiling? Easiest way to do it is to compile with: make filename If that doesn't work check you are adding it correctly: #include
I am trying to write Python C extensions and I'm on a mac. I know how to install thePython.hheader file on Linux, but I don't know how to do it on a Mac. How can I install it?
The Python header file is a framework on Mac. You have to include it like this: ``` #include <Python/Python.h> ```
I get the warning: passing argument 2 of ‘accept’ from incompatible pointer type [-Wincompatible-pointer-types] Why am I getting this error? ``` if(s = accept(ls, &client_address, &client_address_len)<0); { perror("Error: accepting failed!!"); exit(1); } ```
According tohttps://pubs.opengroup.org/onlinepubs/009695399/functions/accept.html, the second argument ofacceptfunction receives a type ofstruct sockaddr *. You might want to do a conversion:&client_addressto(struct sockaddr *)&client_address
I have an embedded linux project. And it gets data via UDP to static char array from UDP buffer. This static array's size is 20000 bytes. I want to ignore UDB messages that exceed this size. But when comes bigger data, it stays always in UDP buffer since it is not read with recvfrom. Is there any way to clear this bigger data in UDP buffer?
One cannot discard the data from the socket buffer without reading. But one can read these large datagrams even when having a smaller buffer - it will simply discard anything which does not fit into the given buffer. To find out if the datagram was too large use theMSG_TRUNCflag so that it will provide the original length of the packet. If this indicates an oversized packet just discard it and continue with the next packet.
How can I calculate all the missing values between a particular range of numbers where a missing number is equal toaverageofnextandpreviousvalues of given input range Example Number of missing values = 2 Array :[5, ?, ?, 20] Result:5,10,15,20 Simply doing (5+25)/4+1 i.e. missing values+1 gives you 5 which we add to our first value gives 5 10 15 20 but doesn't work with other examples like [6,?,?,?,20](3 missing values)
Maybe you can try something like calculate the difference between the first and the last number you know, 20-5=15 on the example, and now you just divivide it to the number of "steps" you want to get the last one (number of missing number + 1), 15/3 = 5 on the example, and now you just add that quantity to each element to get the next one. Something like this: [5, (5+5), ((5+5)+5), 20] You can verify it works for the second example too with 3 missing values.
How can I calculate all the missing values between a particular range of numbers where a missing number is equal toaverageofnextandpreviousvalues of given input range Example Number of missing values = 2 Array :[5, ?, ?, 20] Result:5,10,15,20 Simply doing (5+25)/4+1 i.e. missing values+1 gives you 5 which we add to our first value gives 5 10 15 20 but doesn't work with other examples like [6,?,?,?,20](3 missing values)
Maybe you can try something like calculate the difference between the first and the last number you know, 20-5=15 on the example, and now you just divivide it to the number of "steps" you want to get the last one (number of missing number + 1), 15/3 = 5 on the example, and now you just add that quantity to each element to get the next one. Something like this: [5, (5+5), ((5+5)+5), 20] You can verify it works for the second example too with 3 missing values.
I'm working on recodingprintfand I'm blocked for a moment now with the precision flag. So I read that the default precision when type conversion specifier isdis 1: So I supposed that there is no difference between%.dand%.1d, but when I test: ``` printf(".d =%.d, .1d= %.1d", 0, 0); ``` I do find one: ``` .d =, .1d= 0 ```
If you use.after%without specifying the precision, it is set to zero. From theprintfpage on cppreference.com: .followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored.If neither a number nor * is used, the precision is taken as zero. It defaults to1if you use%d(without.): ``` printf("d = %d, 1d= %1d", 0, 0); # Output: d = 0, 1d= 0 ```
I am using the GMP. My program can build successfully, But run failed. The following is error things: ``` a=1231231231231231 res^n != a Segment fault ``` All codes in my program is: ``` #include <gmp.h> #include <stdio.h> int main() { mpz_t a,res; unsigned long int n = 123; char str1[] = "1231231231231231"; mpz_init_set_str(a, str1, 10); gmp_printf("a=%Zd\n",a); mpz_init(res); if(mpz_root(res, a, n)){ printf("res^n == a\n"); } else{ printf("res^n != a\n"); } mpz_clears(a,res); return 0; } ```
You have to call mpz_clears() like: ``` mpz_clears(a,res, NULL); ``` Here's what the documentation says: ``` Function: void mpz_clears (mpz_t x, ...) Free the space occupied by a NULL-terminated list of mpz_t variables. ```
I want an easy way to create multiple directories in C. For example I want to create directory in: /a/b/c but if the directories are not there I want them to be created automagically. How can I do this ?
Here is a small C program to create the directory treea/b/cin the current directory: ``` #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <errno.h> int create_dir(char *name) { int rc; rc = mkdir(name, S_IRWXU); if (rc != 0 && errno != EEXIST) { perror("mkdir"); exit(1); } if (rc != 0 && errno == EEXIST) printf("%s already exists.\n", name); return 0; } int main(int argc, char **argv) { create_dir("a"); create_dir("a/b"); create_dir("a/b/c"); exit(0); } ```
In x86-64 linux environment, why C promote signed integer -1 to unsigned long 0xffffffffffffffff, but not 0xffffffff? ``` #include <stdio.h> int main() { unsigned long ul = (int)-1; printf("%lx\n", ul); } ```
C11§6.3.1.3 Signed and unsigned integers ¶1,2: When a value with integer type is converted to another integer type other than_Bool, if the value can be represented by the new type, it is unchanged.Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)60)The rules describe arithmetic on the mathematical value, not the value of a given type of expression. So,-1is converted by addingULONG_MAX + 1, yieldingULONG_MAX, as you discovered. Your system must be using 64 bits for theunsigned longtype.
This question already has answers here:Writing to pointer out of bounds after malloc() not causing error(7 answers)Closed3 years ago. I'm allocating memory for a string using malloc:s=(char*) malloc(sizeof(char)*4)Why can I store more than 4 characters to the string? If I allocated 4 bytes of memory and each character requires 1 byte, why can I store 8 characters before the program crashes?
you can do it i(in some cases) but this results in 'Undefined Behavior'. UB can produce many results, including seeming to work most of the time until your biggest customer tries to run your app on their busiest day. You must not do this. There are various tools that you can use to detect it (electric fence, valgrind, for example)
Reading in a key file, I pass the data toPEM_read_bui_RSAPrivateKey, and am rewarded with: error:0906D06C:lib(9):func(109):reason(108) I was able to look up lib 9 (PEM, makes sense), but wasn't able to find anything about thefuncorreason. I'm guessingfunc(109)isPEM_read_bui_RSAPrivateKey(), but it could just as easily be some internal thing. What am I doing wrong?
I was using the public key file instead of the private key file. Based on my searches, this is one of several different things that can cause this particular error, but I didn't see any of them mention this particular cause.
I have code here which works as a countdown timer but it prints results on a new line like this: ``` 10 9 8 7 6 5 4 3 2 1 ``` here is my code: ``` int timer() { int count; count = 10; while(count != 0) { printf("Time: \t%d \n", count); count--; sleep(1); } printf("\nCount down timer has expired\n"); return 0; } ``` what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense
Try changingprintf("Time: \t%d \n", count);toprintf("Time: \t%d \t", count);
Why both inner printf() functions are working different even the printing value is same for both functions ? Here is the code -: ``` #include<stdio.h> int main() { char ch = '\0'; printf("%d",printf("%c", ch)) ; // This line will print 1. printf("%d",printf("\0")) ; // This line will print 0. return 0; } ```
printf("%d", printf("%c", '\0'));Why this line prints 1? The value'\0'is one single character, which"%c"sends th stdout (though you can't see it). printf("%d", printf("%s", "\0"));Why this line prints 0? The string"\0"has two characters in it: the literal'\0'and the implied'\0'. None of them are printed with"%s", the first zero terminates the string. The string"foo"has 4 characters: the 3 literal ones and the implied'\0'
I am relatively new in C and found the code ofthis question. How do you pass the argumentdouble (*f)(double)of the function and how does the pointer works out in this? Here's the function: ``` double derivative(double (*f)(double), double x0, int order) ``` My guess was that first you need something like: ``` #include<stdio.h> #include<stdlib.h> #include<math.h> double f(double x){ return pow(x,2); } int main(){ double x = 2; int order = 2; derivative(f(x), x , 2); } ``` I tried it but it didn't work. Thanks for the help.
double (*f)(double)is a function pointer. It means you need to pass a pointer to (or just the name of) a function. In your attempt, you're calling the function, then passing the return value, which isn't correct. The correct way would be: ``` derivative(f, x, 2); ```
This question already has answers here:Is there a convention for pointer declarations in C? [closed](8 answers)Closed3 years ago. I am following a C tutorial for a Linked List and I am building the node. However, I do not understand why the * operator comes at the end of the node variable versus in front of it. I thought pointers came in front of the word. So which is the pointer? "next" or "node"? ``` struct node { int value; // next pointer, should point to the next node in the list struct node* next; // pointer of structure type }; ``` Thank you.
struct nodeis the type so it comes in front of that, likeint* num, only in this case typeintis only one word. Another hint to this is that variable names can only have one word. Sostruct node*(pointer to struct node) is the type, andnextis the name of the variable. See here
I was trying to do substitution from cs50 pset2 on two loops but I had some issues. I found one loop solution here:free(): invalid pointer Aborted (core dumped) cs50 But now I don't really understand this part: ``` int x = plaintext[i] - 'a'; ``` Ifplaintext[i]is'm','m'is 109 in ASCII, and'a'is 97, som-a == 12, form feed in ascii. Or it's not an ASCII substraction going on?
Look at the next line: ``` printf("%c", tolower(key[x])); ``` x is used as an index into the key array.
I am trying to write a recursive descent parser in C and have the following problem with the availability of my methods, since C uses a top down compiler: ``` void a(){ b(); } void b(){ c(); } void c(){ a(); } ``` How can I work around this problem so I can call all methods where I need them? I could not come up with an elegant solution, since I am rather new to C.
This is normally solved with function prototypes: ``` void a(void); void b(void); void c(void); //^function prototypes void a(void){ b(); } void b(void){ c(); } void c(void){ a(); } ``` You could also use old-style declarations (without thevoidin the parens) which would declare the functions as taking an unspecified number of promoted arguments, but those are deprecated and they result in weak typechecking and slightly worse codegen, so better put thevoidin there if the function takes no arguments.
I want to know what is the difference between these two lines : ``` queue* f=(queue*)malloc(sizeof(queue)); ``` ``` queue* f=(queue*)malloc(sizeof(queue*)); ``` Here's the definition of queue: ``` typedef struct queue { int arr[N]; int tail; }queue; ``` Thanks in advance!
The difference is that the second line is wrong; it allocates enough space to store apointerto aqueue, not aqueueitself, but it's assigned to a type that assumes it points to enough space for a wholequeue. Neither one requires a cast, so the correct form is: ``` queue *f = malloc(sizeof(queue)); ``` To be even safer, don't refer to the type itself, refer to the variable you're assigning to, to avoid repeating the type (potentially causing maintenance problems if the type is changed); this also meanssizeofdoesn't need parentheses: ``` queue *f = malloc(sizeof *f); ```
This question already has answers here:Is floating point math broken?(33 answers)Closed3 years ago. why the following snippet ``` int i = 30; int p = 0.7f * i; printf("p is %d\n", p); ``` gives 20 instead of 21 on vc++ 2008 express ? I know it's an old compiler!
The number 0.7 is not representable in the binary-based floating-point format your compiler uses forfloat. When the decimal numeral “0.7” is converted tofloat, the result is the nearest representable value. That is a number slightly below 0.7. Multiplying that by 30 produces a number slightly below 21, and converting it tointwith truncation produces 20.
I am attempting to get an output of: ``` Score: 0 ``` but my output keeps coming out like ``` Score: 0 ``` this is what I have implemented: ``` move_cursor(30,4); printf_P(PSTR("Score : %8d\n"), get_score()); move_cursor(37, 8); ``` we are writing the score in Putty, from AVR to serial. What am I doing wrong?
Q: If you want "0" on a separate line ... then shouldn't you put a matching `\n' in your format statement? Q: If You want it right-aligned at column 6, then shouldn't your format statement be%6? EXAMPLE:printf_P(PSTR("Score :\n%6d\n"), get_score()); PS: As you're probably aware, "printf_P()" isn't standard C; it's AVR-specific.
In C# I can do the following: ``` Console.Write("{0}, ", string.Format("{0:0.00###########}", someFloatValue)); ``` to get at least 2 decimal places for some arbitrary float value up to some certain number of optional decimal places, in this case 13. I was wondering if the same was possible with printf in C?
Lop off trailing zero digits. ``` void formatDouble(char* buf, double val, int precMin, int precMax) { int length = sprintf(buf, "%.*f", precMax, val); if (isfinite(val) && length > 0) { for (int i = precMax; i > precMin; i--) { if (buf[length - 1] == '0') { buf[--length] = '\0'; } else { break; } } } } void fooo(double d) { char buf[100]; formatDouble(buf, d, 2,6); printf("<%s>\n", buf); } int main(void) { fooo(0.1234567890); fooo(0.123450); fooo(0.12300); } ``` Output ``` <0.123457> <0.12345> <0.123> ```
I want to make struct global I tried something but I got an error. ``` struct data{ int barcode; char product_name[50]; char category[50]; float price; }; void printer(){ struct data *data1=(struct data*)malloc(sizeof(struct data)); } int main() { struct data *data1=(struct data*)malloc(sizeof(struct data)); return 0; } ``` "error:initializer element is not constant" ``` struct data{ int barcode; char product_name[50]; char category[50]; float price; }; struct data *data1=(struct data*)malloc(sizeof(struct data)); ```
You can't callmallocoutside a function context. If you want a single structure, declare it as a global variable. If you want multiple structures, make an array. ``` struct data data1; struct data dataN[12]; ```
I want to make struct global I tried something but I got an error. ``` struct data{ int barcode; char product_name[50]; char category[50]; float price; }; void printer(){ struct data *data1=(struct data*)malloc(sizeof(struct data)); } int main() { struct data *data1=(struct data*)malloc(sizeof(struct data)); return 0; } ``` "error:initializer element is not constant" ``` struct data{ int barcode; char product_name[50]; char category[50]; float price; }; struct data *data1=(struct data*)malloc(sizeof(struct data)); ```
You can't callmallocoutside a function context. If you want a single structure, declare it as a global variable. If you want multiple structures, make an array. ``` struct data data1; struct data dataN[12]; ```
I am currently writing a program that will read a file according to a user given buffer, will write that to an output file, and will continue doing that until the file is done. However, right now my output file has extra characters then it should have when compared to the original file. I think it has something to do with how read and write do not always return the number of bytes that is requested. I am unsure how to fix this. Right now I just have a simple while loop: ``` while(read(inFD, buff, buf)!= 0) write(outFD, buff, buf); ``` buf is the user given buffer. Thanks if you can help!
readmanual reads: "On success, the number of bytes read is returned". You are ignoring the number returned; instead you are assumingbufbytes were read. In result, your output file size will be a multiple ofbuf.
I am currently writing a program that will read a file according to a user given buffer, will write that to an output file, and will continue doing that until the file is done. However, right now my output file has extra characters then it should have when compared to the original file. I think it has something to do with how read and write do not always return the number of bytes that is requested. I am unsure how to fix this. Right now I just have a simple while loop: ``` while(read(inFD, buff, buf)!= 0) write(outFD, buff, buf); ``` buf is the user given buffer. Thanks if you can help!
readmanual reads: "On success, the number of bytes read is returned". You are ignoring the number returned; instead you are assumingbufbytes were read. In result, your output file size will be a multiple ofbuf.
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element. ``` int main() { int array[10] = {1, 2, 0, 3, 4}; printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array int i = 0; while(array[i] != 0 && i < 10) { i++; }; printf("%d\n", i); return 0; }``` ```
You can't.int array[10]will always create an array of 10 elements and you can't ask the compiler which of them have been assigned. What you could do isint array[] = {1, 2, 0, 3, 4}then the compiler will infer the number of elements for you and you'll havesizeof(array)/ sizeof(*array) == 5
This question already has answers here:Client-server synchronization pattern / algorithm?(7 answers)Closed3 years ago. asdfg askjhgkasdhj gfskjd;hdgfk ;jasgdjkf hasdjkghf asdjkf hasdjkfgh klasdhdf jkasdjkf hdjksahf jklhdjkf asjkdhdf jkdlf ajsdhf jklashdf jaksdf hkjlasdjklf hasdhdf kdf kjlasdhdf hkjadf ljkdf adf kjahdkf adf kjashdfhkjlsasdf ``` else { printf("[-]Invalid command\n"); } } bzero(buffer, SIZE); } } ```
You have a couple of issues: ``` -Don't close sockfd, this will prevent further connections from being accepted on the server -The socket should be closed on both ends in the quit case -The fact that the client side uses a random port is fine. Nothing needs to be changed there ```
I have this code work : ``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { FILE *File_fp = fopen("Example.dat", "w"); char Temporary[50]; if(!File_fp) { printf("An error occurred while creating the file.\n"); exit(1); } fprintf(File_fp, "This is an example.\n"); fgets(Temporary, 49, File_fp); printf("It was \"%s\"\n", Temporary); return EXIT_SUCCESS; } ``` I printed "This is an example." in the file, "Example.dat" and I want to read it again from the file by code above but there's no string in the output. Why? Please help me.
You are opening the file in write-only mode ("w"). Use "w+" for reading and writing. ``` FILE *File_fp = fopen("Example.dat", "w+"); ```
I have a C file with macros, to compile it I use gcc file.c -D and the (macro of the portion of code I want to compile). I am writing to ask you how I can get a makefile to manage conditional compilation, in order to compile the makefile deciding whether to create the first file or the second (the two MACROs of the file c)
You can call aMakefilewith a parameter: ``` make action argument=something ``` Then yourMakefilecan take and propagate this parameter: ``` CC = gcc CFLAGS += -std=c11 -pedantic -Wall action: $(argument) $(CC) $(CFLAGS) $(argument) -o demo clean: rm -f demo ``` Say you have two files:file1.candfile2.c, you can call ``` make action argument=file1.c ``` or ``` make action argument=file2.c ``` to decide whether to create the first file or the second .
Is there a function to stretch an image's points to coordinates on the screen based on it's four points? If not, is there a way I could do that using math?
I mean something like a generalized texture-mapped quad. SDL_RenderGeometry()/SDL_RenderGeometryRaw()were added inSDL 2.0.18.
Consider my attempt to implement the Babylonian method in C: ``` int sqrt3(int x) { double abs_err = 1.0; double xold = x; double xnew = 0; while(abs_err > 1e-8) { xnew = (2 * xold + x/(xold* xold))/3; abs_err= xnew-xold; if (abs_err < 0) abs_err = -abs_err; xold=xnew; } return xnew; } int main() { int a; scanf("%d", &a); printf(" Result is: %f",sqrt3(a)); return 0; } ``` Result is for x=27: 0.0000? Where is my mistake?
While the function returns anint, that value is printed with thewrong format specifier,%finstead of%d. Change the signature (and the name, if I may) into something likethis ``` double cube_root(double x) { ... } ``` Or change the format specifier, if you really want anint.
So lets say I have my main file: main.c, linked with file1.c and file2.c where file1 and file2 include their header files: file1.h, file2.h I compiled them together like so: ``` gcc main.c file1.c file2.c ``` which creates the./a.outexecutable to be run. In GDB how do I set a break point in my main.c? I've tried ``` b main.c ``` which gave me this output: ``` Make break-point pending on future shared library load? yes or no ``` to which I respondedyesbut it never sets a break-point anywhere even after I sayb 232: the line number, I even triedb main 232andb main.c 232but non of these work either..
What you want is the following (seeGDB doc): ``` break main.c:232 ``` And don't forget to compile with-g, otherwise line number information will not be present in the generated program.
can someone please convert this line: strcpy_s(this->name, SIZE_NAME, d.getName()); to a strcpy function instead of strcpy_s? thank you
``` strcpy(this->name, d.getName()); ``` That was easy
I don't understand what I am doing incorrectly I have searched several online references and still can't figure out what i am doing wrong. Here's my Code ``` #include <cs50.h> #include <stdio.h> int x = 5; int y=get_int("ENTER DIGIT HERE\n"); if (x>y) { printf("HI\n"); }else{ printf("BYE\n"); } ```
Basically you want this: ``` #include <cs50.h> #include <stdio.h> int main(void) // <<<< your code must be in the main function { int x = 5; int y=get_int("ENTER DIGIT HERE\n"); if (x>y) { printf("HI\n"); } else { printf("BYE\n") } } ```
I am writing a simple C program to test my own colorscheme if it works or not. And I want to change the color of variable and format specifier(%d,%s.%f,...). How should I do it? I did try to configure the vim Identifier but it has no effect on the real Identifier(variable name) in my C code. Also which option should I use along with :hi for changing the color of format specifier.
I want to change the color of variable and format specifier The group for format specifiers is calledcFormat. Normally it's linked tocSpecialChar(which includes\n,\rand such). You can't change variable highlight, as it's justNormal.
I found this structure in the slides of my professor: ``` struct point{ int x; int y; } p; ``` What does p mean? So far I used only the classical struct like this: ``` struct point{ int x; int y; }; ```
``` struct point{ int x; int y; } p; ``` defines a variablepof typestruct point it is same as ``` struct point{ int x; int y; }; struct point p; ```
If I have the follow code " *k != (Queue *)0 * ", there is a violation of the rule 11.9. But why ? Qich can I rewrite thise code for make it compliant to MISRA 11.9?
You have to use the Keyword "NULL" to make it compliant: ``` *k != NULL ```
Can anyone explain the meaning of the code and give an example how to use it? I can understandfoo[100], but notbar. ``` typedef struct{ int a,b; } CELL, *PCELL; CELL foo[100]; PCELL bar(int x, CELL y); ```
``` PCELL bar(int x, CELL y); ``` is a function declaration. It means thatbarwill take in anintand aCELLas parameters, and it will return a pointer to aCELLas a return value. The actual body of the function will be defined later.
I'm writing a header file in C and needstdlib.hfor it to work. But, when I check if_STDLIB_His defined, the pre-processor says it's not, even if I include the file. I have tried it on multiple compilers, where it works on most but not ontdm-gcc. How can I fix this?
Looking atstdlib.hsource code, it seems like the macro to look for in tdm-gcc might be_TR1_STDLIB_H.So you can try something like: ``` #if defined _STDLIB_H || defined _TR1_STDLIB_H ```
I'm using an efm32lg230f256 microcontroller and in its code there is a line which usesUSART_Rxand it returns: 1 2 3 4 but when I look inside of it I can't see how it retuns1 2 3 4. I tried to look in thedata sheetbut there are no such names. What is the logic in this function? And why does it do this? ``` c = USART_Rx(uart); ``` ``` uint8_t USART_Rx(USART_TypeDef *usart) { while (!(usart->STATUS & USART_STATUS_RXDATAV)) ; return (uint8_t)usart->RXDATA; } ```
"1 2 3 4" is simply the device password
Imagine I have a simple program that prints out hello, world to the terminal when executed. Usually, you would type in the terminal ./a.out or whatever the name and extension (or not) of the program. I want to create an executable file that, when clicked, will open the terminal and run the program. I'm using windows and linux subsystem for windows and the debian terminal from the windows store. How can I make my program open the debian terminal and run the hello world program, when I click on the executable?
You can simply create.batfile with startup of your app via wsl: ``` wsl NEEDED_DIR/a.out ```
``` char em[] = {'no','yes','maybe','kinda','btw'}; for (int k = 0;k<2;k++){ printf("%c", em[rand()%5+1]); } ``` This code should print in output"no","yes","maybe","kinda"or"btw". But when I run it, it prints one single characters for example'o'or'k'ecc... Why?
You've gotemdeclared as an array of characters and yet you've got what look like Python-style strings in its definition. In C, character strings require double-quotes. Single quotes areonlyfor individual characters. What you want is ``` char *em[] = {"no","yes","maybe","kinda","btw"}; ``` That will makeeman array of character pointers. Finally, you need to use%sinstead of%cto print out strings.
I'm new in C. Here is my code: ``` int *i = (int *)calloc(10, sizeof(int)); i[0] = 3; i[1] = 1; i[2] = 2; i[3] = 5; printf("before: %d %d %d %d\n", i[0], i[1], i[2], i[3]); printf("before: %d %d\n", i, (i + 3)); free(i); printf("after: %d %d %d %d\n", i[0], i[1], i[2], i[3]); printf("after: %d %d\n", i, (i + 3)); ``` and output: ``` before: 3 1 2 5 before: 3 5 after: 0 0 2 5 after: 0 5 ``` I usedfree()func. Why are not all elements of the array zero?
The data in memory maybe doesn't disappear, they can exist in the memory afterfreeing. But try to read from the freed memory is undefined behavior. To be sure, you can assign the pointer toNULLafterfreeing it (Setting variable to NULL after free).
``` int ln; printf("how many letters are your name?\n"); scanf("%d", &ln); printf("Ok...enter your name by characters: \n"); char name[ln]; for (int i = 0; i<=ln; i++){ scanf("%s", &name[i]); } ``` This code should transform a name in the array but the for-loop never ends. Someone who can help me?
%s is scanning string so technically your whole name is considered as one element. So have to enter many strings . just replace %s by %c and code should be ready to use
I'm writing a header file in C and needstdlib.hfor it to work. But, when I check if_STDLIB_His defined, the pre-processor says it's not, even if I include the file. I have tried it on multiple compilers, where it works on most but not ontdm-gcc. How can I fix this?
Looking atstdlib.hsource code, it seems like the macro to look for in tdm-gcc might be_TR1_STDLIB_H.So you can try something like: ``` #if defined _STDLIB_H || defined _TR1_STDLIB_H ```
I'm using an efm32lg230f256 microcontroller and in its code there is a line which usesUSART_Rxand it returns: 1 2 3 4 but when I look inside of it I can't see how it retuns1 2 3 4. I tried to look in thedata sheetbut there are no such names. What is the logic in this function? And why does it do this? ``` c = USART_Rx(uart); ``` ``` uint8_t USART_Rx(USART_TypeDef *usart) { while (!(usart->STATUS & USART_STATUS_RXDATAV)) ; return (uint8_t)usart->RXDATA; } ```
"1 2 3 4" is simply the device password
Imagine I have a simple program that prints out hello, world to the terminal when executed. Usually, you would type in the terminal ./a.out or whatever the name and extension (or not) of the program. I want to create an executable file that, when clicked, will open the terminal and run the program. I'm using windows and linux subsystem for windows and the debian terminal from the windows store. How can I make my program open the debian terminal and run the hello world program, when I click on the executable?
You can simply create.batfile with startup of your app via wsl: ``` wsl NEEDED_DIR/a.out ```
``` char em[] = {'no','yes','maybe','kinda','btw'}; for (int k = 0;k<2;k++){ printf("%c", em[rand()%5+1]); } ``` This code should print in output"no","yes","maybe","kinda"or"btw". But when I run it, it prints one single characters for example'o'or'k'ecc... Why?
You've gotemdeclared as an array of characters and yet you've got what look like Python-style strings in its definition. In C, character strings require double-quotes. Single quotes areonlyfor individual characters. What you want is ``` char *em[] = {"no","yes","maybe","kinda","btw"}; ``` That will makeeman array of character pointers. Finally, you need to use%sinstead of%cto print out strings.
I'm new in C. Here is my code: ``` int *i = (int *)calloc(10, sizeof(int)); i[0] = 3; i[1] = 1; i[2] = 2; i[3] = 5; printf("before: %d %d %d %d\n", i[0], i[1], i[2], i[3]); printf("before: %d %d\n", i, (i + 3)); free(i); printf("after: %d %d %d %d\n", i[0], i[1], i[2], i[3]); printf("after: %d %d\n", i, (i + 3)); ``` and output: ``` before: 3 1 2 5 before: 3 5 after: 0 0 2 5 after: 0 5 ``` I usedfree()func. Why are not all elements of the array zero?
The data in memory maybe doesn't disappear, they can exist in the memory afterfreeing. But try to read from the freed memory is undefined behavior. To be sure, you can assign the pointer toNULLafterfreeing it (Setting variable to NULL after free).
``` int ln; printf("how many letters are your name?\n"); scanf("%d", &ln); printf("Ok...enter your name by characters: \n"); char name[ln]; for (int i = 0; i<=ln; i++){ scanf("%s", &name[i]); } ``` This code should transform a name in the array but the for-loop never ends. Someone who can help me?
%s is scanning string so technically your whole name is considered as one element. So have to enter many strings . just replace %s by %c and code should be ready to use
I'm new in C. Here is my code: ``` int *i = (int *)calloc(10, sizeof(int)); i[0] = 3; i[1] = 1; i[2] = 2; i[3] = 5; printf("before: %d %d %d %d\n", i[0], i[1], i[2], i[3]); printf("before: %d %d\n", i, (i + 3)); free(i); printf("after: %d %d %d %d\n", i[0], i[1], i[2], i[3]); printf("after: %d %d\n", i, (i + 3)); ``` and output: ``` before: 3 1 2 5 before: 3 5 after: 0 0 2 5 after: 0 5 ``` I usedfree()func. Why are not all elements of the array zero?
The data in memory maybe doesn't disappear, they can exist in the memory afterfreeing. But try to read from the freed memory is undefined behavior. To be sure, you can assign the pointer toNULLafterfreeing it (Setting variable to NULL after free).
``` int ln; printf("how many letters are your name?\n"); scanf("%d", &ln); printf("Ok...enter your name by characters: \n"); char name[ln]; for (int i = 0; i<=ln; i++){ scanf("%s", &name[i]); } ``` This code should transform a name in the array but the for-loop never ends. Someone who can help me?
%s is scanning string so technically your whole name is considered as one element. So have to enter many strings . just replace %s by %c and code should be ready to use
When we execute the following code: ``` #include <stdio.h> int main(void){ char x,y; scanf("%c", &y); x = getchar(); putchar(x); return 0; } ``` The enter that is being inputted in thescanf("%c", &y);statement is passed on to x. Is there some way to get away with this? I now that if we are usingscanfthen we can ignore the\nbyscanf("%*c%c", &x);but don't know what do while usinggetchar().
You can do something like this ``` #include <stdio.h> int main(void) { char x,y,ch; scanf("%c%*c", &y); while((ch=getchar())!='\n'&&ch!=EOF); //removes all character in input buffer x = getchar(); putchar(x); return 0; } ```
For my C project, I had to check the format of 2 files and had to pass them as cmd line args. Depending on which files were passed, different functions were supposed to be invoked for which I had to compare something like this : ``` if(argv[1] == "file.txt") { func1(); }else{ func2(); } ``` But this doesn't seem to work. Can anyone help me out with this?
You want to compare 2 strings but you are comparing char * instead. Use strcmp instead of == operator.
For my C project, I had to check the format of 2 files and had to pass them as cmd line args. Depending on which files were passed, different functions were supposed to be invoked for which I had to compare something like this : ``` if(argv[1] == "file.txt") { func1(); }else{ func2(); } ``` But this doesn't seem to work. Can anyone help me out with this?
You want to compare 2 strings but you are comparing char * instead. Use strcmp instead of == operator.
I want to change the orientation of contents on ili9325 display. according to the datasheet I should change the AM and ID0 and ID1 registers to change the orientation of GRAM data. but when I change these registers and display some data on the LCD, it won't change the orientation. datasheet
It is usually aninitproblem. When you initialize these LCDs in a wrong way, sometimes they won't work correctly. So, check your initialization process and then rotate the lcd again. that should work. (read the initialization process from the datasheet)
See this answer I understood it except for the last statement. the conversion specifier "%d" skips optional leading whitespace and (tries to) converts the rest of the input to integer (if no errors occur). I understood the point regarding theoptional whitespace. But what does"converts the rest of the input to integer"means? I mean why will it convert the input to integer if the input itself is an integer?
The input itself is an integer? No, the input from key board is string(ascii), So the scanf Convert it to integer and store it in the variable. See this: ``` #include <stdio.h> int main() { char cnum[] = "123"; int num = 0; int i=0; while(cnum[i]) { num*=10; num+= cnum[i]-'0'; i++; } printf("%d",num); //This also converts int to string to print return 0; } ``` Thanks.
In the visual studio code, as soon as I type thepr... it shows meprintfand soon as I hitenterit just writesprintfas a normal variable but it doesn't auto complete likeprintf(""). Can you please help me to how to add this auto complete feature in visual studio code windows edition.
I figured out a way, and this worked for me. Try doing this: Go toFile > Preferences > User Snippets, type in (c.json) There you can create your own snippets. For example : ``` "printf": { "prefix": "print", "body": ["printf(\"$1\",$2);", "$3"], "description": "Printf statement" }, "include": { "prefix": "include", "body": ["#include<$1>", "$2"], "description": "Include Statement" } ``` You will even find the instructions in thec.jsonfile in the form of comments, follow them and customize the way you want, and you are set ready. Thank You :)
i know that -> is a pointer |= is OR. what is the logical meaning of such line? TIMER0->ROUTELOC0 |= TIMER_ROUTELOC0_CC0LOC_LOC15
|= does not mean OR. | means OR. |= is similar to +=, that is A |= B is the equivalent of A = A | B So to answer your question: It looks likeTIMER0is a structure with a memberROUTELOC0. The above expression is setting theROUTELOC0as the result whenROUTELOC0is ORed withTIMER_ROUTELOC0_CC0LOC_LOC15