question
stringlengths
25
894
answer
stringlengths
4
863
This must be a simple problem about char data type and pointers. ``` void main() { const char* a; char character = 65; a = &character; printf("%c \n", character); // PRINTS 'A' AS EXPECTED if (strstr("ABC", a)) { printf("found \n"); } else { printf("not found\n"); // goes into else } } ``` I don't understand why it doesn't go into first if statement.
You need to null terminate theastring so that it's a proper C string before calling strstr: Any of the following: ``` if (strstr("ABC", "A")) { // found } ``` Or ``` char a[2] = {'A', '\0'}; if (strstr("ABC", a)) { // found } ``` Or ``` const char* a = "A"; if (strstr("ABC", a)) { // found } ```
This question already has answers here:What is the difference between NULL, '\0' and 0?(11 answers)Closed2 years ago. ``` #include <stdio.h> int main(){ int *p = '\0'; if (p == NULL){ // this block will get executed. } return 0; } ``` I have read that0,NULLand\0are all equal to the integer constant0in C. So is the above code technically correct in setting and checking for a NULL pointer? I guess it still needs to be avoided as\0is mainly used to terminate strings and its usage here is confusing?
'\0'is an integer zero. All three do exactly the same. ``` int *p = NULL; int *p = 0; int *p = '\0'; ``` but the last two may emit the warning.
I have a question regarding the CreateThread API in windows (C/C++) that MSDN of the API doesn't explain. If i use this API to create multiple threads that execute a function (all of them execute a common function), will Windows automatically spread these threads across different cores? specially if the function is CPU intensive?
Most operating systems internally treat processes and threads as a specialization of more general "tasks". By default tasks have no fixed association with particular cores. In general the OS will try to reschedule tasks on the same core in the short term, to aid with cache coherence, but will cycle them over all associated cored in the long term to distribute the thermal load. It is however possible to limit the set of cores a given task may run on using the so called "CPU affinity mask", which can be set either at runtime using a system call, or as part of the executable binary at link time.
1- I got how to find the numbers, I just don't know how to link that to a sum for loop ``` #include <stdio.h> #include <conio.h> int main () { int count, sum=0, i; for (count=1;count<125;count=count+2) if(count%5 != 0) { //non multiple of 5 printf ("%d \t ",count); } for (i = 0; i<=count; i++) sum = sum + count; printf("Sum= %d \t" , sum); return(0); } ```
A single loop seems to suffice, here's a solution I threw together: ``` #include <stdio.h> int main(void) { int sum = 0; for (int i = 1, hits = 0; hits < 50; i += 2) { if (i % 5 != 0) { sum += i; ++hits; } } printf("Got sum %d\n", sum); return 0; } ``` The result is 3124.
I want to create 5 variables whose value will be user inputted and all variable will have thesame value, is there a way to directly assign values to all the 5 variables from scanf() instead of the regular way ``` int var1, var2, var3, var4, var5; scanf("%d", &var1); var2 = var3 = var4 = var5 = var1; ```
is there a way to directly assign values to all the 5 variables from scanf() instead of the regular way No there isn't. You have to assign to each of the variables where you want to copy the value, just like in your current code. I'm not sure what the rest of your code is like, but often when you have several variables and want to perform some common operation on them, what you really need is an array and a loop.
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.Closed2 years ago.Improve this question can I use post-increment in a function return in C like this? ``` int meta_solve() { //some codes return metaData[head++]; //head is global variable } ``` I asking this question because it showing the different results on windows and mac. thanks for your attention. have a great day!
Yes, that will work. The return will not happen until the expressionmetaData[head++]is fully evaluated so the (global) variableheadis incremented before the function returns.
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.Closed2 years ago.Improve this question When I implement my code, my function does not work. However, I don't know the reason why. Can you tell me some problems and how to solve it? Here's my code! And I'm using language C!
You are calling the function in wrong way: try this: findMin(n,arr); findMax(n,arr); Whenever you are calling function: in function just pass the array name;
``` #include <stdio.h> int main() { int a; float b; char ch; scanf("%d%f%c",&a,&b,&ch); printf("%d %f %c",a,b,ch); return 0; } ``` whenever I run above code its takes only two inputs and terminates why is that? I want to input :2,3.5,d.but its terminates after 3.5. here is image of when I run the code:https://i.stack.imgur.com/ef6CE.png
Include spaces informatstring. Otherwise any whitespace character (spaces, newline and tab characters) will be read into your variables. So, include a space before%clike this: ``` scanf("%d%f %c",&a,&b,&ch); ```
``` #include <stdio.h> int main() { int a; float b; char ch; scanf("%d%f%c",&a,&b,&ch); printf("%d %f %c",a,b,ch); return 0; } ``` whenever I run above code its takes only two inputs and terminates why is that? I want to input :2,3.5,d.but its terminates after 3.5. here is image of when I run the code:https://i.stack.imgur.com/ef6CE.png
Include spaces informatstring. Otherwise any whitespace character (spaces, newline and tab characters) will be read into your variables. So, include a space before%clike this: ``` scanf("%d%f %c",&a,&b,&ch); ```
On the basis ofshutdown vs closeI have known the difference between shutdown and close. But which will choose if select timeout in socket, the client will close or shutdown(sock, SHUT_WR). I try to read the source code of select.c, but it is too hard to read. Can anyone give me some help.
But which will choose if select timeout in socket, the client will close or shutdown(sock, SHUT_WR). If the client has a call toselect(), the client can decide what to do when that call times out. Almost by definition, if yourselect()times out, it's telling you thatnothinghappened to the socket (nothing that you toldselect()you were interested in, anyway). Sockets don't automatically close (or shutdown) just because nothing happened for a while. You have to do that yourself, if you want it.
how to find the sum of all column and row in 2d 4x5 arry I did this but it's not working ``` for (j = 0; j < M; j++) { for (i = 0; i < N; i++) { summ = summ + arr[i][j]; } printf("the sum of the amoda is:%d\n", summ); } ```
Your question is very ambiguous. Do you want to find the sum of each column? If so, you should initializesummto 0 for each of them: ``` for (j = 0; j < M; j++) { summ = 0; for (i = 0; i < N; i++) { summ = summ + arr[i][j]; } printf("the sum of the column is: %d\n", summ); } ``` If you want to find the sum of all numbers, then take that print out of the loop.
An acquaintance of mine claims that any program compiled with the MSVC compiler is JIT compiled, as it is using the Visual C runtime, and that compilation with the GCC toolchain on Windows makes a fully AOT compiled output. Is this true?
Despite very similar names C,C++ and C# are not the same languages. C & C++ are compiled languages and the compiler generatrates the machine level code. C# is generally compiled and interpreted (or better said JIT compiled) language at the same time. C# code is compiled to the special IL format which JIT compiled to the machine code. As it is JIT compiled you may dynamically runtime create assemblies - so the code may modify itself runtime. (Reflection emit) So I believe that you have asked about theC#.
It is known and useful features that: consttype qualifier prohibits writing (modification) of a variableregisterstorage-class specifier prohibits taking address of a variable However, is there a standard way to prohibit reading (via assignment) of a variable? For example, for such variable only writing and/or taking address is permitted. Reason of the question: need to conditionally prohibit reading (via assignment) of some variable. Does the language provide any way to do it? If no, then why? UPD. Readers may be interested as well:C: check at compile time or at run time that variable has static storage-class specifier.
No, not as far as I know. I don't know why, one reason might be that it's something that is only fantastically rarely useful. You (in my opinion) don't actually explainwhyyou want this, which further emphasizes that's a rather convoluted/weird thing to want.
This question already has answers here:Strict ISO C Conformance Test(5 answers)Closed2 years ago. Is there any C compiler able to detect* the violation of a "strictly conforming program"? * under some option, for example,--accept-only-strictly-conforming-program If no, then which tools to use to detect the violation of a "strictly conforming program"? Informative (C11, 4. Conformance, p5): A strictly conforming program shall use only those features of the language and library specified in this International Standard.3) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit.
Buffer overflow is undefined behavior.Therefore, this compiler must detect every possible buffer overflow in every possible program.Sounds too hard or impossibleSounds that such compiler does not exist :'(
Like ``` pri ntf("hi"); ``` I can use \ in macro but I think that doesn't work here :'(
You can use\ ``` pri\ ntf("hi"); ``` Demo From draft N1570 of the C standard, section 5.1.1.2 Translation phases: Each instance of a backslash character ( \ ) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines.
I encountered some problems when using M93C46. I can read data in 93C46 through spi communication, but I cannot write data to 93C46. I checked the timing of my spi, but no problem was found. Here are the sequences pictures: Here is the code table and sequences pictures:
It looks like your D signal (what would be MOSI if this were SPI) is transitioning simultaneously with the rising edge of the clock. This would be SPI mode 1. These "microwire" parts are not SPI, they are a pain in the backside. You have to use a different clock edge when reading and writing. Write databeforethe rising edge of clock, the memory samples it on the rising edge (equivalent to SPI mode 0). However, the memory only outputs data on Q (equivalent to MISO)afterthe rising edge of the clock, so you have to read it on the falling edge of the clock (SPI mode 1).
``` #include<stdio.h> int main(){ char w[3]; scanf("%s",w); printf("%s\n",w); return 0; } ``` For example, if I give a string 'Goods' which has 5 characters. But my array will accommodate only 2 characters and a \0. I got output as 'Goods' why?
You will have input overflow the buffer you pass. This will invokeundefined behavior. This behavior could be nothing on the moment or crash the application much later. You could have segment violation and more adverse effects. To avoid that, you should usefgets()to read a string and thensscanf()to parse it.fgets()takes the size of the buffer as argument and prevent the buffer overflow.
I heard that if you run Nim to generate C-code:nim c -d: release try1.nimThen the further generated C code can be slipped into any compiler on any operating system. In the nimcache folder, the following is generated:@ mtry1.nim.cstdlib_io.nim.cstdlib_system.nim.ctry1.json What to do next with this for compilation?
You might want to try and runnim c -d:release --genScript try1.nim. This will generate acompile_try1script in the nimcache folder that should be able to compile the C sources generated by Nim.
I have two char pointer arrays: ``` char* mainMenu[] = {"Start", "Mode"}; char* subMenu[] = {"Mode1", "Mode2", "Mode3"}; ``` I put both arrays in an array containing pointer to pointer:char **menus[] = {mainMenu, subMenu}; Now I'd like to get the size of thesubMenuarray by usingmenus. WithsubMenuit works: ``` int num = sizeof(subMenu)/sizeof(subMenu[0]); // num = 3 ``` But I'd like to do this withmenus, i tried: ``` int num2 = sizeof(*(menus[1]))/sizeof(*(menus[1]))[0]; // num2 = 2 ``` What do i have to do with menus to get3as a result?
I was thinking about de-reference. Something likesizeof(*(menus[1]))/sizeof(*(menus[1])[0]). Why doesn't it work ? It doesn't work becausemenusis not an array of arrays but an array of pointers. Thesubmenuidentifier used to initializemenusis a taken as a pointer, not an array.
Lets say I have anexternfunction pointer in a header file ``` extern void (__stdcall * const glEnable) (GLenum cap); ``` is there a way to define it inside a function, because its definition depends on other stuff ``` void glInit() { ... Lib lib = loadLib("opengl"); glEnable = procAddr(lib, "glEnable"); ... } ```
You can do this: ``` // .h file extern void (__stdcall * glEnable) (GLenum cap); // .c file void (__stdcall * glEnable) (GLenum cap) = NULL; void glInit() { Lib lib = loadLib("opengl"); glEnable = procAddr(lib, "glEnable"); } ``` Now, the function pointer is null until someone callsglInit. It is undefined behavior to call that function pointer before callingglInit, and I assume that was your intention anyway.
I am trying to build TerraGear from the FlightGear project. I got no errors while compiling but while linking I'm getting undefined reference to multiple functions all starting withdns_and none of them is present in/usr/lib/x86_64-linux-gnu/libdns.so.1100. In which library are these defined ? Because, I googled fordns_init(that's one of these functions) and found no documentation.
Okay, I should do more research before asking here ;) : these functions come from libudns, and I just forgot to link it ! :@
How do I get the value from the Label that is in the StackPanel in the Button? ``` <Button Width="auto" Height="40" Click="GoAds" HorizontalAlignment="Left"> <StackPanel Orientation="Horizontal"> <Image Source="/Resours/Icons/Basket.png" Width="24" Height="24"/> <Label Content="Proc" FontSize="20" Foreground="Black"/> </StackPanel> </Button> ``` How to get the value of the Content property of the clicked button in the conditional variable x? I see it somehow, but something is missing ``` String X = (sender as Button).Content.ToString(); ```
Here you go: ``` String X = (((sender as Button)?.Content as StackPanel).Children[1] as Label)? .Content?.ToString(); ``` You need to cast theContentas aStackPaneland then access theLabelin theStackPanel'sChildrencollection.
I am trying to use a pointer to a structure as iterator in a for loop but it is giving me the error "error #20: identifier "z" is undefined" as if I have to declare it first than using it in the for loop and I don't know how to do that. ``` typedef struct { int id; double low; char *str; } Zone; ``` ``` void print_table(Zone zones[], int len, double hr_max) { for (Zone *z = zones; z < zones + len; z++) ```
Your compiler is from the stone age and therefore can't handle declarations inside aforloop. You need to enable C99 support or newer. Apparently this "CCS" thing is using a gcc version older than 5.0.0, when gcc was default set to-std=gnu90, so I guess your compiler is outdated by over 10 years. In general I would strongly recommend not to use dysfunctional Eclipse spawns provided by silicon vendors. These tools arehorrible.
``` int main(int argc, char* argv[]) { char file1 = argv[1]; char file2 = argv[2]; } ``` I am getting an error message here - initialization makes integer from pointer without a cast. file1 and file2 are the names of files. How can I approach to this?
argv[1]andargv[2]have the typechar *that point to strings while objectsfile1andfile2have the type char and are not pointers. So the compiler issues an error that you are trying to assign pointers (argv[1]andargv[2]) to characters (file1andfile2) that does not make a sense.. ``` char file1 = argv[1]; char file2 = argv[2]; ``` You need to write ``` char *file1 = argv[1]; char *file2 = argv[2]; ``` In this case the pointersfile1andfile2will point to the user supplied strings that denote file names.
I am using MSVC via ``` cl file.c ``` with this very simple code: ``` #include <stdio.h> #include <stdlib.h> int main(void) { int num = 50, pointNum = 60, max = 0; puts("Hello"); for (int i = 0; i <= num; i++) { printf("%d\n", pointNum % i); } return 0; } ``` but when I run it from the commandline, it just pauses and then crashes, only printing "Hello". I have no clue what is wrong, because it seems error free.
Wheni == 0, you perform the math60 % 0which triggers division by zero. That triggers undefined behavior which often will crash your program.
``` #include<stdio.h> main() { char path[]="\"set path=C:\\Program Files\\WinRAR\""; //the extension I want to path system(path); //the command system("UnRAR x filename.rar"); } ``` OUTPUT ``` 'UnRAR' is not recognized as an internal or external command, operable program or batch file. ``` it works when i try it myself in cmd
Every call tosystem()starts a fresh shell, and so things like environment variables don't carry over from one to the next. You need to include both commands in onesystem()call. According toHow do I run two commands in one line in Windows CMD?it looks like you can separate them by&, but I haven't tested this.
the linePrinting("testing ",H->Name)causes a compiler error: expected 'char *' but argument is of type 'char **' But i tried with many pointer-combinations, but I need help for this ``` struct header { char* Name[257]; ... }; void Printing(char * string,char * val) {printf("%s [%s]",string,val);}} int main () { struct header *head = malloc (sizeof(struct header)); func(header); } void func( struct header * H) { FILE * FP = fopen("test.t","r"); if (FP == NULL) {return 0;} fscanf(FP,"%s\n",H->Name); Printing("testing ",H->Name); fclose(FP); }``` ```
You should update your struct to following, ``` struct header { char Name[257]; ... }; ```
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed2 years ago. I saw such a piece of C code: ``` int main() { static int a[] = {7,8,9}; printf("%d", 2[a] + a[2]);; return 0; } ``` What does2[a]mean here?
a[b]andb[a]are 100% equivalent in C. What you have there is a very unidiomatic way of writinga[2]. By way of more complete explanation, array subscript notationa[b]is also 100% equivalent to*(a + b), which may make the reason it works both ways clearer.
I defined extern a in the scope and outside of the scope a.c ``` int a; void foo(void) { a = 3; } ``` b.c ``` extern int a = 10; /*same as "extern a; int a = 10?" */ void foo(void); int main(void) { foo(); printf("%d", a); } ``` Is this code well-defined?
This causes undefined behaviour in Standard C due to multiple definition ofa. There is a common extension for implementations to allow multiple definition so long as at most one is initialized. For more detail see:Is having global variables in common blocks an undefined behaviour? extern int a = 10;is the same asint a = 10;which is the same asextern int a; int a = 10;. Variable definitions have external linkage unless specified as static (or the identifier already declared as static in the same scope).
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed2 years ago. I saw such a piece of C code: ``` int main() { static int a[] = {7,8,9}; printf("%d", 2[a] + a[2]);; return 0; } ``` What does2[a]mean here?
a[b]andb[a]are 100% equivalent in C. What you have there is a very unidiomatic way of writinga[2]. By way of more complete explanation, array subscript notationa[b]is also 100% equivalent to*(a + b), which may make the reason it works both ways clearer.
I defined extern a in the scope and outside of the scope a.c ``` int a; void foo(void) { a = 3; } ``` b.c ``` extern int a = 10; /*same as "extern a; int a = 10?" */ void foo(void); int main(void) { foo(); printf("%d", a); } ``` Is this code well-defined?
This causes undefined behaviour in Standard C due to multiple definition ofa. There is a common extension for implementations to allow multiple definition so long as at most one is initialized. For more detail see:Is having global variables in common blocks an undefined behaviour? extern int a = 10;is the same asint a = 10;which is the same asextern int a; int a = 10;. Variable definitions have external linkage unless specified as static (or the identifier already declared as static in the same scope).
libcrypto3provides aPEM_read_bio_PrivateKeyas shown here https://www.openssl.org/docs/man1.1.0/man3/PEM_read_bio_PrivateKey.html I do not see aPEM_read_bio_PublicKey. ThereisaPEM_read_PUBKEY, but it expects aFILE*and not a BIO. Obviously algorithm-specific read functions exist, but why is there noPEM_read_bio_PublicKey?
It's actually calledPEM_read_bio_PUBKEY, listed in the same man page: ``` EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u); ```
I need to create a matrix with 2 columns and unknown number of rows. I know I have to use malloc but I can't find how to declare such matrix. it should hold integers in the first column and doubles in the second. How do I do that?
``` struct item { int i; double d; }; struct item matrix = malloc(sizeof(struct item) * number_of_rows) matrix[0].i = 544343; matrix[0].d = 0.3434343; ``` Is that the code you are looking for?
I am trying to learn how to use non-ascii (i.e., wide) characters in my C programs. I figured that I would start with a C program that writes hello, world in Chinese. Below is my program. It compiles fine but when I run it (from a Windows command line) I just get a blank line. I am thinking that either (a) my program is not correct, or (b) I have to do something to my Windows command screen for it to display Chinese. Do you know which is the case? ``` #include <wchar.h> int main() { wchar_t *helloworld = L"你好,世界"; wprintf_s(L"%s\n", helloworld); return 0; } ```
For long strings you have to use %S as opposed to %s.
I have a variable ``` char **data; ``` and I'm trying to print the content of the variable. I understand it to be array of arrays. How would I print it? Thanks
It's apointer to a pointernot array of arrays You need use**datato get value datawill give the memory address whichdatavariable holds*datawill give the memory address of the pointer whose addressdatais holding**datawill give you the actual value Say you have a variable like ``` char c = 'X'; char *cp = &c; //cp stores memory address of c char **cpp = &cp; //now cpp is pointer which points to a existing pointer cp ``` To get the value stored at the location which pointer points to - we need todereferencethe pointer. ``` printf("%c", *cp); //prints 'X' printf("%p", *cpp); //prints memory address of cp printf("%c", **cpp); //prints 'X' (double stars because address->address->value) ```
This question already has answers here:Is it necessary to multiply by sizeof( char ) when manipulating memory?(8 answers)Closed2 years ago. I'm learning C and I'm wondering what is the point ofsizeof(char) *100in ``` char *temp = (char*) malloc(sizeof(char) * 100); ``` I understand the sizeof(char) to be 1, so why we can't just writemalloc(100)? Thanks
There's no point to usingsizeof(char)in this case. The C standard definessizeof(char)to be 1, so better to just usemalloc(100). Also,don't cast the return value of malloc.
Why the loop goes on to infinity , I have put limits via n<6 , one more thing , the code prints 111111... . The output that I expect is 12345. ``` #include <stdio.h> //Compiler version gcc 6.3.0 int main() { int n=1; do{ while(n<6) printf("%d",n); n++; } while(n<6); return 0; } ```
Why this is an infinite loop? Because this: ``` do{ while(n<6) printf("%d",n); n++; } ... ``` Is actually this: ``` do{ while(n<6) { printf("%d",n); } n++; } ... ``` The code will never escape the "single statement while loop" just under thedo. I would suggest that deleting it so that you only have one line that sayswhile(n<6), just above thereturn, will make your program function as you expect
This question already has answers here:Is it necessary to multiply by sizeof( char ) when manipulating memory?(8 answers)Closed2 years ago. I'm learning C and I'm wondering what is the point ofsizeof(char) *100in ``` char *temp = (char*) malloc(sizeof(char) * 100); ``` I understand the sizeof(char) to be 1, so why we can't just writemalloc(100)? Thanks
There's no point to usingsizeof(char)in this case. The C standard definessizeof(char)to be 1, so better to just usemalloc(100). Also,don't cast the return value of malloc.
Why the loop goes on to infinity , I have put limits via n<6 , one more thing , the code prints 111111... . The output that I expect is 12345. ``` #include <stdio.h> //Compiler version gcc 6.3.0 int main() { int n=1; do{ while(n<6) printf("%d",n); n++; } while(n<6); return 0; } ```
Why this is an infinite loop? Because this: ``` do{ while(n<6) printf("%d",n); n++; } ... ``` Is actually this: ``` do{ while(n<6) { printf("%d",n); } n++; } ... ``` The code will never escape the "single statement while loop" just under thedo. I would suggest that deleting it so that you only have one line that sayswhile(n<6), just above thereturn, will make your program function as you expect
This code for example: ``` int x = 75; int *p = &x; printf("%llx\n",p); ``` Writes a 64-bit number. What I'm asking is, what exactly is this number? Yes, it is an address. But is it an absolute address in virtual memory where the value 75 is stored? Or is it possibly offset from some page marker, or an offset from the "start point" of the program's memory block? If it matters, I'm asking about Windows 10, 64 bit, on a typical x64 intel chip.
Yes, it is the absolute address in your program'svirtual address space. It is not an offset. In 16-bit Windows (which was common 30 years ago), asegmented memory modelwas used, in which pointers were segmented and consisted of a 16-bit segment pointer and a 16-bit offset (32 bits in total). However, 32-bit and 64-bit Windows both use aflat memory model, which uses absolute addresses.
I want to convert a string"12341234123412341234"to int, but when I use atoi it returns-1 ``` char n[100] = "12341234123412341234"; printf("%d",atoi(n)); ``` returns-1 if i use%ldor%lldit returns a junk value ``` char n[100] = "12341234123412341234"; printf("%lld",atoi(n)); //even if i use %ld it returns the same value ``` returns4294967295
The function you want isstrtol: ``` char n[100] = "12341234123412341234"; printf("%llu", strtoull(n, NULL, 10)); ```
I have some trouble chaining logical operators. I'm certain that I'm messing something up but I do not see it. I have tried various combinations of this (like adding parentheses around every "not equal to" operation etc.): ``` if (a != b && (a != EOF || b != EOF)) { /* Do stuff */ } ``` But nothing works.aandbare bits read from a file withfgetc, I can provide more code. But since this is about chaining logical operators I assume that this is enough. If it's not apparent, I want the if condition execute ifaandbare different butnotwhen one of them equalsEOF.
Translating what you said to code: ``` // I want the if condition execute: // if a and b are different but not when one of them equals EOF if ( a != b && ! (a == EOF || b == EOF) ) ``` Then applying DeMorgan's rule which moves the NOT inside and switches the OR to an AND: ``` if ( a != b && a != EOF && b != EOF ) ```
This question already has answers here:How to view C preprocessor output?(7 answers)C macros and use of arguments in parentheses(2 answers)Closed2 years ago. ``` #define MUX(a,b) a*b ``` MUX(10-5,10+5) = 10+5*10-5 = 10+50-5 = 55 I thinkMUX(10-5,10+5) = (10-5)*(10+5) = 75, but it's wrong. Why? Can anyone explain?
It's because macro replacement is entirely textual. If you want parentheses for correct arithmetic, they must be in the replacement text.
``` int x =5; char y = x + '0'; ``` Apparently this bit of code converts an integer to a string. But I don't understand how it works behind the scenes. I'm a newbie. Could someone explain how adding a string 0 with an int converts it into a string?
In char y = x + '0'; put the character code (ASCII or whatever character code your system implements) of'0'and add5to it then again convert that integer to an ASCII(/UTF-8 or any other character encoding) character that's what your output(5) will be. Behind the scenes this is what's happening: ``` y = 5 + 48 ;for ASCII/UTF-8 character code of '0' is 48 y = 53 ``` and ASCII/UTF-8 char for53is'5'. It does not convert a string to an integer. It just gives you the equivalent character. We can convert anint(0-127)to acharor vice-versa, output will be an ASCII/UTF-8 value.charare stored asshort intin memory. i.e. they are8-bit intvalues.
This question already has answers here:Char pointers and the printf function(6 answers)Closed2 years ago. For example, the following code returns an error and a warning when compiled and anintwhen changed to%d Warning: format%sexpects argument of typechar *, but argument 2 has typeint ``` void stringd() { char *s = "Hello"; printf("derefernced s is %s", *s); } ```
*sis an expression of type char since it's the dereference operator applied to a pointer-to-char1. As a result, it getspromotedto an int when passed toprintf; in order to print a null-terminated string, you need to pass the pointer to the first character (i.e. justs). 1even thoughsis not a const pointer, you should not try to modify the characters it points to as they may be placed in read-only memory where string literals are stored on some architectures/environments; seethis discussionfor more details.
why im getting errors in the code given below.... ``` #include <stdio.h> void foo(int*); int main() { int i = 10; foo((&i)++);(in this line error shows like this) //error: lvalue required as increment operand } void foo(int *p) { printf("%d\n", *p); } ```
FromMember access operators: The address-of operator produces the non-lvalue address of its operand, suitable for initializing a pointer to the type of the operand. And fromIncrement/decrement operators: The operand expr of both prefix and postfix increment or decrement must be a modifiable lvalue of integer type (including _Bool and enums), real floating type, or a pointer type. Simply put the&operator does not produce an appropriate object for the++operator.
I was do manual analysis to this code. Would wait that the value of variable D change to 1 after first call to F1 function, but conserve his value on 2. Also i noticed that comment or not comment the*Y--;has no effect. The output is: ``` 8 9 5 2 5 9 5 2 15 13 4 2 5 13 4 2 ``` Shouldn't variable D change your value to 1 after the first print? ``` #include <stdio.h> int F1 (int, int *); int A = 3; int B = 7; int C = 4; int D = 2; void main(void) { A = F1 (C, &D); printf("\n %d %d %d %d", A, B, C, D); C = 3; C = F1(A, &C); printf("\n %d %d %d %d", A, B, C, D); } int F1 (int X, int *Y) { int A; A = X * *Y; C++; B += *Y; printf ("\n %d %d %d %d", A, B, C, D); *Y--; return(C); } ```
It's aprecedenceissue. ``` *Y--; ``` means ``` *(Y--); ``` but you want ``` (*Y)--; ```
To enter into if, I need to reach the value in "t" variable. Is there any way I can do this? ``` int main(int argc , char* argv[]){ sem_t t; sem_init(&t, 0 /*#ofP*/, 1/*Semaphore start value*/); if(t > 0){ printf("Hello"); } return 0; } ```
You can usesem_getvalue(error checking omitted for brevity): ``` sem_t t; sem_init (&t, 0 /*#ofP*/, 1 /*Semaphore start value*/); int sval; sem_getvalue (&t, &sval); if (sval > 0) printf ("Hello"); ``` However:semaphores are generally used in a multi tasking / multi threaded context, so the value can change from underneath you at any time. If your goal is to wait on the semaphore until it is signalled, usesem_wait(orsem_trywaitorsem_timedwait) instead.
I have an STM32F429l-DISC1 board. I'm trying to read the value on pin PC11. This is the PORTC settings: ``` RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); GPIO_InitTypeDef GPIO_InitDef; GPIO_InitDef.GPIO_Pin = GPIO_Pin_11; GPIO_InitDef.GPIO_Mode = GPIO_Mode_IN; GPIO_InitDef.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitDef.GPIO_OType = GPIO_OType_PP; GPIO_InitDef.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOC,&GPIO_InitDef); ``` And this is how i'm pulling the value: ``` uint8_t value = GPIO_ReadInputDataBit(GPIOC, 11); ``` When I connect the pin to GND i expect to obtain 0 as a value since it's a pullup... But I'm always getting a 1. What I am doing wrong? Thanks!
ChangeGPIO_ReadInputDataBit(GPIOC, 11);toGPIO_ReadInputDataBit(GPIOC, GPIO_Pin_11);orGPIO_ReadInputDataBit(GPIOC, 1 << 11); DO NOT USE SPL. It is long time DEAD.
Here is my code ``` #include <stdio.h> #include <stdlib.h> int main(){ char c,d; c=getchar(); d=getchar(); printf("%c %c",c,d); return 0;} ``` here i asked for 2 inputs but it is stopping after taking one input. I mean if i write only one character and press enter it is just showing only that character. Not asking any further inputs. But when i am giving two inputs at the same time and then press enter it is showing both.
So,getchar()is taking a single character that is typed. But if you typecfollowed byenteryou're actually giving it 2, with the second one being theenter. Thus, the secondgetchar()is actually receiving theenterkey and hence you see the extra blank line in your top output.
Write a program that uses two dimensional of 256x8 to store 8 bit binary representation of each of the character of ASCII character set I didn't understand this question properly. Should I have to use 2d array? And place 256 characters on them.. give me some advised or help me sort out to this problem
Your question asked you to store the binary representation of all ASCII characters in an array. As everyASCIIcharacter is 8 bit long you need 8 places(ex. int or bool) for each 256 elements total 256*8 2D array. You can declare the array as, ``` int codes[256][8]; ``` Now for ASCII of 'a' is 97(dec) or 01100001(bin). ``` codes[96][0]=0; codes[96][1]=1; codes[96][2]=1; codes[96][3]=0; codes[96][4]=0; codes[96][5]=0; codes[96][6]=0; codes[96][7]=1; ``` You can print the binary representation as, ``` for(int i=0;i<8;i++) printf("%d",codes['a'][i]); ```
I am trying to set the highest bit in a byte value only when all lower 7 bits are set without introducing branching. for example, given the following inputs: ``` input: 0b_0010_1100 -> return same value input: 0b_0101_0101 -> return same value input: 0b_0111_1111 -> all bits set except MSB, return 0xff input: 0b_1010_1100 -> MSB is already set, return same value ``` This only needs to work for values of 8-bit size. I tried a few attempts usingpopcountbut that didn't work for all input.
How about: ``` return x | ((x+1) & 0x80); ```
The code got compiled successfully. but I can't reverse the string. since I am a beginner-level programmer, I can't really figure out the mistake I made. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int temp, i, j, length; char name[20], name1[20]; printf(" Enter string \n"); scanf("%s", name); length = strlen(name); printf(" %d", length); for (i = length - 1; i >= 0; i--) { name1[length - i] = name[i]; } printf("%S ", name1); return 0; } ```
Use lower case 's' in print: ``` printf("%s ",name1); ``` Similar codes:https://www.programmingsimplified.com/c-program-reverse-string
I am trying to set the highest bit in a byte value only when all lower 7 bits are set without introducing branching. for example, given the following inputs: ``` input: 0b_0010_1100 -> return same value input: 0b_0101_0101 -> return same value input: 0b_0111_1111 -> all bits set except MSB, return 0xff input: 0b_1010_1100 -> MSB is already set, return same value ``` This only needs to work for values of 8-bit size. I tried a few attempts usingpopcountbut that didn't work for all input.
How about: ``` return x | ((x+1) & 0x80); ```
The code got compiled successfully. but I can't reverse the string. since I am a beginner-level programmer, I can't really figure out the mistake I made. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int temp, i, j, length; char name[20], name1[20]; printf(" Enter string \n"); scanf("%s", name); length = strlen(name); printf(" %d", length); for (i = length - 1; i >= 0; i--) { name1[length - i] = name[i]; } printf("%S ", name1); return 0; } ```
Use lower case 's' in print: ``` printf("%s ",name1); ``` Similar codes:https://www.programmingsimplified.com/c-program-reverse-string
I need a macro that puts "**" before and after the string value, it should work someway like this: ``` #define M(x) <something> puts(M("abc")) ``` Output: ``` **abc** ``` I've tried things like ``` #define M(x) "**x**" ``` but it doesn't work :/Thanks in advance! :)
Try ``` #define M(x) "**" x "**" ``` It uses a feature that C compiler concatenates sequence of string literals.
So I have a variable value that represents an angle in degrees. I do operations with this value very often in my code, so I also need to check if its value is still in [-180, +180] range very often. Currently, I'm doing it with this piece of code: ``` if (value > 180) value -= 360; else if (value < -180) value += 360; ``` Are there any faster ways of accomplishing the same thing?
Convert it to an alu operation. So skip the if( blablabla) all together and use something along the lines of (just off the top of my head) ``` val = (val % 180) * (-1 * (val<180||val>180); ``` or ``` val = (val%180) * (-1 * abs(val)>180); ``` hmmm not sure that's right and it's a little clunky but you get the idea. The (val<180 || val>180) isn't an if then and won't cause a branch miss or stall, it is an alu operation. Will it be faster? that depends. Time different versions to find out.
I am trying to printf a simple string but I am not being able to. ``` #include <stdio.h> int main(){ char *word; scanf("%s", &word); printf("%s\n", word); return 0; } ``` When I insert the word my code breaks. It just stops the program execution but doesn't give me any error. What am I doing wrong?
Problem 1: you need toallocate spacefor your word. Problem 2: Your scanf() syntax is incorrect for a character array. Problem 3: scanf("%s", ...) itself is susceptible to buffer overruns. SUGGESTED ALTERNATIVE: ``` #include <stdio.h> #define MAXLEN 80 int main(){ char word[MAXLEN]; fgets(word, MAXLEN, stdin); printf("%s", word); return 0; } ```
I want to compare the integers in a string with integers (0-9) and I wrote this - ``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char num[100]; int count = 0; scanf("%s", num); int len = strlen(num); for (int i = 0; i <= 9; i++) { for (int j = 0; j <= len; j++) { if (i == (num[j] - '0')) { count++; } } printf("%d ", count); count = 0; } return 0; } ``` No problems with this (works in most cases but it is failing in few cases). So can you please give me alternate and best idea to do this? Thanks in advance Complete pic -
The root cause is not in char comparison, but in the under-allocated buffer: ``` char num[100]; ``` The assignment constraint is: ``` 1 <= len(num) <= 1000 ``` After increasing the buffer size, all the tests pass.
I want to compare the integers in a string with integers (0-9) and I wrote this - ``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char num[100]; int count = 0; scanf("%s", num); int len = strlen(num); for (int i = 0; i <= 9; i++) { for (int j = 0; j <= len; j++) { if (i == (num[j] - '0')) { count++; } } printf("%d ", count); count = 0; } return 0; } ``` No problems with this (works in most cases but it is failing in few cases). So can you please give me alternate and best idea to do this? Thanks in advance Complete pic -
The root cause is not in char comparison, but in the under-allocated buffer: ``` char num[100]; ``` The assignment constraint is: ``` 1 <= len(num) <= 1000 ``` After increasing the buffer size, all the tests pass.
``` double imprimirValores(char dadosHotelaria[], int n); int main( void ) { char dadosHotelaria2 [1][3][50] = { { "unidadeid1", "joao fernandes", "quartoExecutivo" }; }; imprimirValores(dadosHotelaria2, 1); } double imprimirValores(char dadosHotelaria[][3][50], int n) { return 0; } ``` warning: passing argument 1 of 'imprimirValores' from incompatible pointer type ((imprimir valores))
You declare the function to take achar []as the first parameter: ``` double imprimirValores(char dadosHotelaria[], int n); ``` But define it to take achar [][3][50]: ``` double imprimirValores(char dadosHotelaria[][3][50], int n) { return 0; } ``` The declaration of a function must match its definition: ``` double imprimirValores(char dadosHotelaria[][3][50], int n); ```
``` double imprimirValores(char dadosHotelaria[], int n); int main( void ) { char dadosHotelaria2 [1][3][50] = { { "unidadeid1", "joao fernandes", "quartoExecutivo" }; }; imprimirValores(dadosHotelaria2, 1); } double imprimirValores(char dadosHotelaria[][3][50], int n) { return 0; } ``` warning: passing argument 1 of 'imprimirValores' from incompatible pointer type ((imprimir valores))
You declare the function to take achar []as the first parameter: ``` double imprimirValores(char dadosHotelaria[], int n); ``` But define it to take achar [][3][50]: ``` double imprimirValores(char dadosHotelaria[][3][50], int n) { return 0; } ``` The declaration of a function must match its definition: ``` double imprimirValores(char dadosHotelaria[][3][50], int n); ```
i've found weird behavior ofcnd_broadcasti run 2 threads, one of them is busy doing something. and one of them is waiting for a new job. and the main thread callcnd_broadcastto inform all threads that there's no work left so they can return. then main waiting for chid threads to returnthrd_join. butnot allchild threads get informed. only the one who's waiting before the broadcast get informed. and the other threads stuck waiting signal. is this what it suppose to happen?
turns out its expected and documented.cppreference > cnd_broadcast
Is ``` int main() { int a; int b = (a = 0, a) + (a = 1, a); } ``` defined? Without the, ain each term, the program behaviour is clearly undefined due to multiple unsequenced writes toa, but don't the,introduce adequate sequencing points?
No it isn't well-defined. Suppose we replace all sequence point in your code with pseudo code "SQ": ``` SQ int b = (a = 0 SQ a) + (a = 1 SQ a) SQ ``` Then we haveSQ a) + (a = 1 SQwhere two accesses and one side effect happens toabetween sequence points, so it is still undefined behavior. We could write well-defined (but of course very bad and fishy) code like this: ``` (0, a = 0) + (0, a = 1) ``` The order of evaluation of the + operands is still unspecified, but the compiler must evaluate either parenthesis before moving on to the next. So there's always a comma operator sequence point between the side-effects/access ofa.
I came across something I don't understand why and I'd like to hear an explanation about it. I have this struct: ``` typedef struct Student { int age; char *name; } Student; int main() { Student **test1 = calloc(2, sizeof(*test1)); Student **test2 = calloc(2, sizeof(**test2)); return 0; } ``` I've noticed that test1 gets 2 memory allocations (as it should) while test2 gets 4. Why is that and which is the correct usage? I assume its the first one but i'm not sure why. Thanks!
sizeof(*test1)is the size of a pointerStudent*, whilesizeof(**test)is the size of a structureStudent.The structure has a pointer, so its size should be larger than the size of a pointer. ``` Student **test1 = calloc(2, sizeof(*test1)); ``` Is the typical usage. This is allocating 2-element array ofStudent*and assigning the pointer to its first element totest1.
Is there a way to read a format specifier, such as%sor%dfrom a text file and then use this specifier in a string variable for aprintflater on? For example, if I had a file that contains ``` foo=%s ``` would i be able to do something like this? ``` FILE * f = fopen("/home/foo/bar", "r"); charn * s_buf = malloc(sizeof(charn) * 256); fgets(s_buf, 255, f); printf(s_buf, "bar"); ``` and get this printed as a result: ``` foo=bar ``` I know it obviously doesn't work exactly like this, but i hope you understand what I'm going for and maybe know of a way to do something like this
Your code is correct but you have to think about what will happen if the file contains a %d instead of a %s, or any other invalid format specifier for what has to be displayed. It is correct to malloc() space for s_buf but a static array will do as well. You won't need to call free(s_buf) later.
The numbers are split up perfectly, however when assigned to the char array, there seems to be some memory corruption. In every number bigger or equal to 10000 the number at theten thousandsis corrupted and gives a similar output: ``` ► {‼░ ↔ @ a■ ♣ ``` ``` #include <unistd.h> void ft_putnbr(int nb) { char character[sizeof(int)]; int i; i = 0; while (nb > 0) { character[i] = (nb % 10) + 48; // Split up the number into characters nb /= 10; // Remove the number at the ones i++; } while (i >= 0) { write(1, &character[i - 1], 1); i--; } } int main (void) { ft_putnbr(2147483647); } ``` Output: ``` 21474É ► →‼░ ↔ @ a■ ♣3647 ```
``` sizeof(int) ``` Does not return number of digits, but size of int in bytes. That means that it returns 4, not 10 (or more).
I have the following files: main.c ``` #include <stdio.h> #include "test.h" int main(){ printf("%d", testFunction()); return 0; } ``` test.h ``` int testFunction(); ``` test.c ``` int testFunction(){ return 1; } ``` should i include test.h in test.c? test.c ``` #include "test.h" //is this necessary? int testFunction(){ return 1; } ``` If I run the main, there are no errors in either case.
Q: should i include test.h in test.c? A: Generally, yes. It'sessentialwith a more complex header that contains constants, struct definitions, etc. It's "good practice" in any case. ALSO: Don't forget to addheader guardsto your .h file. EXAMPLE: ``` #ifndef TEST_H #define TEST_H int testFunction(); #endif ``` If you prefer, most compilers also support#pragma onceas an alternative.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed2 years ago.Improve this question In this piece of code: ``` int main() { int i=0; while(i<10) printf("%d",i++) return 0; } ``` If I am not wrong, the printf will always print the value +1 of i, so the first print will not be 0 but actually 1, am I right?
You are wrong. The post-incrementi++is evaluated to the value ofibeforeincrementing, so what is printed in the first iteration is 0.
I have the following files: main.c ``` #include <stdio.h> #include "test.h" int main(){ printf("%d", testFunction()); return 0; } ``` test.h ``` int testFunction(); ``` test.c ``` int testFunction(){ return 1; } ``` should i include test.h in test.c? test.c ``` #include "test.h" //is this necessary? int testFunction(){ return 1; } ``` If I run the main, there are no errors in either case.
Q: should i include test.h in test.c? A: Generally, yes. It'sessentialwith a more complex header that contains constants, struct definitions, etc. It's "good practice" in any case. ALSO: Don't forget to addheader guardsto your .h file. EXAMPLE: ``` #ifndef TEST_H #define TEST_H int testFunction(); #endif ``` If you prefer, most compilers also support#pragma onceas an alternative.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed2 years ago.Improve this question In this piece of code: ``` int main() { int i=0; while(i<10) printf("%d",i++) return 0; } ``` If I am not wrong, the printf will always print the value +1 of i, so the first print will not be 0 but actually 1, am I right?
You are wrong. The post-incrementi++is evaluated to the value ofibeforeincrementing, so what is printed in the first iteration is 0.
So, I tried to create a program in C which converts uppercase characters to lowercase, just by adding 32 to uppercase characters. ``` #include <stdio.h> int main() { char user_inp[16]; char final_res[16]; int ascii; printf("%s", "Enter any string : "); scanf("%s", &user_inp); for (int i = 0; user_inp[i] != 0; i++){ ascii = (int) user_inp[i]; if (ascii < 91&& ascii > 64){ ascii = ascii + 32; } final_res[i] = ascii; } printf("%s\n", final_res); return 0; } ``` But when I run it, I get some extra jibrish results. ``` For example, Input : Apple Output : apple But, Input : Encyclopedia Output : encyclopedia�U ``` What problem am I getting ? How can I fix this ?
C strings need to be null terminated.user_inpis. Butfinal_resis not.
I have two 256X256 images, one has full purple background and the other has some of it transparent. I want to copy the second image into the first image, so that the transparent data from the second image is filled by the data from the first image, resulting this: My attempt of doing so ended with the entire first image replaced by the second image. I used theOverCompositeOpoperator:MagickCompositeImage(wand1, wand2, OverCompositeOp, MagickFalse, 0, 0);
You probably have the two images swapped. You need to overlay the transparent one on top of the opaque one. This assumes they both are the same size. In ImageMagick 7 command line, this works fine. ``` magick purple.png blue_transparent.png -compose over -composite result.png ``` For ImageMagick 6, replacemagickwithconvert
In C, inside a implementation file, when forward declaring a static function in that same file, is the static keyword needed in both the declaration (prototype) and the definition of the function?
If you includestaticin the prototype (forward declaration), then you can omit that keyword in the actual definition (it is then implied). However, if youdo nothavestaticin the prototype butdoinclude it in the definition, then you are in the realms of non-Standard C. For example, the following code is non-standard: ``` #include <stdio.h> void foo(void); // This declares a non-static function. int main() { foo(); return 0; } static void foo(void) { printf("Foo!\n"); } ``` The clang-cl compiler warns about this: warning : redeclaring non-static 'foo' as static is a Microsoft extension [-Wmicrosoft-redeclare-static]
I have two 256X256 images, one has full purple background and the other has some of it transparent. I want to copy the second image into the first image, so that the transparent data from the second image is filled by the data from the first image, resulting this: My attempt of doing so ended with the entire first image replaced by the second image. I used theOverCompositeOpoperator:MagickCompositeImage(wand1, wand2, OverCompositeOp, MagickFalse, 0, 0);
You probably have the two images swapped. You need to overlay the transparent one on top of the opaque one. This assumes they both are the same size. In ImageMagick 7 command line, this works fine. ``` magick purple.png blue_transparent.png -compose over -composite result.png ``` For ImageMagick 6, replacemagickwithconvert
In C, inside a implementation file, when forward declaring a static function in that same file, is the static keyword needed in both the declaration (prototype) and the definition of the function?
If you includestaticin the prototype (forward declaration), then you can omit that keyword in the actual definition (it is then implied). However, if youdo nothavestaticin the prototype butdoinclude it in the definition, then you are in the realms of non-Standard C. For example, the following code is non-standard: ``` #include <stdio.h> void foo(void); // This declares a non-static function. int main() { foo(); return 0; } static void foo(void) { printf("Foo!\n"); } ``` The clang-cl compiler warns about this: warning : redeclaring non-static 'foo' as static is a Microsoft extension [-Wmicrosoft-redeclare-static]
In bash,umaskwith no arguments returns current mask. Is there a way to do the same in C? umask(mode)in C changes the mask to mode and returns the previous mask. I would like to have a function that immediately returns the current mask.
Is there a way to do the same in C? I've got some bad news for you, you can't do it in C. But, then again, you can't really do it inbasheither :-) Thebashshell itself uses the "change it then quickly change it back" method for getting it, which you can also do from your own C program: ``` mode_t umask_arg; umask_arg = umask (022); // get it while temporarily setting. umask (umask_arg); // change it back quickly. // umask_arg now has the umask. ``` Other than my added comments, that's directly frombuiltins\umask.def(which creates the file to eventually be compiled for theumaskbuilt-in) in version 5.1 of thebashshell.
I have the following code in C: ``` char *val = &((file->chunk).a); ``` but when I do ``` struct Chunk data = file->chunk; char *val = &(data.a); ``` it doesn't yield the same result in val. Why aren't these two the same?
These two pieces of code havevalpointing to two different places. In the first example, you have an instance ofstruct Chunkatfile->chuckand take the address of one of its members. In the second example, you copy the contents offile->chunkto aseparateinstance ofstruct Chunkwhich resides in a different memory location. While the contents of these two structs may be the same, they are separate objects each with their own address. Sofile->chunk.aanddata.awill have different addresses.
if I have two header files a.handb.h can I include "a.h" in b.h and also include "b.h" in "a.h" ?
You can, but it's not a very good idea. If you really must, you can prevent recursion with the use of include guards (which are a good idea regardless). Ina.h: ``` #ifndef A_H #define A_H #include "b.h" #endif ``` andb.h ``` #ifndef B_H #define B_H #include "a.h" #endif ```
Consider I have the following processes which have their own copy of an array of some size (lets go with length 4) and have each calculated some values and stored it in an array according to a compressed row/col storage format. A = [ . . . .] P0: A[ 1 . 3 .] P1: A[. 2 . 4] P1 sends A to P0P0 combine P1.A with P0.A => [1 2 3 4] Is there a way for me to merge these arrays such as using some type of AllGather? There will never be any overlapping values to merge. My current approach is to use do MPI_Send(indexes_used, to P0) for each process, then send the A array with another MPI_Send.
If the empty values on each process are set to zero you can just sum the arrays up withMPI_Allreduce.
I'm trying to make a basic kernel hook which happens to use kallsyms_lookup_name, but each time i try to compile the module i getmodpost: "kallsyms_lookup_name" [<path to .ko>] undefined! I haveMODULE_LICENSE("GPL")in my module, in/proc/kallsymsi foundT kallsyms_lookup_name, but in/lib/modules/<kernel>/build/Module.symversi couldn't find it. So is the symbol not exported and if not, what do I do to export it? I'm pretty new to kernel programming.
You can't use it cause it's not exported by the latest kernels. You always can build your own kernel, just undo these changes -git patch. However, that's not good for production :)
Android Studio can't start the debugger if I use C code though JNI. Running it normally works well, but the debugger doesn't even start, regardless if I'm debugging Kotlin or C code. It throws a messageDebugger process finished with exit code 127. Rerun 'app'And the only detail it gave me iscom.intellij.execution.ExecutionFinishedException: Execution finished. Here I set up a simple github repository to replicate the error:https://github.com/perojas3/Android-JNI-debug-bug-example. It simply calls C code to get a string and then displays it in a toast. And here I set up an small youtube video displaying the bug the way it is happening:https://youtu.be/8jIL5yqP7m8 I'm using Manjaro Linux right now.
I had the same issue and installinglibncurses5package solved it. If using Ubuntu:sudo apt install libncurses5and launch the debugger again (no android studio restart required).
See below logic fromwgetsource code. Where islast_componentdefined? I presume this is either a GNU include or buried somewhere in the standard C includes. But I can't seem to locate it. Thx. ``` char * get_metalink_basename (char *name) { int n; char *basename; if (!name) return NULL; basename = last_component (name); while ((n = FILE_SYSTEM_PREFIX_LEN (basename)) > 0) basename += n; return metalink_check_safe_path (basename) ? basename : NULL; } ```
Wget usesgnulib.last_componentis declared inbasename-lgpl.hand defined inbasename-lgpl.c.
so i want to extract a part of a char variable ,likesigned char *a="06254148"*i want to extract "06" the first two characters and compare it with "07" i tried to use shift >> but i think it works only with integers ! * ``` int main () { signed char *a="021547"; //int a=0x100201,b=0x102548; printf("%d", a>>12); return 0; } ``` i know that what i have tried is false ;could someone help me please
To get the first character use: ``` a[0] ``` and for the second: ``` a[1] ``` and so on
I've started learning C language. I tried using extern variable modifier but it is showing undefined reference error.enter image description here I have declared int a in xyz.c file same as shown in video lecture.
As you have just started learning C I advise avoiding more advanced language features before you become a bit more proficient. Removeextern. Do not use it before you start writing multi source file programs and understand the linkage concept.maindeclaration is wrong. It should beint main(void)if main does not take any parameters.
This is a code for input-output practice. I am getting the correct output for the first two input lines. But I am getting a zero for the third line input. The given task is: To calculate the sum of some integers. ``` Input: 4 1 2 3 4 5 1 2 3 4 5 0 Output: 10 15 #include<stdio.h> int main() { int i, first, next, total; while(scanf("%d", &first) != EOF) { total = 0; for(i = 1; i <= first; i++) { scanf("%d", &next); total += next; } printf("%d\n", total); if(first == 0) { printf(" "); } } return 0; } ```
If you do not want output when the first number on a line is zero, then you should testfirst == 0beforecalculating and printing a total and break from the loop (break;if you want to stop the loop) or continue to the next iteration (continue;).
How to call an executable C in script shell ? I did echoname_of_executable_filebut it didnt works
You call it like this: ``` /path/to/name_of_executable_file ``` Or if it's in the current directory, like this: ``` ./name_of_executable_file ```
I am a beginner in TwinCAT and is using XAE to test some functionalities.My current program requires me to pass an array of bytes from the PLC ST program to C module instance. However TwinCAT 3 doesn't allow this and the error message says 'Structured value types not allowed in external function calls'.Is there any workaround for this?Is there any other way of passing a byte array to the C module instance?
In your C/C++ project you will be able to find a folder called "TMC Files". In the .tmc file you can define Data Areas for your module. You can define inputs for the module using "Input-Destination" and then defining the data structures and naming that you need. When you later instantiate your module you can link this data area to variables in your PLC code. Here is an example of the .tmc file from my project (not using arrays but other input data types): TMC file
I have two arrays ``` int x[]={1,2,3,4}; int y[]={5,6,7}; ``` I like to create two dimensional array. assign x and y. Can I do something like this ``` int x[]={1,2,3,4}; int y[]={5,6,7}; int *k=x; int *l=y; int **m={k,l}; printf("%d\n",m[0][0]); ``` but atprintfwhen 1 is get accessed throws segFault What I am doing wrong
``` int **m={k,l}; ``` is wrong. This is assigning the value ofk(int*) to the variablem(int**) and leaving the excess elementlin the initializer unused. You can use an array ``` int *m[]={k,l}; ``` or a compound literal ``` int **m=(int*[]){k,l}; ``` instead.
I know that thegettextlibrary haspgettext()which can be used to translate a piece of string for given context. I also know that it hasngettext()which can be used to translate string which should have different singular and plurar forms. How to translate a string which should have different singular and plurar formsanddepends on context? It seems that logical extension calledpngettext()doesn't exist. I'd want to use such behavior from PHP but I'd be happy to know a solution for plain C only.
There seems to benpgettext()in Python's gettext documentation, and for C, a macro by that name is defined ingettext.h(but notlibintl.h).
I am working on a project for fun to learn C programming, and in Java, I know that I can just obtain a String from a method through a simple return statement. However, in C, I believe it is returning the address of the pointer or garbage data. Here is some basic code: ``` // In Main Method char *words = getWords(); // ... // In getWords char *getWords() { char *input; //Well-formatted input. // Filler code that collects data through file or text entry with 256 max char. char str[256]; scan("%s", str); input = str; return input; } ```
You need to pass the pointer as an argument and store the data there itself. Declaring local pointer and returning it is not a good way of doing it. It may lead to dangling pointer. https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/
I am a beginner in TwinCAT and is using XAE to test some functionalities.My current program requires me to pass an array of bytes from the PLC ST program to C module instance. However TwinCAT 3 doesn't allow this and the error message says 'Structured value types not allowed in external function calls'.Is there any workaround for this?Is there any other way of passing a byte array to the C module instance?
In your C/C++ project you will be able to find a folder called "TMC Files". In the .tmc file you can define Data Areas for your module. You can define inputs for the module using "Input-Destination" and then defining the data structures and naming that you need. When you later instantiate your module you can link this data area to variables in your PLC code. Here is an example of the .tmc file from my project (not using arrays but other input data types): TMC file
I have two arrays ``` int x[]={1,2,3,4}; int y[]={5,6,7}; ``` I like to create two dimensional array. assign x and y. Can I do something like this ``` int x[]={1,2,3,4}; int y[]={5,6,7}; int *k=x; int *l=y; int **m={k,l}; printf("%d\n",m[0][0]); ``` but atprintfwhen 1 is get accessed throws segFault What I am doing wrong
``` int **m={k,l}; ``` is wrong. This is assigning the value ofk(int*) to the variablem(int**) and leaving the excess elementlin the initializer unused. You can use an array ``` int *m[]={k,l}; ``` or a compound literal ``` int **m=(int*[]){k,l}; ``` instead.
I know that thegettextlibrary haspgettext()which can be used to translate a piece of string for given context. I also know that it hasngettext()which can be used to translate string which should have different singular and plurar forms. How to translate a string which should have different singular and plurar formsanddepends on context? It seems that logical extension calledpngettext()doesn't exist. I'd want to use such behavior from PHP but I'd be happy to know a solution for plain C only.
There seems to benpgettext()in Python's gettext documentation, and for C, a macro by that name is defined ingettext.h(but notlibintl.h).
I am working on a project for fun to learn C programming, and in Java, I know that I can just obtain a String from a method through a simple return statement. However, in C, I believe it is returning the address of the pointer or garbage data. Here is some basic code: ``` // In Main Method char *words = getWords(); // ... // In getWords char *getWords() { char *input; //Well-formatted input. // Filler code that collects data through file or text entry with 256 max char. char str[256]; scan("%s", str); input = str; return input; } ```
You need to pass the pointer as an argument and store the data there itself. Declaring local pointer and returning it is not a good way of doing it. It may lead to dangling pointer. https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/
When I change two values of the struct variable, I am getting unexpected output. But if I change these variables one by one, I don't get unexpected output. Why did this happen? Here are the codes and outputs. Unexpected Output ``` void check_tag_names(struct tag t){ struct tag *tagPtr; tagPtr = &t; strncpy(tagPtr->name,"name",4); //strncpy(tagPtr->surname,"surname",7); printf("%s",t.name); } ``` Output:namesurname I don't understand why t.name is "namesurname" instead of just "name"
printf("%s",t.name);expectst.nameto refer to astring. t.nameis not astringas it lacks anull character`. The result isundefined behavior.
How can i run asynchrounous-unsafe code in a signal handler. I cant use a flag in my case. Could i use longjmp to jump to a different context?
In a signal handler you can only use a set of safe functions which in many cases is sufficient for complicated functionality started within a handler. You can check man pages for your system for 'signal-safety' or similar. Here is a pointer on the web:https://man7.org/linux/man-pages/man7/signal-safety.7.html pthread synchronization functions are not on the list. However, One of the function listed there issem_post:https://man7.org/linux/man-pages/man3/sem_post.3.html sem_post() is async-signal-safe: it may be safely called within a signal handler. So, you can implement mutex-like synchronization using semaphores within the signal handler.
This question already has answers here:Python ? (conditional/ternary) operator for assignments [duplicate](2 answers)Closed2 years ago. Can somebody explain me the following line of C-code and translate it into Python? I have no plan.... ``` x[IX(0 ,i)] = b==1 ? –x[IX(1,i)] : x[IX(1,i)] ``` The array structure is not important (except that I am interested in a vectorized Numpy form too). I'm interested in understanding the C command. Simplified we can write ``` D = b==1 ? –A : A ``` What does this mean? What is the result of D at the end? What's the role of–A : A? How can we write this in Python? How can we write this vectorized in Numpy? Thank you !
Alternative form: ``` if(b==1) D = -A; else D = A; ``` or ``` if(b==1) x[IX(0 ,i)] = –x[IX(1,i)]; else x[IX(0 ,i)] = x[IX(1,i)]; ``` I think in this form it is not difficult to translate to python
I have two files: ``` FILE* fileToScan = fopen("c:/fileToScan.png", "rb"); FILE* contentFile = fopen("c:/virusFile.jpg", "rb"); ``` I want to check if the content of contentFile is in (/part of) fileToScan. Any help?
"Simple" solution: read the whole file to scan in memory. You can use variablechar *haystack;with sizesize_t haystack_len;read the whole content file in memory. You can use variablechar *needle;with sizesize_t needle_len;run amemchr()on haystack using the first character of needleif you find the first character try amemcmp()from that pointif thememcmp()fails you can update the haystack pointer to one past thememchr()result and go back to step 3 This is using no optimization at all! You can find definitely find better implementations likethe glibc one. If the file doesn't fit in memory, things are going to be harder. You basically need to work in chunks.
I run the following c program ``` char str[80] = "String"; printf("hello %s\n", str); scanf("%s", str); printf("%s\n", str); scanf("%[ABCDEF]", str); printf("hello %s\n", str); return 0; ``` For some reason on line 5 when it is suppose to input from Pattern %[ABCDEF], the console simply prints previous string (input from line 3). Why is that so?
Thats because the firstscanfcall doesn't read the newline character and the second call toscanfsimply reads that newline character. To avoid this start the format string with a space like this: ``` #include <stdio.h> int main(void) { char str[80] = "String"; printf("hello %s\n", str); scanf("%s", str); printf("%s\n", str); scanf(" %[ABCDEF]", str); printf("hello %s\n", str); return 0; } ``` However, you also need to make sure thatstrdoesn't overflow if the user inputs a string longer than 79 characters.