question
stringlengths
25
894
answer
stringlengths
4
863
I have this code: ``` for (int i = 0; i < var; i++) for (int j = 0; j < var2; j++) // something which using j variable ``` Can I useivariable from first loop insteadvar2variable?
a quick note: if your code used brackets{} then the scope of the variables lives within the brackets boundaries. Wihtout the brackets in c your loop lives until the next semi colon (in other words one line of code) ``` for (int i = 0; i < var; i++) { // i can use i here but not j for (int j = 0; j < i; i++) { // something which using j variable // something using i variable } // i can use i here but not j } ``` to learn more look up Scope in Chttps://www.tutorialspoint.com/cprogramming/c_scope_rules.htm#:~:text=A%20scope%20in%20any%20programming,which%20is%20called%20local%20variables.
As I was following an example from a book, ``` #include <stdio.h> main() { int c; c = getchar(); while (c != EOF) { putchar(c) c = getchar(); } } ``` I thought it would make more sense to read character first, then print it so switched putchar and getchar around ``` c = getchar(); putchar(c); ``` now when I run it, what happens is the first output of putchar is missing the first character of c? This is the output: ``` kingvon@KingVon:~/Desktop/C$ ./a.out first letter is missing? irst letter is missing? but now it is not but now it is not ``` This is interesting, why does this happen?
Because you're getting a characterbeforethe loop. That means c is equal to that first character, but in the loop it's getting every character after that. So, ``` Get: f Start the loop Get: i Print: i And so on ```
I'm attempting to use ccall to interface with a Windows function (FindWindowA to be specific), but i'm getting a weird behavior ``` julia> ccall((:FindWindowA, :user32), Int32, (Ptr{Cvoid},), C_NULL) 855386 julia> foo() = ccall((:FindWindowA, :user32), Int32, (Ptr{Cvoid},), C_NULL) foo (generic function with 1 method) julia> foo() 0 julia> @ccall :user32.FindWindowA(C_NULL::Ptr{Cvoid})::Int32 65920 julia> foo() = @ccall :user32.FindWindowA(C_NULL::Ptr{Cvoid})::Int32 foo (generic function with 1 method) julia> foo() 0 ``` Is there a way to get consistent results from ccall?
Try providing second parameter to the function as well, according todocs: ``` julia> @ccall :user32.FindWindowA(C_NULL::Ptr{Cvoid})::Int32 65896 julia> boo() = @ccall :user32.FindWindowA(C_NULL::Ptr{Cvoid}, C_NULL::Ptr{Cvoid})::Int32 boo (generic function with 1 method) julia> boo() 65896 ```
I have 2 thread bonded to 2 cpu core separately. thread A and thread B have the same cache line data. If I modified the cache line data and call _mm_clflush (void const* p) in thread A. The cache line (L1,L2,L3) in thread B will become invalid and only can be read from main memory again. Is that right ?
The answer is yes. According to the Intel documentation, theCLFLUSHinstruction invalidates the cache line in the entire "cache coherency domain". It is therefore not limited to the shared cache (normally Level 3 Cache), but also affects the dedicated cache of all other CPUs (i.e. their Level 1 and Level 2 Cache). So, the next time a read takes place from that cache line, it will have to be read from main memory again.
Iam new to c. Here defined a macro as#define val 4+2. when try to print square usingval*valit gives output as14instead of36. How is this happening, but when macro is defined as#define val 6it gives correct output. Here is the sample code snippet. Can someone explain why is this so? ``` #define max 4+2 int main() { printf("%d\n",max); int i = max*max; printf("%d\n",i); } ``` output: 6 14
The statement ``` int i = max*max; ``` expands to ``` int i = 4 + 2 * 4 + 2; ``` which is equivalent to ``` int i = 4 + (2 * 4) + 2; ``` If you want the result to be ``` int i = (4 + 2) * (4 + 2); ``` then you need to explicitly add the parentheses in the macro: ``` #define max (4+2) ``` This is a common "flaw" with macros, and one reason their usage is discouraged, or to be used for very simple constant values only.
I want to initialize a value of all array members to their index. ``` int main() { int i; int arr[10]; for (i = 0; i <= 9; i++) arr[i] = i; } ``` Should I consider the sequence point in this case?Isarr[i] = ilegal and portable?
You need to consider sequence points if you modify something more than once in one place,orif you both read and modify something in one place. You're not doing any of that, so your code is fine.
Is there a way to do multiple increments / decrements on distinct semaphores in one (atomic) operation? I saw that in SysV it is possible to do this and I was wondering if there was a way to do the same using POSIX API. Here's what I would like to do (in SysV): ``` sem[0].sem_num = 0; sem[0].sem_op = 1; sem[0].sem_flg = 0; sem[1].sem_num = 1; sem[1].sem_op = -1; sem[1].sem_flg = 0; semop(semid, sem, 2) ``` Is there a way to do the same in POSIX?
Is there a way to do same usingsemaphore.h? No, it is not possible. Is there a way to do the samein POSIX? The code you posted is using XSI extension to POSIX. Generally, even the standard states that if you are on POSIX compatible platform, you may use XSI extension with confidence that it will be available.
I have the following problem: I'm using zlib in C to gzip files. The compressing (usingz_stream,deflateInit2...) is no problem, but I need to know the size of the gziped file before I compress it. Is this possible or is the only option I have to count the bytes while compressing? Thanks in advance!
but I need to know the size of the gziped file before I compress it If you mean that you need it to compress (perhaps to allocate a buffer to hold the data), then you are mistaking, the whole point ofz_streamis to let you compress input chunks in output chunks. is the only option I have to count the bytes while compressing Yes, you need to apply the compression algorithm to know the resulting size.
I wanted to try to execute 'make install' command from a makefile automatically with meson. I tried the following in a meson.build file: ``` r = run_command('make install') if r.returncode() != 0 # it failed endif output = r.stdout().strip() errortxt = r.stderr().strip() ``` But it prints the following error:Program or command 'make install' not found or not executable.This meson.build file is located in the same directory as my makefile. Is this not the way to use this functionality or is there a better way to acheive what I'm trying to do?
The first argument is the command (binary) followed by its arguments: ``` run_command('make', 'install') ```
I have the following problem: I'm using zlib in C to gzip files. The compressing (usingz_stream,deflateInit2...) is no problem, but I need to know the size of the gziped file before I compress it. Is this possible or is the only option I have to count the bytes while compressing? Thanks in advance!
but I need to know the size of the gziped file before I compress it If you mean that you need it to compress (perhaps to allocate a buffer to hold the data), then you are mistaking, the whole point ofz_streamis to let you compress input chunks in output chunks. is the only option I have to count the bytes while compressing Yes, you need to apply the compression algorithm to know the resulting size.
This question already has answers here:C program to convert Fahrenheit to Celsius always prints zero(6 answers)Closed2 years ago. ``` int number = round(2/3); printf("%i", number); ``` the output is ``` 0 ``` I expected to get 1 as 0.6 recurring should round up - i know for sure that the problem is with recurring decimals as they are always rounded down - I'm not sure how to round up in this kind of scenario.
``` #include <stdio.h> #include <math.h> #include <stdlib.h> int main(void) { double number = round(2.0/3.0); printf("%0.f", number); } ``` Output = 1 You can use double or float for rounding numbers
I was working on the "QNX RTOS" in which i came across the following line can anyone please help me to understand? ``` *(volatile void **) kernel_data = (void *) & _mqx_version_number; ``` Regards, Omkar Dixit
(volatile void **)kernel_data--> castkernel_datato pointer to pointer of type volatile void. Now,kernel_datais a pointer to pointer (volatile void**)*kernel_datais pointer of typevolatile void* *(volatile void **) kernel_data = (void *) & _mqx_version_number; So, here, we are type castingkernel_datato typevolatile void **and then dereferencing it.
I am reading "Computer Systems: A Programmer's Perspective". Topic: stages of compilation in C Preprocessing phase, Compilation phase, Assembly phase and Linker phase. In Assembly phase this line "This file (the object file) is a binary file containing17 bytes to encode the instructionsfor function main." I can't understand what the "17 bytes to encode the instructions mean".
Without entering in much detail, the result of the compilation is stored in object files. Then, after compiling that functionmain, the result are 17 bytes that are stored in the object file. It says 'encode' because the compiler is "translating" from C++ language to another, which normally is machine code. Depending on the compiler and the target machine/environment you want to compile for, those 17 bytes will probably be different.
There is a code: ``` float x=-8.92; int y=5; printf("%u\n", sizeof x+y); printf("%u\n", sizeof (x+y)); ``` Conclusion: ``` 9 4 ``` Why is this happening(result 9)? After all, these are simple unary operations.
Thesizeofoperator has higher precedence than the binary addition operator+. So this: ``` sizeof x+y ``` Parses as: ``` (sizeof x)+y ``` So in the first expression you're getting the size of afloatwhich is 4 on your system and adding the value 5 to that, resulting in 9. For the second expression, the subexpressionx+yhas typefloatbecause of theusual arithmetic conversions, so the result is 4 which is what's printed.
I'm just starting out with C and I've got this code block for beginners: ``` #include <stdio.h> #include <stdlib.h> int main() { printf(' /\n'); printf(' /\n'); printf(' /\n'); printf(' /\n'); printf(' /\n'); printf('/\n'); return 0; } ``` I'm using Code Blocks to build and run it. It prints outSegmentation Fault, core dumped. The editor is using default gcc compiler. What's wrong with the code ?
You use single quotes callingprintfinstead of double quotes. It's going to turn the first few characters into an integer, and cast that integer as a pointer and access wherever it points as a format string, which is most likely not yet mapped, so segmentation fault. Use double quotes. As Ed Heal mentioned, always compile with warnings enabled. C isn't like other languages. Warnings are usually very serious problems.
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it. How can I declare it in global scope and assign its size in themainfunction?
``` #include <stdlib.h> // for malloc int *globalarray; int main() { ... globalarray = malloc(thesizeyouwant * sizeof(*globalarray)); ... globalarray[0] = foo; ... free(globalarray); } ```
``` #include <stdio.h> #include <math.h> int main() { float g1, g2, c1, c2, dismul, cadd, csub, dis; printf("Enter the latitudes of the places (L1 and L2): "); scanf("%f %f", &c1 ,&c2); printf("Enter the longitudes of the places (G1 and G2): "); scanf("%f %f ", &g1, &g2); cadd = cos(c1 + c2); csub = cos(g2-g1); dismul = cadd * csub; dis = 3963 * acos(dismul); printf("The distance between the places is:%f\n", dis); return 0; } ``` I wrote this code to give distance between two points but when I run it, it does not give the lastprintfuntil I type any letter and press enter.
as already pointed out in comments, on line 9 of your code (scanf("%f %f ",&g1,&g2);) There is an extra space after the second "%f", so scanf() is expecting to read a whitespace after a floating point character. replace it with ``` scanf("%f %f",&g1,&g2); ``` to fix it.
Option 1: ``` typedef struct s{ int x; double y; char z; }mystruct; ``` Option 2: ``` typedef struct { int x; double y; char z; }mystruct; ``` What's the difference between these 2 options?
With option 1 you can declare a variable like this: ``` struct s foo; ``` or ``` mystruct foo; ``` With option 2 the only possibility is: ``` mystruct foo; ```
``` #include <stdio.h> int main() { int n1,n2 ; char operator ; printf("enter the expression"); scanf("%d","%c","%d",&n1,&operator,&n2); if (operator == '+') { printf("%d+%d=%d",n1,n2,n1+n2); } else if (operator == '-') { printf("%d-%d=%d",n1,n2,n1-n2); } else if (operator == '*') { printf("%d*%d=&d",n1,n2,n1*n2); } else if (operator == '/') { printf("%d/%d=%d",n1,n2,n1/n2); } else { printf("wrong input"); } return 0; } ``` This code shows no error but does not run as expected. After i enter the expression, it does not give me an output
Yourscanfcall is incorrect. You should put everything in one string: ``` scanf("%d%c%d",&n1, &operator, &n2); ``` See also thedocumentation. I tried it and it works now.
I'm just starting out with C and I've got this code block for beginners: ``` #include <stdio.h> #include <stdlib.h> int main() { printf(' /\n'); printf(' /\n'); printf(' /\n'); printf(' /\n'); printf(' /\n'); printf('/\n'); return 0; } ``` I'm using Code Blocks to build and run it. It prints outSegmentation Fault, core dumped. The editor is using default gcc compiler. What's wrong with the code ?
You use single quotes callingprintfinstead of double quotes. It's going to turn the first few characters into an integer, and cast that integer as a pointer and access wherever it points as a format string, which is most likely not yet mapped, so segmentation fault. Use double quotes. As Ed Heal mentioned, always compile with warnings enabled. C isn't like other languages. Warnings are usually very serious problems.
I have an array that I want to have in global scope. Its size however is determined during runtime, so I can't initialize it where I define it. How can I declare it in global scope and assign its size in themainfunction?
``` #include <stdlib.h> // for malloc int *globalarray; int main() { ... globalarray = malloc(thesizeyouwant * sizeof(*globalarray)); ... globalarray[0] = foo; ... free(globalarray); } ```
``` #include <stdio.h> #include <math.h> int main() { float g1, g2, c1, c2, dismul, cadd, csub, dis; printf("Enter the latitudes of the places (L1 and L2): "); scanf("%f %f", &c1 ,&c2); printf("Enter the longitudes of the places (G1 and G2): "); scanf("%f %f ", &g1, &g2); cadd = cos(c1 + c2); csub = cos(g2-g1); dismul = cadd * csub; dis = 3963 * acos(dismul); printf("The distance between the places is:%f\n", dis); return 0; } ``` I wrote this code to give distance between two points but when I run it, it does not give the lastprintfuntil I type any letter and press enter.
as already pointed out in comments, on line 9 of your code (scanf("%f %f ",&g1,&g2);) There is an extra space after the second "%f", so scanf() is expecting to read a whitespace after a floating point character. replace it with ``` scanf("%f %f",&g1,&g2); ``` to fix it.
Option 1: ``` typedef struct s{ int x; double y; char z; }mystruct; ``` Option 2: ``` typedef struct { int x; double y; char z; }mystruct; ``` What's the difference between these 2 options?
With option 1 you can declare a variable like this: ``` struct s foo; ``` or ``` mystruct foo; ``` With option 2 the only possibility is: ``` mystruct foo; ```
``` #include <stdio.h> int main() { int n1,n2 ; char operator ; printf("enter the expression"); scanf("%d","%c","%d",&n1,&operator,&n2); if (operator == '+') { printf("%d+%d=%d",n1,n2,n1+n2); } else if (operator == '-') { printf("%d-%d=%d",n1,n2,n1-n2); } else if (operator == '*') { printf("%d*%d=&d",n1,n2,n1*n2); } else if (operator == '/') { printf("%d/%d=%d",n1,n2,n1/n2); } else { printf("wrong input"); } return 0; } ``` This code shows no error but does not run as expected. After i enter the expression, it does not give me an output
Yourscanfcall is incorrect. You should put everything in one string: ``` scanf("%d%c%d",&n1, &operator, &n2); ``` See also thedocumentation. I tried it and it works now.
I have a C++ project, and the main file with the main function is a.c, but when I include my.hthat is supposed to be C++, I think I am getting errors because it thinks it is C. How can I tell it that my header should be C++ and not C, like my main?
You cannot#includeC++ header in a C source file. A header is not compiled separately. All that#includedoes - it makes the compiler work as if the header was a part of the file.
I want to declare of array of pointers to arrays of char *. When i compile the code, i got warnings: ``` warning: initialization of ‘const char *’ from incompatible pointer type ‘const char **’ [-Wincompatible-pointer-types] ``` This code works, but i know i do something wrong and i should not have any warnings by C compiler. How to declare it right? ``` const char *S6_ARR[] = { "here", "we" }; const char *S7_ARR[] = { "go", "again" }; const char *SHEET_HEADER_ARR[] = { S6_ARR, S7_ARR }; int main() { ... } ```
The warning is telling you that you are trying to put elements of typeconst char **into an array of typeconst char *. So change the array type to match what you're putting into it: ``` const char **SHEET_HEADER_ARR[] = { S6_ARR, S7_ARR }; ```
Shouldn't I be getting warning or error message after declaring macro in this way: ``` #define c 123 #define a b #define b c ``` The code worked flawlessly - so just like variable definition, is macro definition stored somewhere?
This is perfectly fine, because preprocessor does not act upon macro definitions until the point of expansion. That is why the order does not matter: as long as each macro has a definition to which it could be expanded when your code makes a reference to it, the preprocessor is happy. This applies to macros that rely on other macros for their expansion. One consequence of this behavior is that the relative order of macro declarations does not change the end result.
It seems to be that Vim's:compiler gcchas a bug. It treatsmake: ***as an error and therefor opens an empty buffer namedbuild.makewhen opening quickfix. Here is a screenshot: I don't want to bother Vim people for no reason. It looks like a bug to me, but maybe I a m wrong, so I want a second opinion: who else thinks its a bug?
I eventually opened an issue at Vim's Github. Here is the link:https://github.com/vim/vim/issues/7536. TL;DR - since I usecmakeand notmake,:compiler gccwas not working as expected, I should have used:compiler cmake(such a thing does not exists).
I am curious about a behavior of bit-wise operator of C on Character. ``` #include <stdio.h> int main() { int x = 108; x = x<<1; printf("%d\n", x); char y = 108; y = y<<1; printf("%d", y); //printf("%d", y<<1); return 0; } ``` Here, if I pass like this, y = y<<1, it's output was-40and when I print it directly like, printf("%d", y<<1); it's output was216. How I can simulate it?
Note that there is really no<<operation onchartypes - the operands of<<are promoted to (at least)inttypes, and the result is, similarly, anint. So, when you doy = y << 1, you are truncating theintresult of the operation to a (signed)char, which leaves the most significant bit (thesign bit) set, so it is interpreted as a negative value. However, when you passy << 1directlytoprintf, the resultingintis left unchanged.
INPUT: A string in c that looks like this : " 12345 computer seince 101" OUTPUT: NUMBER OF COURSE = "12345" NAME OF COURSE = "computer seince 101" i need to ignore all spacebars before the number and the name, so strings like : "(spaces)12345(more spaces)computer sience 101" are allowded i tried messing around with strtok, but i failed
Usestrtol()function. ``` #include <stdio.h> #include <stdlib.h> int main () { char str[30] = " 12345 computer science 101"; char *ptr; long ret; ret = strtol(str, &ptr, 10); printf("NUMBER OF COURSE %ld\n", ret); printf("NAME OF COURSE %s", ptr); return(0); } ``` The output is: ``` NUMBER OF COURSE 12345 NAME OF COURSE computer science 101 ```
So i want to select all elements of a struct and initialize them to 0 in C ``` typdef struct s_coord { int x; int y; } t_coord; ``` So in order to initialize them i should go ``` int main(void) { t_coord coord; coord.x = 0; coord.y = 0; } ``` so i have a struct with more than 10 variables is there any way to initialize them all at the same time something like: ``` coord.* = 0; ``` or ``` coord = 0; ``` ??? Edit: Thanks guys for the answers i found out bzero function also works
On declaration (as said in comments) : ``` t_coord coord = {0}; ``` After declaration, you can set the memory to zero like this : ``` memset(&coord, 0, sizeof(t_coord)); ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed2 years ago.Improve this question ``` int i=3,j=1,k=0,m; m=++i || ++j && ++k; printf("%d%d%d%d",i,j,k,m); ``` //output is 4 1 0 1enter code here//can anyone explain why k=0 and j=1 only
m = ++i || ++j && ++k;is grouped asm = ++i || (++j && ++k);since,&&has higher precedence. But, they are evaluated from left to right. Since,++i = 4, which a non-zero number, the right hand expression is not evaluated. I mean(++j && ++k)is not evaluated since, left hand expression result is non-zero. For A||B, if A = 1, then results is always 1, irrespective of the value of B. Since, the right hand expression is not evaluated, the values ofjandkremain same. This feature is called "Short Circuit Evaluation".
When working with seccomp userspace notifications (https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html) via SECCOMP_RET_USER_NOTIF I found the PID as part of the seccomp_notif struct extremely useful for some filtering decisions. In ebpf filters helper functions, like bpf_get_current_pid_tgid(), can be used to obtain such information. But since seccomp only seems to support the classic BPF I was wondering if there is another way. Inside a seccomp filter as far as I know it is only possible to access the seccomp_data structure. Is there a way to get specific information like the PID inside a seccomp filter directly?
No, you cannot get that information from the seccomp filter itself unless it is part of the syscall arguments. To retrieve the PID, you would have to e.g. give control to a userspace ptracer process or rely onSECCOMP_RET_USER_NOTIFas you mentioned.
I'm trying to prompt the user for a number between 1-8 and reprompt if they don't respond correctly. However when I try to compile my code I get these errors. ``` mario.c:4:15: error: expected ';' after top level declarator int main(void) ^ ; mario.c:6:1: error: expected identifier or '(' { ^ 2 errors generated. ``` This is my code: ``` #include <stdio.h> int main (void) int height; { do { height = get_int ("Enter Height: "); } while (height > 8 || <1); } ```
The opening bracket should be directly aftermain, not afterheightis declared. Alsowhile(height >8 || <1)should bewhile(height >8 || height <1). ``` int main(void){ int height; do { height = get_int("Enter Height: "); } while(height >8 || height<1); } ```
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question When writing a C library, many developers argue that it should not be header only since that would increase compilation time. Personally, I'm a little confused by that fact since I'm comparing it to the fact that the standard library is all header only. So what's the right way to build a library?
It is really naïve to think, that standard library is all header only. Behind those headers you include in your code, there islibcfor example, where all functionalities are defined, and those headers are just an "interface" to access them. I'll recommend to read about .so files, for further understanding.
I'm using a library that callbacks to my functions. Those functions do basically the same thing; the only difference is that they have a different type of structure passed to the function. ``` static void func_a(void * a, TypeA * b) { ... printf("%d\n", b -> code); } static void func_b(void * a, TypeB * b) { ... printf("%s\n", b -> string); } ``` Is there a way in C to avoid using duplicate code in this case?
You could write a single function like this: ``` enum struct_type { A, B, // ... }; static void func(void *a, void *b, enum struct_type st) { // ... char const *str; switch(st) { case A: str = ((TypeA *)b)->string; case B: str = ((TypeB *)b)->string; // ... } printf("%s\n", str); } ``` Is that what you are looking for?
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed2 years ago.Improve this question Suppose the .txt file contains numbers such as : 52 53 54 How can I store these numbers which are to be read from the file into an array of some order?
``` #include <stdio.h> int main() { FILE *myFile; myFile = fopen("numbers.txt", "r"); int numberArray[3]; int i; for (i = 0; i < 3; i++) { fscanf(myFile, "%d", &numberArray[i]); } // Do more stuff with numberArray } ```
This question already has answers here:How do you read C declarations?(10 answers)Closed2 years ago. I was looking into simple source code. and found this line ``` int (*pfds)[2]; ``` does it means pointer to function similar to ``` void (*fun_ptr)()[2] = &fun; ``` which I think is array of pointer to functionfun(void)
int (*pfds)[2];---->pfdsis a pointer to an array of 2 elements. void (*fun_ptr)()[2]----> Declarefun_ptras pointer to function returning array of 2 elements of void. But it is invalid. Since, in C, function returning array is not allowed. void* (*fun_ptr)()-----> declarefun_ptras pointer to function returning, pointer to void. This is valid. This is what you need, if you want to return an array of type void.
I'm learning WINAPI, so I'm dealing with tab control, which requires to callInitCommonControlsEx()but where's the proper place to call it? whenWM_CREATEmessage is received in the windows callback procedure? or before the main loopwhile(GetMessage(&msg, NULL, 0, 0))or somewhere else? I've seen all those approches I mentioned being used, I'm not quite sure which one is correct.
The best place to call it is once at program startup, such as inWinMain(), before you start creating your UI Windows.
Is there any way to flip a Bitmap with function like BitBlt or StretchBlt. I'am getting really confused by the Cooridnates. Currenty i've tried some variation of this: BitBlt(hdc,0,bmp.bmHeight,bmp.bmWidth,0,hdc,0,0,SRCCOPY); Is it even possable with these functions?
BitBltdoes not allow for transformations other than translation.StretchBltwill do this, though. Just specify a negative destination width or height (depending on which axis you want to flip around), and adjust the corresponding destination origin coordinate so that it refers to the other side. For instance, to flip a 200x100 image horizontally, you’d do ``` StretchBlt( dest, 200, 0, -200, 100, src, 0, 0, 200, 100, SRCCOPY); ```
How could I write it in C language? I tried many things, but it seems that I cannot understand the exp and sin functions.
A direct implementation could be: ``` double y = exp(pow(sin(x),3)) + pow(x,6) - 2*pow(x,4) - pow(x,3) - 1.0; ```
So i have this function that reads file, allocates memory, and puts file's content into buffer. I constantly get garbage data in the end though, so i need a way to null terminate the buffer. ``` #include "GetText.h" void GetText(const char* filename, char** buffer) { FILE* file = fopen(filename,"rb"); long file_lenght; if(file) { fseek(file, 0, SEEK_END); file_lenght = ftell(file); rewind(file); *buffer = (char*) malloc(file_lenght + 1); fread(*buffer, 1, file_lenght, file); *buffer[file_lenght] = '\0'; //This line crashed program fclose(file); } } ```
Since the bracket operator has higher precedence than pointer dereference you need to dereferencebufferbefore indexing, like this: ``` (*buffer)[file_lenght] = '\0'; ``` In your program you also need to make suremallocwas successful.
Whenever I run the following, I get undefined references to all the SDL-related functions used in my program: ``` cc -lSDL2 -lGL *.o ``` I believe this is caused by the lack of-llinker flags.
GCC arguments are positional, put the link flagsafteryourofiles: ``` gcc *.o -lSDL2 -lGL ``` Also, if you're on a proper full Linux system I'd recommend usingpkg-configto pull compiler/linker flags: ``` gcc -c main.c `pkg-config sdl2 --cflags` gcc main.o `pkg-config sdl2 --libs` ```
hey I want to type if statement with the way 2 but I need to put there a continue and it not working with any ideas ? way 1 to type if ``` if ( x+2 < 0) { y=x+2; } else { y=-(x+2); } ``` way 2 to type if ``` y=(x+2 < 0) ? x+2 : -(x+2) ``` my question how to type continue in the second way something like this : ``` (x==1) ? continue : x+1 ; ``` but this not working for me.
The ternary operator (?) just returns a value (conditionally). You can't use it to execute arbitrary blocks of code. In other words, if you need to conditionally callcontinue, you need to use anifstructure, not a ternary.
So i have this function that reads file, allocates memory, and puts file's content into buffer. I constantly get garbage data in the end though, so i need a way to null terminate the buffer. ``` #include "GetText.h" void GetText(const char* filename, char** buffer) { FILE* file = fopen(filename,"rb"); long file_lenght; if(file) { fseek(file, 0, SEEK_END); file_lenght = ftell(file); rewind(file); *buffer = (char*) malloc(file_lenght + 1); fread(*buffer, 1, file_lenght, file); *buffer[file_lenght] = '\0'; //This line crashed program fclose(file); } } ```
Since the bracket operator has higher precedence than pointer dereference you need to dereferencebufferbefore indexing, like this: ``` (*buffer)[file_lenght] = '\0'; ``` In your program you also need to make suremallocwas successful.
Whenever I run the following, I get undefined references to all the SDL-related functions used in my program: ``` cc -lSDL2 -lGL *.o ``` I believe this is caused by the lack of-llinker flags.
GCC arguments are positional, put the link flagsafteryourofiles: ``` gcc *.o -lSDL2 -lGL ``` Also, if you're on a proper full Linux system I'd recommend usingpkg-configto pull compiler/linker flags: ``` gcc -c main.c `pkg-config sdl2 --cflags` gcc main.o `pkg-config sdl2 --libs` ```
hey I want to type if statement with the way 2 but I need to put there a continue and it not working with any ideas ? way 1 to type if ``` if ( x+2 < 0) { y=x+2; } else { y=-(x+2); } ``` way 2 to type if ``` y=(x+2 < 0) ? x+2 : -(x+2) ``` my question how to type continue in the second way something like this : ``` (x==1) ? continue : x+1 ; ``` but this not working for me.
The ternary operator (?) just returns a value (conditionally). You can't use it to execute arbitrary blocks of code. In other words, if you need to conditionally callcontinue, you need to use anifstructure, not a ternary.
I need to check if a int64_t is in the range -UINT32_MAX <= x <= UINT32_max I've tried like so: ``` if(x >= -(UINT32_MAX) && x <= UINT32_MAX) ``` But it seems that -(UINT32_MAX) overflows to 1 Any ideas?
In-(UINT32_MAX), the negation is performed in the typeuint32_t(and the parentheses have no effect). Negating within theuint32_ttype wraps modulo 232, so it produces 1. To truly negateUINT32_MAX, do it in a wider type, as in- (int64_t) UINT32_MAX. Inx >= - (int64_t) UINT32_MAX && x <= UINT32_MAX, theusual arithmetic conversionswill be performed. Given thatxis of typeint64_t, these will not be a problem. However, for some other types, this expression may fail. For example, if the type ofxwereuint64_t, then, inx >= - (int64_t) UINT32_MAX, the right operand would be converted touint64_t, producing a large positive value, and the comparison would not produce the desired result.
How can I compile a C project on macOS 11 (Intel) to work on Silicon? My current build script is as simple as: ``` ./configure make sudo make install ``` I've tried using the--hostand--targetflags withaarch64-apple-darwinandarm-apple-darwinwithout any luck. The binary always defaults tox86_64: ``` > file foobar.so foobar.so: Mach-O 64-bit bundle x86_64 ``` UPDATE:It seems cc and gcc aren't found when--hostis specified. ``` checking for arm-apple-darwin-cc... no checking for arm-apple-darwin-gcc... no ```
I found a hint onthis pageto use this: ``` -target arm64-apple-macos11 ``` When I run this from my mac: ``` clang++ main.cpp -target arm64-apple-macos11 ``` The resulting a.out binary is listed as: ``` % file a.out a.out: Mach-O 64-bit executable arm64 ``` I have XCode 12.2 installed. I don't have an Arm Mac in front of me, so I'm assuming this works.
I want to make a macro to return the real part of a complex number (which will work with double, float and long double types). The GNU C extension__real__seems to fit the bill (although it is not portable unfortunately). I am trying the following: ``` #include <complex.h> #if defined(__real__) #define MYREAL(z) (__real__ z) #endif ``` However it seems that the__real__extension is not defined as a usual macro, so the defined(__real__) test fails, even though it is available. Does anyone know how to test for the existence of__real__to make a proper macro for this? Also, if anyone knows of a portable way to do this, I'd be interested in that solution as well.
Permanual: To test for the availability of these features in conditional compilation, check for a predefined macro__GNUC__, which is always defined under GCC. Hence: ``` #ifdef __GNUC__ #define MYREAL(z) (__real__(z)) #endif ```
How can I remove only the title of the console in C or C++? Remove that: ``` HWND hwnd = GetConsoleWindow(); DWORD style = GetWindowLong(hwnd, GWL_STYLE); style &= ~WS_THICKFRAME; SetWindowLong(hwnd, GWL_STYLE, style); ``` I tried that, but it doesn't work.
You can use the functionSetWindowText, like this: ``` SetWindowText( GetConsoleWindow(), TEXT("") ); ``` This will set the title of the window to an empty string. If you want to remove the entire title bar, then you can use the following code: ``` DWORD style = GetWindowLong( GetConsoleWindow(), GWL_STYLE ); style &= ~WS_CAPTION; SetWindowLong( GetConsoleWindow(), GWL_STYLE, style ); ``` However, moving the window will be a lot harder without a title bar.
``` #include<stdio.h> void main(){ int x = 0x80000000; if((x-1)<1) printf("True"); else printf("False"); } ``` this is from csapp practice 2.44, if this is compiler's operation, how to close it?
Assuming anintis 32 bit, the constant0x80000000is outside the range of anintand has typeunsigned int. When used to initialize anintit is converted in an implementation defined manner. For gcc, that conversion results inxhaving the value -231(whose representation happens to be0x80000000) which is the smallest value it can hold. Then when you attempt to calcuatex-1, it causes signed integer overflow which isundefined behavior. As an example of this, if I compile this code under gcc 4.8.5 with-O0or-O1I get "False" as output, and if I compile with-O2or-O3it outputs "True".
I would like to convert a double into character string and I findgcvt()and_gcvt(). I just wondering what is the difference between them. Both return withchar*and both need value, number of digits and buffer as a given parameters
As per thegoogle search result The_gcvt()function is identical togcvt(). Use_gcvt()for ANSI/ISO naming conventions.
``` #include<stdio.h> void main(){ int x = 0x80000000; if((x-1)<1) printf("True"); else printf("False"); } ``` this is from csapp practice 2.44, if this is compiler's operation, how to close it?
Assuming anintis 32 bit, the constant0x80000000is outside the range of anintand has typeunsigned int. When used to initialize anintit is converted in an implementation defined manner. For gcc, that conversion results inxhaving the value -231(whose representation happens to be0x80000000) which is the smallest value it can hold. Then when you attempt to calcuatex-1, it causes signed integer overflow which isundefined behavior. As an example of this, if I compile this code under gcc 4.8.5 with-O0or-O1I get "False" as output, and if I compile with-O2or-O3it outputs "True".
I'm trying to read an ENTIRE process withReadProcessMemorybut for some reason no matter what, trying to read at low addresses causes the function to fail. For example, if I'm reading from a process, I can access areas of its memory without a problem. But the lower addresses of the process, like 0, can't be accessed andReadProcessMemoryfails on those. Is there some privileges I need to be able to access the ENTIRE process withReadProcessMemory?
Some memory pages are intentionally set to unreadable, especially the first page, because that detects a lot of programming errors. You can determine if you are able to read the memory page in another process withVirtualQueryEx. To determine the size of the memory page useGetSystemInfo. You have to read the memory page by page. Also, check out this article that explains why you should not useIsBadReadPtrinstead ofVirtualQuery:IsBadXxxPtr should really be called CrashProgramRandomly
Example code ``` int main() { char *s = "kut"; char **p = &s; printf("*s: %c\n", *s); printf("s: %p\n", s); printf("&s[0]: %p\n", &s[0]); printf("p: %p\n", p); printf("*p: %p\n", *p); printf("**p: %c\n", **p); printf("p[0]: %s\n", p[0]); printf("&p[0]: %p\n", &p[0]); return 0; } ``` Output: ``` *s: k s: 0x1043acf46 &s[0]: 0x1043acf46 p: 0x7ffeeb853670 *p: 0x1043acf46 **p: k p[0]: kut &p[0]: 0x7ffeeb853670 ``` How does it come that&p[0](address ofp[0]) does print out the stringkut? The output show that the address ofp[0]is the same asp(aspis just a constant pointer pointing to the first element of the array).
For any pointer or arraypand indexi, the expressionp[i]isexactlyequal to*(p + i). Ifi == 0then we havep[0]which is equal to*(p + 0)which in turn is equal to*(p)which is the same as*p. And in your case*pis the same ass.
Good morning, I need help with convert do..while from C to Python "while". I spent a lot of time to create good code but my solution not working. Please show me how Can I convert this "do..while" to Python code. ``` do { while( c < N ) { list[ b ][ c ] = t[ q ]; q++; c++; }; b++; c = 0; } while( b < 6 ); ```
Something like this : ``` while True: while c < N: lst[b][c] = t[q] q += 1 c += 1 b += 1 c = 0 if b >= 6: break ```
I'm calling a function to change an array in C, say ``` int array[3] = {a, b, c} ``` to ``` array[3] = {d, e, f} ``` but, it gives me an error. Is there another way to assign a bunch of values all at once like I can do upon initialization with the braces in C?
You can't assign an array to another array in C. There's not much of a rationale why, it's simply how the language was designed. Some alternatives: structwrapper.typedef struct { int array [3]; } arr_t; ... arr_t arr = {a,b,c}; arr_t arr2 = {d,e,f}; arr = arr2;memcpy.int arr[3] = {a,b,c}; int arr2[3] = {d,e,f}; memcpy(arr, arr2, sizeof arr);memcpy+ compound literal.int arr[3] = {a,b,c}; memcpy(arr, (int[]){d,e,f}, sizeof arr);
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 I am very new to C and I have the following code where I want to double the timeval, how can I do this? ``` #include <time.h> struct timeval t ={1, 10000}; while(1){ //some code to use timeval Here I need to double the timeval. Meaning if the timeval was 1.1 seconds, I need to make t = 2.2 seconds. } ```
You need to doubleboththe microseconds and the seconds. Then you need to check for overflow of the microseconds (if it's larger than one million) in which case you need to add another second and subtract one "second" from the microseconds.
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 I am very new to C and I have the following code where I want to double the timeval, how can I do this? ``` #include <time.h> struct timeval t ={1, 10000}; while(1){ //some code to use timeval Here I need to double the timeval. Meaning if the timeval was 1.1 seconds, I need to make t = 2.2 seconds. } ```
You need to doubleboththe microseconds and the seconds. Then you need to check for overflow of the microseconds (if it's larger than one million) in which case you need to add another second and subtract one "second" from the microseconds.
Hello everyone I've a problem with this code: ``` #define MAX_LIMIT 5 #include <stdio.h> #include <stdlib.h> int main() { char S[MAX_LIMIT]; scanf("%s", S); printf("%s\n", S); } ``` As you can see the "MAX_LIMIT" value is 5 so I don't want the sting "S" to have more than 5 chars... The problem occurs when I give in input words which exceed this limit. For example, if I wrote "1234567890" I expect the printf to print "1234" but it prints "1234567890" and I don't know why... I've also tried to addfflush(stdin);orgetchar();after the input but it doesn't work I've tried withfgets(S, MAX_LIMIT, stdin);and it works but I still don't understand why if I usescanfit doesn't...
try to usefgetsfunction instead ofscanfhttps://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
Is there any way to read input in this format: ``` {int,"string1","string2","string3"} ``` Obviously the printf/scanf functions do not let me ignore quotations so I was wondering how I can bypass this limitation. One way I was thinking was using strtok and ignoring the "{", commas and quotes. Any faster way I may not know of?
You can definitely ignore any characters: ``` char buf[100]; scanf("%99[^{},\"]", buf); ``` This will read intobufthe first token, in your caseint. Repeat this call for all tokens you need.
I have some library written in pure C. Now I'm creating some unit tests but the testing library is written in C++ rather than C. When I pass NULL to API function under test CLion gives me a hint to pass nullptr instead of NULL. Is it safe to pass nullptr to pure C function in this case?
Is it safe to pass nullptr to pure C function in this case? I think it is. Fromthe C++11 standard (4.10 Pointer conversions): Anull pointer constantis an integral constant expression ([expr.const]) prvalue of integer type that evaluates to zero or a prvalue of typestd::nullptr_t. Anull pointer constantcan be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. Anullptrand an intergral constant expression that evaluates to0are equivalent for such conversions.
I am new in C world. I understand C code needs to be build which means compiling the code and producing exectuable. But here on thispageI read this line : A developer typically builds applications against the IDF I know what IDF stands for. What i dont understand is meaning of this line. What is the meaning of building C application against something?
It is just poor English, a sort of slang in the computer world. It would be better expressed as ``` A developer typically builds applications using IDF. ``` In the context of the paragraph (thanks for the link) this might also include using IDF tools, and certainly involves using the IDF framework.
This question already has answers here:How do I byte-swap a signed number in C?(3 answers)Closed2 years ago. I have an arrayint16_t arr[4];. What I want to do is to convert a value in this array to little endian. For example, let us say I have 0x1d02 on the first index, but I need 0x21d there. Is there any elegant way of converting that and writing it back to the array or how are these things done? Note that I just expressed myself in hex, because its easier to see the problem.
``` #define BS16(x) (((x) >> 8) | ((x) << 8)) ``` ``` int main(void) { uint16_t arr[] = {0x1122, 0x2233, 0xaabb}; printf("%hx %hx %hx\n", BS16(arr[0]), BS16(arr[1]), BS16(arr[2])); arr[0] = BS16(arr[0]); } ```
What is the difference between uppercase and lowercaseprintf()function in C? I'm usingcontikiOS and in some files uppercaseprintfdoesn't work but lowercase does. ``` if (addr == NULL) { uip_create_linklocal_rplnodes_mcast(&tmpaddr); addr = &tmpaddr; printf("RPL: Sending a DIS to\n "); PRINT6ADDR(addr); PRINTF("\n"); uip_icmp6_send(addr, ICMP6_RPL, RPL_CODE_DIS, 2); } ```
The uppercasePRINTFadPRINT6ADDRare probably macros defined in one of the project headers for debugging output. Look for the definition with a search tool such asgrepor with your IDE. A simple search on an Internet search engine finds these matches: http://contiki.sourceforge.net/docs/2.6/a00417_source.htmlhttps://github.com/contiki-os/contiki/blob/master/core/net/ipv6/uip-icmp6.c
The following is from the man page ofsignal The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigac‐ tion(2) instead. See Portability below. Does that mean that we should always use thesigactioncall instead of usingsignal?
Yes. You've already identified the Linux reference, andPOSIX says the same thing: Thesigaction()function supersedes thesignal()function, and should be used in preference. sigactionaddresses the historical inconsistencies insignalby forcing the user to make decisions about syscall interruption (SA_RESTART),handlerinterruption (sa_mask, SA_NODEFER), child handling (SA_NOCLD[WAIT|STOP]), disposition permanence (SA_RESETHAND), and more.
What is the difference between uppercase and lowercaseprintf()function in C? I'm usingcontikiOS and in some files uppercaseprintfdoesn't work but lowercase does. ``` if (addr == NULL) { uip_create_linklocal_rplnodes_mcast(&tmpaddr); addr = &tmpaddr; printf("RPL: Sending a DIS to\n "); PRINT6ADDR(addr); PRINTF("\n"); uip_icmp6_send(addr, ICMP6_RPL, RPL_CODE_DIS, 2); } ```
The uppercasePRINTFadPRINT6ADDRare probably macros defined in one of the project headers for debugging output. Look for the definition with a search tool such asgrepor with your IDE. A simple search on an Internet search engine finds these matches: http://contiki.sourceforge.net/docs/2.6/a00417_source.htmlhttps://github.com/contiki-os/contiki/blob/master/core/net/ipv6/uip-icmp6.c
The following is from the man page ofsignal The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigac‐ tion(2) instead. See Portability below. Does that mean that we should always use thesigactioncall instead of usingsignal?
Yes. You've already identified the Linux reference, andPOSIX says the same thing: Thesigaction()function supersedes thesignal()function, and should be used in preference. sigactionaddresses the historical inconsistencies insignalby forcing the user to make decisions about syscall interruption (SA_RESTART),handlerinterruption (sa_mask, SA_NODEFER), child handling (SA_NOCLD[WAIT|STOP]), disposition permanence (SA_RESETHAND), and more.
I'm learning pointers and memory allocation with C. I've used the snippet below to manually allocate some bunch of bytes to copy: ``` char *s = get_string("s: "); // this is included in cs50 library and it returns a char pointer char *t = malloc(strlen(s) + 1); // +1 for "\0" ... free(t); ``` My question is this, why do we declaretas it points to a char value? How doesmallocknow that the pointertpoints at acharvalue, even if we did not enter any "clue" about usingchar?
It doesn't, and it doesn't need to.mallocallocates a block of exactly as many bytes as you tell it to, and returns avoid*pointer to it. The pointer is then implicitly converted tochar*when the assignment is made. Seethisfor more insight.
``` char *s1 = "emma"; char *s2 = s1; s2[0] = toupper(s2[0]); printf("%s\n", s2); printf("%s\n", s1); ``` I am messing and studying with pointers but i don't quite understand why i'm getting a segmentation error here. I know that toupper function requires a char but isn't 0'th element of string s2 a char? I know it's a pointer but it's pointing at a char right? What's the case here?
i don't quite understand why i'm getting a segmentation error here. Code attempts to modify astring literal. That is UB. Make a copy. UB: Undefined behavior - might work, might fail in obvious or bizarre ways.
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 Is it possible to get row and colum of matrix given cell, row length and col length ? example : matrix 10x10 cell : 4 should be: [0,3]
Assuming row major ordering ``` i = col j = row k = element number l = width i = k % width j = floor( k / width ) ```
I am trying to print eachcharinsarray one at a time. The program I have printed all the letters after the defined index in the array. The problem I am facing is after that the user inserts the phrase then it is allocated. How do you call letters from the string using pointers? Can you usestrtokto split this string, I tried setting thedelimto "" got no output. In other word make it a list like a Pythonsplit(). ``` #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { char *s; s = malloc(1024 * sizeof(char)); scanf("%[^\n]", s); s = realloc(s, strlen(s) + 1); //printf("%s \n", s); for (int i = 0 ; i <strlen(s); i++){ printf("%s \n", &s[i]); } return 0; } ```
``` printf("%c\n", s[i]); ``` or ``` printf("%c\n", *(s + i)); ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed2 years ago.Improve this question How to define a function in C likeint MatrixPrint(int a[3][3])with integer variables in place of3?
``` int MatrixPrint(int a[int a][int b]) ``` This is not correct. Instead do the following way: ``` int MatrixPrint(int rows, int columns, int a[rows][columns]) ```
i did this code. I tried declaring the array in the struct as well. but i keep on getting an error message. Can someone help me :) Thank you. Have a nice day. ``` #include<stdio.h> struct stack { int arr[5]; int top; }st; void push (int ele) { st.arr[st.top]=ele; st.top++; } int pop() { int item=st.arr[st.top]; st.top--; return item; } void display() { int i; for(i=4;i>=0;i--) { printf("%d\t",st.arr[i]); } } int main() { st.arr[5]={3,6,8,7,5}; display(); } ```
This won't work: ``` st.arr[5]={3,6,8,7,5}; ``` Because you can't assign directly to a whole array at once. What you can do however is initialize the struct along with the array it contains at the point it is defined: ``` struct stack { int arr[5]; int top; } st = { {3,6,8,7,5}, 5}; ```
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 How to define a function in C likeint MatrixPrint(int a[3][3])with integer variables in place of3?
``` int MatrixPrint(int a[int a][int b]) ``` This is not correct. Instead do the following way: ``` int MatrixPrint(int rows, int columns, int a[rows][columns]) ```
i did this code. I tried declaring the array in the struct as well. but i keep on getting an error message. Can someone help me :) Thank you. Have a nice day. ``` #include<stdio.h> struct stack { int arr[5]; int top; }st; void push (int ele) { st.arr[st.top]=ele; st.top++; } int pop() { int item=st.arr[st.top]; st.top--; return item; } void display() { int i; for(i=4;i>=0;i--) { printf("%d\t",st.arr[i]); } } int main() { st.arr[5]={3,6,8,7,5}; display(); } ```
This won't work: ``` st.arr[5]={3,6,8,7,5}; ``` Because you can't assign directly to a whole array at once. What you can do however is initialize the struct along with the array it contains at the point it is defined: ``` struct stack { int arr[5]; int top; } st = { {3,6,8,7,5}, 5}; ```
Is it possible to encode a C char array (char*) in JSON in order to send it through a TCP socket? If so how can I make it and which would be a simple JSON library to use? Thanks,
You probably don't need to use JSON. If you just want to send a simple message (e.g. "Hi, how are ya"), then you can just send the char array. You cannot send JSON, only a char array of JSON (JSON is a data format, not a transfer protocol).Example ``` const char *json = "{\"id\": 12837, \"name\": \"Massimo Isonni\"}" // You would then send json. ``` If you need to serialize a struct into a JSON string, I would recommendthis.
I tried to attach a char vector to a shared memory:shmget()is ok butshmat()returns an error. This is my code: ``` ... ... #define TXTSZ 512 ---main--- char *address; int shm_id; ... if(shm_id = shmget(IPC_PRIVATE, TXTSZ*sizeof(char), IPC_CREAT | 0666) == -1){ perror("Error shmget"); } ... if((address = (char *)shmat(shm_id, NULL, 0)) == (char *) -1){ perror("Error shmat"); } ... ... ```
Classic mistake (usually made withopen()). You're settingshm_idto the result of the comparison, not the ID returned byshmget. You need parentheses around the assignment. ``` if((shm_id = shmget(IPC_PRIVATE, TXTSZ*sizeof(char), IPC_CREAT | 0666)) == -1){ ```
When I execute this code and debug, I see the "h" betweenop1andop2values when I entered two parentheses(). I don't know where it came from. Can you help me to solve this problem? It's about data structure without pointers. I don't know where this garbage value comes from. Problems: ``` op = pop(); printf("op1: %ch\n", op); //() = h op2 = ch; printf("op2: %ch\n", op2); ``` Link below which has full of code.https://paste2.org/yNhFcx5s
The format specifier for char is %c. the extra h added by you is being printed
Why doesthis functionin the Linux kernel take avoid *unusedparameter that serves no purpose in the body of the function?
Because it is a callback. The prototype of all callbacks used in this context must be equal, sometimes may have an unused parameter. kthread_runresquires a function like this in the first parameter: ``` int cb(void *param); ```
``` void makeMoveReplace(); void makeMoveReplace(char board[][SIZE*SIZE], char char1, char char2){ int i=0, j=0; if(char1 == '\n' || char1 == ' ') printf("Error"); for(i; i < SIZE*SIZE;i++){ for(j; j < SIZE*SIZE; j++){ if(board[i][j] == char1) board[i][j] = char2; } } } ``` Conflicting types for 'makeMoveReplace' - The error I get.
Function declaration should match, with the function definition. Change the funtion declaration statement:void makeMoveReplace();tovoid makeMoveReplace(char [][SIZE*SIZE], char, char);
I am using C code with sed. I want to read lines in the interval 1-10,11-20 etc. to perform some calculation. ``` int i,j,m,n; for(i=0;i<10;i++){ j=i+1; //correction. m,n is modified which was incorrect earlier. m=i*10; n=j*10; system("sed -n 'm,n p' oldfile > newfile"); } ``` Ouput. ``` m,n p ``` It looks the variable is not passed in system. Is there any way to do that?
Usesprintfto build the command line: ``` char cmdline[100]; sprintf(cmdline, "sed -n '%d,%dp' oldfile.txt > newfile.txt", 10*i+1, 10*(i+1)); puts(cmdline); // optionally, verify manually it's going to do the right thing system(cmdline); ``` (This is vulnerable to buffer overflow, but if your command-line arguments are not too flexible, 100 bytes should be enough.)
So I want to print an integer array to my document. To do it so I tried these: Changing my integer array to char array: ``` char* intAtocharA(int* k,int n){ char *z = calloc(n, sizeof(char)); for (int i = 0; i < n; ++i) { z[i]=(char)k[i]; } return z; } ``` does not give me an error but won't do what I want. For additional info in my int main I did these: ``` FILE* fout = fopen(argv[1],"w"); char* l =intAtocharA(arr,arrsize); fprintf(fout,l); ``` I don't know if it is relevant but my integer array is full of 1's and 0's
lis an array of (small) integers, not a null-terminated string which is what theprintfformat string is supposed to be. You need to use a loop and print all numbers one by one: ``` for (size_t i = 0; i < arraysize; ++i) { fprintf(fout, "%hhd ", l[i]); } ```
I am using C code with sed. I want to read lines in the interval 1-10,11-20 etc. to perform some calculation. ``` int i,j,m,n; for(i=0;i<10;i++){ j=i+1; //correction. m,n is modified which was incorrect earlier. m=i*10; n=j*10; system("sed -n 'm,n p' oldfile > newfile"); } ``` Ouput. ``` m,n p ``` It looks the variable is not passed in system. Is there any way to do that?
Usesprintfto build the command line: ``` char cmdline[100]; sprintf(cmdline, "sed -n '%d,%dp' oldfile.txt > newfile.txt", 10*i+1, 10*(i+1)); puts(cmdline); // optionally, verify manually it's going to do the right thing system(cmdline); ``` (This is vulnerable to buffer overflow, but if your command-line arguments are not too flexible, 100 bytes should be enough.)
So I want to print an integer array to my document. To do it so I tried these: Changing my integer array to char array: ``` char* intAtocharA(int* k,int n){ char *z = calloc(n, sizeof(char)); for (int i = 0; i < n; ++i) { z[i]=(char)k[i]; } return z; } ``` does not give me an error but won't do what I want. For additional info in my int main I did these: ``` FILE* fout = fopen(argv[1],"w"); char* l =intAtocharA(arr,arrsize); fprintf(fout,l); ``` I don't know if it is relevant but my integer array is full of 1's and 0's
lis an array of (small) integers, not a null-terminated string which is what theprintfformat string is supposed to be. You need to use a loop and print all numbers one by one: ``` for (size_t i = 0; i < arraysize; ++i) { fprintf(fout, "%hhd ", l[i]); } ```
If I execute anexecinto a main process of a program, can I somehow get the PID (Process ID) of the process executed by theexecin order to send interruptions / signals towards it later on?
Yes on linux you can fork a child process and get is PID like inhttps://ece.uwaterloo.ca/~dwharder/icsrts/Tutorials/fork_exec/ ``` #include <stdio.h> int main( void ) { char *argv[3] = {"Command-line", ".", NULL}; int pid = fork(); if ( pid == 0 ) { execvp( "find", argv ); } /* Put the parent to sleep for 2 seconds--let the child finished executing */ wait( 2 ); printf( "Finished executing the parent process\n" " - the child won't get here--you will only see this once\n" ); return 0; } ``` source :https://ece.uwaterloo.ca/~dwharder/icsrts/Tutorials/fork_exec/ getpid()is also in this link
I'm doing the following: ``` static uint32 myReadValue; static uint32 myNewValue; DoRead(10, &myReadValue); myNewValue = (uint32)(&myReadValue) | (3 << 8); ``` whereby ``` void DoRead(SomeEnumType, void * Ptr) { // some functionality } ``` The compiler gives me the messages: ``` "conversion of integer to pointer at assignment" on the assignment of "myNewValue" ``` I don't see exactly what I'm doing wrong there. Any idea?
(uint32)(&myReadValue)isa conversion touint32of a pointer tomyReadValue, not the other way around and this conversion does not happenat assignment... There is something you are not telling us. Post compilable code that produces the proble. The cast is useless anyway, you probably should use this instead: ``` myNewValue = myReadValue | (3 << 8); ```
When using Eclipse for C C++ operations it shows this error. I have installed mingw64 and jdk14, also in the system variables>> added both bin path there. "An internal error occurred during: "Load QML Analyzer". java.lang.NullPointerException"
Just found this on the web. It worked for me. Might help you as well, if you still need it. "If you need the Qt plug-ins, the workaround is to downgrade to Java 14. Otherwise, to get rid of the message box, it is possible to uninstall the Qt plugins: go to the Eclipse menu → (Help →) About Eclipse IDEclick the Installation Details buttonclick the Installed Software tabselect the C/C++ Qt Support featureclick the Uninstall buttonclick Finish"
This question already has answers here:How to implement a "private/restricted" function in C?(7 answers)Closed2 years ago. I have a .c file which contains many functions. I want only one to be called outside the file, this public function calls the private functions and the private function is also call each others. ``` void f() { .... } void g() { f(); .... } void public() { f(); .... } ```
If you declare a function asstatic, it will only be visible by that name from inside that source file (or more accurately, from inside thattranslation unit): ``` static void f() { .... } static void g() { f(); .... } void public() { f(); .... } ```
I'm playing little bit with bitwise operators in c. I have the following: ``` uint32 myValue = 0x00ffffff; ``` I want to add a byte with the value 0x33 to the first byte of myValue to have at the end this: ``` myValue = 0x33ffffff; ``` I'm trying to do it with: ``` myValue = ((myValue & 0xff) << 0) | (0x33u & 0xff); ``` What I'm doing wrong here?
Try this instead : ``` int main() { uint32_t myValue = 0x00ffffff; myValue = myValue | (0x33u << 24); printf("%x\n", myValue); //====> 0x33ffffff } ```
I'm playing little bit with bitwise operators in c. I have the following: ``` uint32 myValue = 0x00ffffff; ``` I want to add a byte with the value 0x33 to the first byte of myValue to have at the end this: ``` myValue = 0x33ffffff; ``` I'm trying to do it with: ``` myValue = ((myValue & 0xff) << 0) | (0x33u & 0xff); ``` What I'm doing wrong here?
Try this instead : ``` int main() { uint32_t myValue = 0x00ffffff; myValue = myValue | (0x33u << 24); printf("%x\n", myValue); //====> 0x33ffffff } ```
I want to define functioncalcin the way : ``` calc(num1,num2,+) ``` returns num1 + num2
You can't do that with functions but you can write a function-like macro: ``` #define calc(a,b,op) ( (a) op (b) ) ``` Examples: ``` #include <stdio.h> #define calc(a,b,op) ( (a) op (b) ) int main() { printf("%d\n", calc(1,1,+)); printf("%d\n", calc(1,1,-)); } ``` More proper and type safe program design would however be to use function pointer templates instead: ``` #include <stdio.h> typedef int opfunc_t (int a, int b); int calc(int a, int b, opfunc_t* op) { return op(a,b); } int add (int a, int b) { return a + b; } int sub (int a, int b) { return a - b; } int main() { printf("%d\n", calc(1,1,add)); printf("%d\n", calc(1,1,sub)); } ``` The latter example is generally the preferred way.
Suppose I have a pointer ``` int *x; ``` Then I need to let the pointer point to an int of value, say 42. Should I do this: ``` *x = 42; ``` or this: ``` int y = 42; x = &y; ``` ? What is the usual practice?
After this declaration ``` int *x; ``` the pointerxeither is equal toNULL(if it is declared outside any function) or has an indeterminate value. So dereferencing the pointer like ``` *x = 42; ``` invokes undefined behavior. You can write either ``` int y = 42; x = &y; ``` or ``` x = malloc( sizeof( int ) ); *x = 42; ```
I am wondering, what does below mean in .h, it has ``` typedef void *(*some_name)(unsigned int); ``` And then in .c ``` some_name rt; some_name State= 0; unsigned int t = 1; rt = (some_name) State(t); ```
It creates an aliassome_namefor a pointer to a function with a return typevoid*and a single unsigned int parameter. An example: ``` typedef void *(*my_alloc_type)(unsigned int); void *my_alloc(unsigned int size) { return malloc(size); } int main(int argc, char *argv[]) { my_alloc_type allocator = my_alloc; void *p = allocator(100); free(p); return 0; } ```
I have QQuickWindow * _mainWindow and in OS Windows I just write ::ShowWindow(reinterpret_cast<HWND>(_mainWindow->winId()), SW_MINIMIZE); and it's works! But I do not know how it make in OS linux, I googled about x11 library, but don't understand how use it. Please help. I try minimize application window because in QML until Windows & Linux Qt has bugs and does not fixed. showMinimize in Qt does not work correctly
``` #include <X11/Xlib.h> #include <QX11Info> // from qt q11extras // function for minimze your app XIconifyWindow(QX11Info::display(), _mainWindow->winId(), QX11Info::appScreen()); ```
I try to get strings from userspace within the kernel module. Till I set my char size manually it seems working properly. However, I need to make it dynamic so if I uselenparameter it shows weird symbols on the end of char. ``` static ssize_t msecurity_write(struct file *filep, const char *buffer, size_t len, loff_t *offset){ char chars[12]; if(copy_from_user(chars,buffer,len)){ return -EFAULT; } printk(KERN_ALERT "Output> %s", chars); printk(KERN_ALERT "lengh> %i", len); return len; } ``` First output is forchar[len]secound has been set manualychar[12]. Even if you printlenit shows value of 12.
C strings are terminated by anullcharacter. This character is not included in any string length calculation but must be included. Thus a string of length 12 will need 13 bytes with the last byte equal to 0.
Suppose I have a structure named 'Item'. I have to make a member of Item double pointer inside another structre. ``` struct Item{ char *name; int price; double weight; }; struct Inventory{ struct Item double* item; int NUMITEMS; }; ```
Unfortunately, the termdouble pointeris ambiguous. It can mean two different things: Pointer to doubledouble *ptr;Pointer to pointerT **ptr;whereTis any type. It could bedouble:) Which of these is depending on context. So in your case, do this: ``` struct Inventory{ struct Item **item; int NUMITEMS; }; ``` Accessing these is not that tricky. You could do something like this: ``` struct Inventory inventory; // Do something struct Item *item = inventory.item[index]; struct Item item2 = *(inventory.item[index]); ```
I'm learning socket programming using bookUnix Network Programming. Here are two pieces of code from this book: As we can see, it callsFD_ISSETafterFD_SETwithout callingselectfunction between them, what's the result? Will it betrueifsockfdis writable? PS: the source codehttp://www.masterraghu.com/subjects/np/introduction/unix_network_programming_v1.3/ch16lev1sec2.html
FD_SETjust sets a bit in a bit mask andFD_ISSETchecks this bit. These calls don't care if this bit represents a file descriptor or not, it is just an integer. If there is nothing in between these calls which manipulates the bit mask (i.e. no call ofselect) then the result ofFD_ISSETreflects exactly what was set withFD_SET.
I need to make sure that a pair of numbers is either (1, 2) or (2, 1). Both x and y are always positive. The code I am using right now: ``` if ((x == 2 && y == 1) || (x == 1 && y == 2)) { return 1; } ``` It looks a little bulky, and I feel like it can be simplified. However, everything I tried resulted in false positives.
This is the most direct way to make this comparison. It is also more readable than any alternative you may come up with, so no need to change it.