question
stringlengths
25
894
answer
stringlengths
4
863
I'm having a bit of difficulty trying to figure out a way to print some numbers in an array. I have an array[0,1,2,3,4,5,6] and I would like print the numbers 0,1,4,5. Is it possible to create a loop that can read the first two numbers skipping the next two and reading the following two numbers.
You can simply use modulo operation on current index to check if this number belongs to "print 2" or "skip 2": ``` int a[17]; int length = sizeof(a) / sizeof(a[0]); for (int i = 0; i < length; i++) { if (i % 4 < 2) printf("%d ", a[i]); } ``` So, foriequal to 0 and 1, it will output value. Fori == 2and...
Withfopen, by setting it towwill automatically clear the file for me. However now I'm trying to do the same thing withopen, ``` int file = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); ``` This won't guarantee that the file is empty and write at the beginning(?). How can I achieve that?
AddO_TRUNC- Initially clear all data from the file.
I build libcurl and run it but it doesnot works when server require digest authentication. I checked the C code and I found that the following part (in http.c in output_auth_headers function) is not build: ``` #ifndef CURL_DISABLE_CRYPTO_AUTH if(authstatus->picked == CURLAUTH_DIGEST) { auth="Digest"; resu...
When configuring, make sure to select--enable-crypto-auth. Like so: ``` ./buildconf && ./configure --enable-crypto-auth ```
I want to calculate the absolute values of the elements of a complex array in C or C++. The easiest way would be ``` for(int i = 0; i < N; i++) { b[i] = cabs(a[i]); } ``` But for large vectors that will be slow. Is there a way to speed that up (by using parallelization, for example)? Language can be either C or ...
Given that all loop iterations are independent, you can use the following code for parallelization: ``` #pragma omp parallel for for(int i = 0; i < N; i++) { b[i] = cabs(a[i]); } ``` Of course, for using this you should enable OpenMP support while compiling your code (usually by using /openmp flag or setting the...
This question already has answers here:Meaning of "| =" operator?(4 answers)Closed7 years ago. I am trying to understand what the C Operator|=do: ``` // Initialize the green led // Enable the clock for PORT D. See Page 216 of the Datasheet SIM_SCGC5 |= (1U<<12); // Enable the mux as GPIO. See Page 193 of the Data...
It is abitwiseOR compound assignment, it is the same as : ``` SIM_SCGC5 = SIM_SCGC5 | (1U<<12); ``` The0x100it is the value 100 inhexadecimal, the 0x prefix means hexadecimal value.
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.Closed7 years ago.Improve this question I just wonder how to findmeanof two numbers without using division. do not use these con...
I think this may be helpful --> ``` int a,b,i,j; if (a>b) { int temp = a; a = b; b = temp; } for(i=a,j=b;i<j;i++,j--) continue; if(i==j)printf("%d\n", i); else printf("%lf\n", (double)(i)-0.5); ```
My homework requires that my name be displayed such that it looks like this: 'Lastname, Firstname'. Last name then [comma space] firstname. While not moving over the rest of the text after that name. This is my code: ``` char str1[11]; char str2[3]; char str3[16]; strcpy (str1,fn); strcpy (str2,", "); strcp...
Assuming you know length of strings, why not do ``` char result[50]; sprintf(result,"%s, %s",ln, fn); ```
For example in the following code: ``` char name[20] = "James Johnson"; ``` And I want to assign all the character starting after the white space to the end of the char array, so basically the string is like the following: (not initialize it but just show the idea) ``` string s = "Johnson"; ``` Therefore, essenti...
i think you want like this.. ``` string s=""; for(int i=strlen(name)-1;i>=0;i--) { if(name[i]==' ')break; else s+=name[i]; } reverse(s.begin(),s.end()); ``` Need to ``` include<algorithm> ```
I'm implementing decimal to binary converter in C. However part of my assignment is to have a space between each 8bits. For example: 00001000 10101010 11111110 00000001 Here is my code: ``` if(decimal >= 0 && decimal <= 2147483647) { printf("%d as a 32-bit binary number is:\n",decimal); for(x=31; x>=0; x--)...
I would use the modulus operator, to say if this is a multiple of 8, then add a space. ``` if (x % 8 == 0) printf(" "); ```
I'm new to c and I'm trying to figure out why my program isn't working. It's supposed to scan 2 lists of arrays and find if a string from any element of an array matches the a string from any element of another array. ``` int i, j; int max; char word1[10][10]; char word2[10][10]; scanf("%d", &max); for(i = 0; i < ...
``` if (word1[i] == word2[j]) ``` word1[i]andword2[j]are both strings , so don't compare like this. Usestrcmpinstead - ``` if (strcmp(word1[i],word2[j])==0) ```
I've got the following Makefile which compiles, creates an executable and then executes it. ``` CC=gcc CFLAGS=-I. DEPS = hellomake.h OBJ = hellomake.o hellofunc.o %.o: %.c $(DEPS) $(CC) -c -o $@ $< $(CFLAGS) hellomake: $(OBJ) $(CC) -o $@ $^ $(CFLAGS) ./hellomake ``` It works perfectly on my local machi...
Yourhellofunc.ois from a different system (tryfile hellofunc.o). Remove it and then recompile it. Were you cross-compiling? Do you have a home directory mounted on different machines? Perhaps unpacking an archive made by someone else on a different architecture?
I build libcurl and run it but it doesnot works when server require digest authentication. I checked the C code and I found that the following part (in http.c in output_auth_headers function) is not build: ``` #ifndef CURL_DISABLE_CRYPTO_AUTH if(authstatus->picked == CURLAUTH_DIGEST) { auth="Digest"; resu...
When configuring, make sure to select--enable-crypto-auth. Like so: ``` ./buildconf && ./configure --enable-crypto-auth ```
I want to calculate the absolute values of the elements of a complex array in C or C++. The easiest way would be ``` for(int i = 0; i < N; i++) { b[i] = cabs(a[i]); } ``` But for large vectors that will be slow. Is there a way to speed that up (by using parallelization, for example)? Language can be either C or ...
Given that all loop iterations are independent, you can use the following code for parallelization: ``` #pragma omp parallel for for(int i = 0; i < N; i++) { b[i] = cabs(a[i]); } ``` Of course, for using this you should enable OpenMP support while compiling your code (usually by using /openmp flag or setting the...
This question already has answers here:Meaning of "| =" operator?(4 answers)Closed7 years ago. I am trying to understand what the C Operator|=do: ``` // Initialize the green led // Enable the clock for PORT D. See Page 216 of the Datasheet SIM_SCGC5 |= (1U<<12); // Enable the mux as GPIO. See Page 193 of the Data...
It is abitwiseOR compound assignment, it is the same as : ``` SIM_SCGC5 = SIM_SCGC5 | (1U<<12); ``` The0x100it is the value 100 inhexadecimal, the 0x prefix means hexadecimal value.
Suppose there are two arrays e.g ``` char arr1[10]="12345"; char arr2[4][4]={"0","-1"}; ``` I want to copy item at index 1 in arr1 into arr2 at index 1. How can i do this ? I have tried this ``` strcpy(arr2[1],arr1[1]) ``` But i am not able to copy.
copy the characteradd the terminating null character code: ``` char arr1[10]="12345"; char arr2[4][4]={"0","-1"}; arr2[1][0] = arr1[1]; /* 1 */ arr2[1][1] = '\0'; /* 2 */ ```
When you have the statement: *str++ = *end Does the*strget assigned the value of*endor does it get incremented and then get assigned the value of*end?
As apost-increment operator, it first assigns*endthen points to new/incremented address ofstr.
This question already has answers here:What is the purpose of a these #define within an enum?(5 answers)Closedlast year. Why netinet/in.h defines constants this way? ``` enum { IPPROTO_IP = 0, #define IPPROTO_IP IPPROTO_IP IPPROTO_HOPOPTS = 0, #define IPPROTO_HOPOPTS IPPROTO_HOPOPTS I...
There's probably other code relying on#ifdef IPPROTO_IPetc.
for example 10'00'11'01'01 -> 01'00'11'10'10 ``` void main() { unsigned int num = 78; unsigned int num2 = change_bit(num); printf("%d\n", num2); //141 } ``` I need a function like that.
From what I see, it seems that you need a function that swaps position of every 2 bits in a number. few examples: 10'00'11'01'01 -> 01'00'11'10'1011'01'10'10'11 -> 11'10'01'01'11 for this operation, a very simple function is following: ``` unsigned int change_bit(unsigned int num) { return ((num & 0xAAAAAAAA) >...
``` #include <stdio.h> int main() { char gradesList[5]; gradesList[2] = "X"; printf("%c", gradesList[2]); } ``` When I try to run this code I get these errors: Incompatible pointer to integer conversion Assignment makes integer from pointer without a cast
You have to assign acharnot apointer to a string literal. Use'instead of" ``` gradesList[2] = 'X'; ``` In C string literals are represented using double qoutes, i.e. " . And char are represented using single quotes, i.e. ' . Since you have declaredgradesListas achararray. And are trying to assign a pointer to a st...
I am new with c and I'm trying to use doubles variable. Unfortunately, the compiler (Code::Blocks) seems to ignore absolutely what i'm writing. ``` #include<stdio.h> int main() { double x=1.03; printf("x: %lf",x); return 0; } ``` and the output is: ``` x: 0.000000 ``` what is the problem?
Use%finstead of%lf. Doubles only need%f; see the "specifiers" tablehere. Ifprintfis looking for a larger value than you are providing, what prints out will be affected by what happens to be in memory near thexargument that you provided. In this case, I'm guessing that's0. Edit: Thanks to @Olaf for pointing out tha...
I want to write a program which executes the Linuxlscommand. I really only want to type inlsand not/bin/ls, so I want to do this usingexecve(execvpis not an option). I tried: ``` char *env[] = { "SHELL=/bin/bash", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games", "_=/us...
IfparmList[0]contains justls,execve()won't find thelscommand unless it is in the current directory. Withexecve(), the value of PATH in the environment is immaterial —execve()does not use it. You'd useexecvp()(orexecvpe()if it is available) to execute the command on the current process's PATH.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve...
Should be: ``` #include<stdio.h> int main() { int i, j, n; scanf("%d",&n); for (i=0;i<=n;i++){ for (j=0;j<=i;j++){ printf("*"); } printf("\n"); } return 0; } ``` You forgot to tell scanf you were reading in an integer by using the %d argument
I'm learning and practicing C. Output formatting aside. I don't understand why "1" is being output for all array elements, or where the number is even coming from. Even if I input 5 "5"s, the output is still always "1". ``` #define LIMIT 5 #include <stdio.h> #include<stdlib.h> void getNums(); int main() { getNu...
resultstores the return value ofscanf, that is, thenumber of matchesin the format string supplied toscanf. What you really want isthe value read, stored inelement: ``` newRay[i] = element; ``` Notes: better useLIMITconsistently. Your program might just be "quick'n'dirty" but you should replace the5in thefor-loop ...
I am creating assembly code from C code withgcc.exe -S -masm=intel -o filename.S filename.c. I declared some variables asexternto allow later linking. I expected something likeextern variablein nasm, but the variable is never mentioned in the assembly file. Is there a way to check if a variable is extern or not? Or c...
If yourexternvariable is not mentioned in the assembly file, you're likely not using this variable. However, even if you were using it, you wouldn't see anything like.extern varnamein assembly as well. GNU assembler treats all undefined symbols as external ones. GCC knows this and doesn't emit.externdirectives. So loo...
This question already has answers here:What is the purpose of a these #define within an enum?(5 answers)Closedlast year. Why netinet/in.h defines constants this way? ``` enum { IPPROTO_IP = 0, #define IPPROTO_IP IPPROTO_IP IPPROTO_HOPOPTS = 0, #define IPPROTO_HOPOPTS IPPROTO_HOPOPTS I...
There's probably other code relying on#ifdef IPPROTO_IPetc.
for example 10'00'11'01'01 -> 01'00'11'10'10 ``` void main() { unsigned int num = 78; unsigned int num2 = change_bit(num); printf("%d\n", num2); //141 } ``` I need a function like that.
From what I see, it seems that you need a function that swaps position of every 2 bits in a number. few examples: 10'00'11'01'01 -> 01'00'11'10'1011'01'10'10'11 -> 11'10'01'01'11 for this operation, a very simple function is following: ``` unsigned int change_bit(unsigned int num) { return ((num & 0xAAAAAAAA) >...
``` #include <stdio.h> int main() { char gradesList[5]; gradesList[2] = "X"; printf("%c", gradesList[2]); } ``` When I try to run this code I get these errors: Incompatible pointer to integer conversion Assignment makes integer from pointer without a cast
You have to assign acharnot apointer to a string literal. Use'instead of" ``` gradesList[2] = 'X'; ``` In C string literals are represented using double qoutes, i.e. " . And char are represented using single quotes, i.e. ' . Since you have declaredgradesListas achararray. And are trying to assign a pointer to a st...
I am new with c and I'm trying to use doubles variable. Unfortunately, the compiler (Code::Blocks) seems to ignore absolutely what i'm writing. ``` #include<stdio.h> int main() { double x=1.03; printf("x: %lf",x); return 0; } ``` and the output is: ``` x: 0.000000 ``` what is the problem?
Use%finstead of%lf. Doubles only need%f; see the "specifiers" tablehere. Ifprintfis looking for a larger value than you are providing, what prints out will be affected by what happens to be in memory near thexargument that you provided. In this case, I'm guessing that's0. Edit: Thanks to @Olaf for pointing out tha...
I want to write a program which executes the Linuxlscommand. I really only want to type inlsand not/bin/ls, so I want to do this usingexecve(execvpis not an option). I tried: ``` char *env[] = { "SHELL=/bin/bash", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games", "_=/us...
IfparmList[0]contains justls,execve()won't find thelscommand unless it is in the current directory. Withexecve(), the value of PATH in the environment is immaterial —execve()does not use it. You'd useexecvp()(orexecvpe()if it is available) to execute the command on the current process's PATH.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve...
Should be: ``` #include<stdio.h> int main() { int i, j, n; scanf("%d",&n); for (i=0;i<=n;i++){ for (j=0;j<=i;j++){ printf("*"); } printf("\n"); } return 0; } ``` You forgot to tell scanf you were reading in an integer by using the %d argument
I'm learning and practicing C. Output formatting aside. I don't understand why "1" is being output for all array elements, or where the number is even coming from. Even if I input 5 "5"s, the output is still always "1". ``` #define LIMIT 5 #include <stdio.h> #include<stdlib.h> void getNums(); int main() { getNu...
resultstores the return value ofscanf, that is, thenumber of matchesin the format string supplied toscanf. What you really want isthe value read, stored inelement: ``` newRay[i] = element; ``` Notes: better useLIMITconsistently. Your program might just be "quick'n'dirty" but you should replace the5in thefor-loop ...
I am creating assembly code from C code withgcc.exe -S -masm=intel -o filename.S filename.c. I declared some variables asexternto allow later linking. I expected something likeextern variablein nasm, but the variable is never mentioned in the assembly file. Is there a way to check if a variable is extern or not? Or c...
If yourexternvariable is not mentioned in the assembly file, you're likely not using this variable. However, even if you were using it, you wouldn't see anything like.extern varnamein assembly as well. GNU assembler treats all undefined symbols as external ones. GCC knows this and doesn't emit.externdirectives. So loo...
I'm learning C, and I am running into some problems which make me write (seemingly) redundant code. I am finding myself writing code like ``` printf("%c", someChar); printf(" "); ``` which (since it is in a loop) would output something like ``` a b c ``` Is there any way to combine these print statements?
just write :printf("%c ", someChar); note the space after%c
This question already has answers here:Division result is always zero [duplicate](4 answers)How to get fractions in an integer division?(2 answers)Closed7 years ago. I want to get the result of a division of two integers. For example the integers 6 and 25. If I divide the integers I get6/25 = 0as the answer. I want t...
Convert the values to floating point first. For example ``` result = (double)a / (double)b. ```
I'm trying to connect a C client to a Python server. The C client sends the length of a string and then one by one sends the characters of the string but as bytes. This is how I send the characters: ``` for ( i = 0; i<length; i++) { ascii = (int)word[i]; --- word is a char [] ascii = htonl(ascii); ...
struct.unpack("!i",el)returns a one-element tuple containing an integer. To convert this integer to the character at that codepoint, usechr: ``` el = chr(struct.unpack("!i",el)[0]) ```
How can we have a user enter three different values on the same line. Something like this:enter three numbers: 1, 2, 3but all three will be stored in 3 different variables. I tried doing something this like this: ``` printf("Enter three numbers: "); scanf("%d %d %d", one,two,three); ``` But this does not work! Her...
``` scanf("%d %d %d", &one, &two, &three); ``` You were close, butscanfdoesn't care about the value of those variables (which is great, because they're most likely not initialized), it cares about their addresses so it can dereference them and write inside.
I create 2 threads without anypthread_exit()and I add 2pthread_join()Is there any problem? Is it possible?
You are not required to callpthread_exit. The thread function can simply return when it's finished. From the man page: An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return ...
I am currently writing a kernel module for Linux and been trying to dynamically allocate a large block of memory and changing its permissions (rwx), but it just won't work. do_mmapandinit_mmseem to be missing (recognized as undefined by the linker). A possible solution might be accessing the kernel's vma but I couldn...
vmalloc_execis not exported for driver use, so you cannot use it. However,__vmalloctakes a page protections argument, so it should do what you want: ``` void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot); ``` So to allocate executable pages, try this: ``` void *p = __vmalloc(size, GFP_KERNEL, PAGE_...
Which numbers can a double type contain? (in C language) I was trying to find the numbers that double can contain in c. I know that a float can contain numbers between -10^38
In C, adoubleisusuallyan IEEE double. I don't know if this is required by the standard, but these days it would be unusual for it to be something else. Here's some info on double precision formats, particularly IEEE:double-precision floating point formats
I have a simple C library that I compile to a.sofile on my linux machine. I'd like to do the same on my Mac, but after I compile and move the library to/usr/local/lib, but I'm not sure how to link it seeing asldconfigisn't a thing. How would I go about doing this?
While Linux has.sofiles, OSX has.dylibfiles. The process is similar, you just invoke compiler as in ``` clang -dynamiclib -o libname.dylib sources.c ```
I am trying toscanfarithmetical operands into variable. I want to put "+" into variable. I tried everything I have found but nothing has worked so far. The best thing I came with is: ``` char plus = "+"; char* c; scanf("%c", &c); if (strcmp(plus, c) == 0) { printf("you have + in variable"); ``` But this does not...
There are multiple errors in there: you declare a char plus and you initialize it with achar*(and not achar).scanfwith%cexpects achar*but you are providing achar**you are comparing acharwith achar*instrcmp If you are dealing with single character operators there's no need to do things more complex than they are: ``...
``` int main() { int longNum = 12345, tempNum[5], i; for (i = 0; i <= 5; i++) { tempNum[i] = longNum[i] ; // not valid, how do i make this work? } printf("%d\n", tempNum); return 0; } ``` Im trying to go through all the digits of longNum and push them into tempNum[].
You may try the modulo operator: ``` int main() { int longNum = 12345, tempNum[5], i; for (i = 4; i >= 0; i--) { tempNum[i] = longNum % 10; longNum /= 10; } for( i = 0; i < 5; i++ ) { printf("%d\n", tempNum[i]); } return 0; } ```
I have some C files that are dependent on iOS 9, (using new features from the accelerate framework) and want to be able to check the current iOS version without using Objective-C. Is there anyway to do this?
Do not check the version of iOS. The proper solution is to check if the desired API is available. In this case you wish to use thevDSP_biquadm_SetTargetsDoublefunction. As described in theSDK Compatibility Guide, the proper way is this: ``` if (vDSP_biquadm_SetTargetsDouble != NULL) { // The vDSP_biquadm_SetTarge...
I am studying for a midterm in C and there is something unclear for me. There is this code in the lectures but there is no extra detail on when and how to use it. The code is: ``` void print_menu(char *options[], int dim); ``` How is that function supposed to be called, with what arguments? I know how to call the...
char* options[]is equivalent tochar** optionswhen it comes to parameters, so passing a pointer to a pointer to acharis alright: ``` char** ptr = malloc(sizeof(char*) * 3); ptr[0] = "entry1"; ptr[1] = "entry2"; ptr[2] = "entry3"; print_menu(ptr, 3); free(ptr); ``` OTOH, an array decays to a pointer when passed to ...
my question deals with creating variables that are visible throughout the program file. In other words, afile-localvariable. Consider this example ``` #include <stdio.h> struct foo { char s[] = "HELLO"; int n = 5; }; struct foo *a; int main() { puts("Dummy outputs!\n"); printf("%s\n",a->s); p...
``` #include <stdio.h> struct foo { char const *s; int n; }; /* static for file-local */ static struct foo a = { "HELLO" , 5 }; int main(void) { printf("%s\n", a.s); printf("%d\n", a.n); return 0; } ```
So I have a total of three drives. C:\ P:\ and X:\ I use the developers console for Visual Studio to make C code (which I write with notepad, cause I'm stubborn.) and I don't know how to change directories from C:\ to P:\ from the Developers Console. Any help would be advised. Notes: I am not an admin, nor do I ...
To change the drive under a Microsoft OS, you type into the console ``` [drive-letter]: ``` and hit enter. In your casedrive-letterisP, so ``` p:{hit the enter key} ``` now you are on that drive. Note: Microsoft Operating systems these commands are not case sensitive.
Suppose I'm not sure how to check what OS I'm running on. So I would like to determine that using the code below: ``` #include <limits.h> ... size_t os_size = sizeof(void*) * CHAR_BIT; ``` Can I rely on it with 100%, or are there any caveats that I need to be aware of? For example: Is it possible that I have a co...
No. as you already mentioned, you could have 32-bit compiler on 64-bit OS. On Linux there is even more interesting case called X32 ABI, where apps are special case of 32-bit, but support native 64-bit registers, native 64-bit math and so on.
This question already has answers here:How to generate a random integer number from within a range(11 answers)How to generate random float number in C(6 answers)generate random double numbers in c++(10 answers)Closed7 years ago. How can i create function in C , which would generate random number }(type double) betwee...
There are several methods. Answer 1 above is ok for min, max as doubles. The important thing to remember forrand()is that it returns a random integer between0andRAND_MAXinclusive.RAND_MAXis a least2^15, but on most systems2^31. If min and max are integers and their difference is less thanRAND_MAXthen a very easy me...
I write two new lines in a file. The new lines are appended to this file. How can print these two new lines to the console. Could you please give me some examples about this? The process is below: fd = open(file , O_WRONLY | O_APPEND, 0666);ret = read(0, buf, 100);write(file, buf, strlen(buf));The problem is 4th pr...
if you want to read back the data you just wrote then you can useftellto get your position in the file then write, thenfseekto reposition to the same point and read
I will be getting three lines of input. The first line will give me 2 integers and the third line will give me 1 integer. But the second line can give me any number of integers ranging between 1 to 100. For example, the input could be: ``` 2 1 5 6 1 9 2 10 ``` or could be: ``` 10 4 5 6 9 ``` I can read the second ...
Read the line into a buffer (@John Coleman) using usingfgets()orgetline().Parse the string looking for whitespace that may contain a'\n', exit loop if found. Then callstrtol()orsscanf()to read the 1 number. Check that function's return value for errors too.Repeat above steps.
I have this code: ``` int suma(int); int produs(int); struct calcul{ int suma(); int produs(); } suma()=1+2+..n;// return S produs()=1*2*..n;// return P ``` I want to call it in main withcalcul sp. How do I call function inside a struct? If I give n a struct type n=5; the result to be sp(15,120). Thanks!!!...
I guess you want something like: ``` struct calcul { int suma(int n) { int result = 0; for (int i = 1; i <= n; ++i) result += n; return result; } //... similar for produs }; int main() { calcul sp; int x = sp.suma(10); }; ```
I have written this easy code ``` void check(uint16_t *m) { while(*m!=0x0D) { if(*m==0x43) //C 0x43 { ... do something } *m++; } } ``` .... // in the main ``` { uint16_t buffer[2]; ...... ...
Sincebufferis already an array of twouint16_ts, and you need to pass auint16_t *tocheck(), then all you need to do is pass the array itself (since it will just decay to a pointer to the first element). So, change: ``` check(&buffer); ``` to: ``` check(buffer); ```
i found a useful page which explainedhow to use double pointers in a linked list. But there are a few points that i could not understand. ``` void AddNodeSorted(node* pNewNode) { node** ppScan = &pRootNode; while(*ppScan != NULL && compare(*ppScan,pNewNode)) ppScan = &(*ppScan)->pNext; pNewNode->pNext = *...
since "ppScan = &(*ppScan)->pNext;","*ppScan = pNewNode;" will let the last element to point to the new node.
Let's say I have aint largeInt = 9999999andchar buffer[100], how can I convertlargeIntinto a string (I triedbuffer = largeInt, doesn't work) and thenfwrite()to a file streammyFile? Now what if I want to write "The large number is (value oflargeInt)." tomyFile?
An example : ``` int largeInt = 9999999; FILE* f = fopen("wy.txt", "w"); fprintf(f, "%d", largeInt); ``` Please refer this link:http://www.cplusplus.com/reference/cstdio/fprintf/ If you want usefwrite, ``` char str[100]; memset(str, '\0', 100); int largeInt = 9999999; sprintf(str,"%d",largeInt); FILE* f = fopen("...
If I want to get a substring between "/" "@", this one will work: ``` char buf[512] ="" ; char src[512] = "iios/12DDWDFF@122"; sscanf( src, "%*[^/]/%[^@]", buf); printf("%s\n", buf); //buf will be "12DDWDFF" ``` How can I get same result from "//^&#@iios////12DDWDFF@@@@122/&*@(@///"; ``` char buf2[512] ="...
You can write yoursscanfstatement as follows - ``` if(sscanf(src,"%*[^0-9]%[^@]",buf2)==1) { //do something } ``` %*[^0-9]will read until number is encountered and then discard it , and%[^@]will read intobuf2until@is encountered. Demo
Simply enough, I'm having an issue where I'm getting a segfault when calling a libnotify function. Erroring code: ``` int lua_libnotify_new(lua_State *L) { const char *summary = luaL_checkstring(L, 1); const char *body = lua_isstring(L, 2) ? lua_tostring(L, 2) : NULL; const char *icon = lua_isstring(L, 3)...
After some tinkering, I realized that it should've been sizeof(NotifyNotification*). Resolved.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I have very complicated problem with this question. This my girlfriend's exam question and I couldn't solv...
``` #include <stdio.h> int main (void) { int x = 3; int p = 8; double y = -3.1415; x = 11 % 3 + 1/x * 3.9 - (double)x; y = -(p/x) * (x/p); printf("%d\n",x); printf("%lf\n",y); return 0; } ```
My question is in thefoo()function, thesavariable seems to be declared and initialized there, however since it is static is it ignored by the compiler after the first time? How come it is not initialized back to the value 10 even if it's static? ``` #include <stdio.h> void foo() { int a = 10; static int sa = 10; a ...
In C,staticmeans that it persists between calls, so it is the opposite of what you suggest: the initializationonlyoccurs on the first call.
If so what technique should I use ? I am thinking about using hippomock as they can be used to mock "C" methods. Are there any better approaches ? If so can anyone give an advice, or do you think unit test for kernel is an overkill ?
Since Linux kernel version 5.5KUnitis available. It's a lightweight unit test framework for the kernel. For more details have a look at https://www.kernel.org/doc/html/latest/dev-tools/kunit/index.htmlhttps://kunit.dev/https://lwn.net/Articles/780985/
I have the following source: ``` int main() { 000J; } ``` With gcc 4.8.4 it compiles without errors. I know there are suffixes like L or U, but I didn't find anything about J. So what does it do?
I get a warning: Imaginary constants are a GNU extension TheJsuffix is a GNU extension, which causes the literal to be of a_Complextype. More info here:https://gcc.gnu.org/onlinedocs/gcc/Complex.html
If so what technique should I use ? I am thinking about using hippomock as they can be used to mock "C" methods. Are there any better approaches ? If so can anyone give an advice, or do you think unit test for kernel is an overkill ?
Since Linux kernel version 5.5KUnitis available. It's a lightweight unit test framework for the kernel. For more details have a look at https://www.kernel.org/doc/html/latest/dev-tools/kunit/index.htmlhttps://kunit.dev/https://lwn.net/Articles/780985/
I have the following source: ``` int main() { 000J; } ``` With gcc 4.8.4 it compiles without errors. I know there are suffixes like L or U, but I didn't find anything about J. So what does it do?
I get a warning: Imaginary constants are a GNU extension TheJsuffix is a GNU extension, which causes the literal to be of a_Complextype. More info here:https://gcc.gnu.org/onlinedocs/gcc/Complex.html
so I have this code: ``` typedef struct node link; struct node {int v; link *next;}; struct graph{int V; int E; link **adj;}; ``` In the first line I get the error "Redefinition of link as different kind of symbol". In the second line and third I get "Unkown type name "link"". Any ideas? EDIT: I changed the nam...
If you're on a POSIX platform (like Linux or OSX) there's a system function calledlink. Structure names, like yourstruct node, lives in a separate name-space (which is why you could do e.g.typedef struct node node;), but type-aliases lives in the same name-space as everything else which means that if you have a funct...
I create 100000 of such structs, by malloc'ing pointers to them. ``` test_struct test { char value[100]; } ``` Does it mean that all char[100] variables (100 * 100000 ~ 10mb) will go to stack memory, exceeding it and causing my program to crash?
No. When you allocate a struct on the heap, all of its members go on the heap as well.
I have recently inherited an old project to make some optimization and add new features. In this project I have seen this type of condition all over the code: ``` if (int_variable) ``` instead of ``` if (int_variable > 0) ``` I have used the first option only withbooleantype of variables. Do you think the first o...
negative numbers evaluate totruealso,so you should go withif (int_variable > 0)to check if a number is positive.
Is the following correct? "A vector in the heap (withsbrkormalloc) starts in the low address and goes to the high ones". For example: ``` int *vec = sbrk(5*sizeof(int)): ``` vec[0]is in the address0x500andvec[1]is in0x504. But in the stack,int vec[5]goes from the high address to the low ones. For example: vec[0...
No, this is not true. Whileusuallythe stack "goes down", this is only valid for adding new objects to it. The content of the objects themselves is still in the same order as if allocated on the heap. Else you could not do pointer arithmetics.
I'm hoping to do some benchmarking of CBC-MAC in C. Does anyone know of a robust C implementation? I've looked around but CBC-MAC implementations (in almost any language) seem to be quite rare. Does anyone know why beside its rather restrictive (desired) use cases, e.g., fixed-length input. Thanks
If you encrypt a message with ablock cipherinCBC modewith azero Initialization Vector, then the last encrypted block, is theCBC-MAC. So if you have ablock cipherimplementation that supportsCBC mode, you basically have support forCBC-MAC.
Programming the msp430, I have a string declared using the.stringdirective: ``` message: .string "Hello World" ``` I want to reference that outside the module, so I.def'd it: ``` .def message message: .string "Hello World" ``` In C, I want to reference the string, but get the wrong character: ``` extern ...
Useextern char message[];. When you declare it as a pointer you're sayingmessageis a value that only takes 2 bytes of memory and stores an address. When declare it as array ofcharyou're saying that's a sequence of 1 byte characters, which is what a string is.
I'm trying to create a struct at a specific location in memory: ``` struct inRAM *ptr = (struct inRAM*)malloc(sizeof(struct inRAM)); ``` But this line only allocates the memory at a place in RAM that is not retainable. I need to malloc beginning at a specific memory address for it to work properly, but how?
For embedded systems where you need to access specific memory addresses for I/O, you normally write directly to the address. You don't need to malloc here, that's used to manage blocks of memory or structures where you don't care where it will be located. e.g. to write to address c00010 ``` ptr = c00010; ptr->field...
I've been trying to learn structs in C and can't figure out how to make this code to work. I keep getting this error: ``` incomplete type 'struct card' struct card aCard = {"Three", "Hearts"}; ^ test.c:2:8: note: forward declaration of 'struct card' struct card aCard = {"Three", "Hearts"}; ``` The code: ``...
First you need to define the structure: ``` struct card { char type[4]; int value; }; ``` And then you can declare it : ``` struct card card1; /*Declaration card1 of type card*/ ```
I was wondering, when you see an API that says that a character buffer should beat leastXXX byte long, does it include the null terminating character? Not that I mind sparing a byte, but this thing bugs me... (no double meaning here!) From the Mac OS X manpage forif_indextoname: The if_indextoname() function maps th...
The character buffer is aNULterminated string. Therefore the buffer needs to be large enough to hold the string, including theNUL.
So when looking into getting my define macro to work, I found the#and##macro helpers, and used them to simplify my macro. The key part of the macro sets a variable to a string containing the name of the variable (but not the variable name alone). As a simplified example, let's take a macro calledSET(X)that should expa...
#define SET(x) x = "pre_"#x C does string concatenation at compile time, so two string literals next to each other are concatenated. "hello " "world"->"hello world"
Linus Torvalds has recently made it to mainstream news with a rant over a pull request. This pull request included a function,overflow_usub, which is apparently non-standard and uses some kind of compiler magic. As a result of the widespread reporting of this rant, it is near-impossible to find any useful information ...
The functionoverflow_usubis defined as: ``` static inline bool overflow_usub(unsigned int a, unsigned int b, unsigned int *res){ *res = a - b; return *res > a ? true : false; } ``` It will check for integer overflows in subtraction and doesn't involve any compiler magic. It's usually a fallback, if the compiler ...
``` #include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { #ifdef DEBUG printf("Debug!\n"); #endif printf("hello world\n"); } ``` makefile: ``` CC=gcc-5 CFLAGS=-I DEPS=foo.c main: $(DEPS) $(CC) -o foo $(DEPS) $(CFLAGS). debug: CFLAGS += -DDEBUG debug: main ``` when I runmake debug ...
The-Ioption expects an argument, and right now its-DDEBUG.. Either remove the-Ioption, or provide it with an argument. I recommend removing it, since I see nothing that warrants adding a directory to the include search paths.
This question already has answers here:What does i = (i, ++i, 1) + 1; do?(7 answers)Closed7 years ago. What exactly is this called in C? If I have int x = 3 * (4, 5); I end up with 15. Can someone give explanation? Is this a list where the result is just the first number times the last one? Thanks
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). https://en.wikipedia.org/wiki/Comma_operator So, the result of the(4, 5...
This question already has an answer here:Syntax error near unexpected token '(' when using terminal [closed](1 answer)Closed7 years ago. I am having problem with the following code ``` #include <stdio.h> int main() { int tall = 175; int weight = 68; printf("I am %d slim.\n", tall); printf("I am %d ...
It seems that you are not compiling your program, but that you are trying to execute it without compiling. The errors that you see is/bin/bashthat tries to interpret this as shell code.
I am using a C libtrary with ``` #define read _io_read ``` but I have a C++ class which inherits a member function 'read'. I am trying to call the member function from another member function but the compiler thinks I am trying to call the C function in the global scope. I tried the following ``` //header name...
You could use: ``` int B::do_read(){ #undef read this.read(); // here is where compiler resolves to _io_read #define read _io_read } ```
I am reading through the document of zlib, and it is fairly detail. But I read upon this line: The output data will be in thezlibformat, which is different from the gzip orzipformatshttp://www.zlib.net/zlib_how.html It seems that zlib createszlibformat which is not the same aszipformat as is discussed in this SO: H...
As @Jongware mentioned, you can find an example in thecontrib/minizipfolder of the source code library. OR ! You can simply uselibzip. Possible duplicate:Simple way to unzip a .zip file using zlib
I'm trying to compile thisprogrambut when I try to execute themakecommand I get an error: (I'm using Ubuntu in Spanish)It says that it goes to directory /home, but then it says that "there is no rule to build the objective sub_all. Stop.". Then it exits the directory /home and finally stops, with the "[top] Error 2"...
You need to downloadthe entire project, not just therandsubdirectory. The Makefile says: ``` # # OpenSSL/fips-1.0/rand/Makefile # ``` So you will have: ``` /home/usuario/Desktop/OpenSSL-38/ ``` andrandwill then be at ``` /home/usuario/Desktop/OpenSSL-38/openssl/fips-1.0/rand/ ```
``` testb $1, %al je .L3 leal 1(%eax,%eax,2), %eax jmp .L4 ``` I am given the above assembly code and asked to translate it to c code. I know what almost all of it is doing, I just don't know how to to do C code for the%alregister. Here Is the rest of the assembly code if it helps ``` prob2: pushl %ebp ...
Doesn't matter here. Bit0 inALis the same as Bit0 inEAX. The 8-bit operation was surely an optimization of the compiler. So you can readALasEAX.
I am using a C libtrary with ``` #define read _io_read ``` but I have a C++ class which inherits a member function 'read'. I am trying to call the member function from another member function but the compiler thinks I am trying to call the C function in the global scope. I tried the following ``` //header name...
You could use: ``` int B::do_read(){ #undef read this.read(); // here is where compiler resolves to _io_read #define read _io_read } ```
I am reading through the document of zlib, and it is fairly detail. But I read upon this line: The output data will be in thezlibformat, which is different from the gzip orzipformatshttp://www.zlib.net/zlib_how.html It seems that zlib createszlibformat which is not the same aszipformat as is discussed in this SO: H...
As @Jongware mentioned, you can find an example in thecontrib/minizipfolder of the source code library. OR ! You can simply uselibzip. Possible duplicate:Simple way to unzip a .zip file using zlib
I'm trying to compile thisprogrambut when I try to execute themakecommand I get an error: (I'm using Ubuntu in Spanish)It says that it goes to directory /home, but then it says that "there is no rule to build the objective sub_all. Stop.". Then it exits the directory /home and finally stops, with the "[top] Error 2"...
You need to downloadthe entire project, not just therandsubdirectory. The Makefile says: ``` # # OpenSSL/fips-1.0/rand/Makefile # ``` So you will have: ``` /home/usuario/Desktop/OpenSSL-38/ ``` andrandwill then be at ``` /home/usuario/Desktop/OpenSSL-38/openssl/fips-1.0/rand/ ```
``` testb $1, %al je .L3 leal 1(%eax,%eax,2), %eax jmp .L4 ``` I am given the above assembly code and asked to translate it to c code. I know what almost all of it is doing, I just don't know how to to do C code for the%alregister. Here Is the rest of the assembly code if it helps ``` prob2: pushl %ebp ...
Doesn't matter here. Bit0 inALis the same as Bit0 inEAX. The 8-bit operation was surely an optimization of the compiler. So you can readALasEAX.
Thesizeof(data_type)operator returns thenumber of bytesand notoctets, so the size of a byte may not be 8 bits. How can one identify the size of a byte in bits on any platform?
I think you can dosizeof(type) * CHAR_BITto determine the number of bits. Include limits.h for the definition of CHAR_BIT.
If I dosizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare acharvariable and initialize it like so: ``` char val = 'r'; printf("%d\n", sizeof(val)); ``` The output indicates that 'r' only requires 1 byte in memory. Why is this so?
This is because the constant'c'is interpreted as anint. If you run this: ``` printf("%d\n", sizeof( (char) 'c' ) ); ``` it will print1.
``` for (n=0;n<sizeof(arr)/sizeof(*arr); n++) ``` i got this piece of code and don't know what this '/' does. is it just a arithmetic operater and means 'divide by' ? 'arr' is my array, so does it just divide the size of my array by the size of the array itself? I'm confused
/is the division operator andsizeof arr / sizeof *arris the idiomatic way to get the number of elements of an array (number of bytes of the array / number of bytes of the first element of the array).
Thesizeof(data_type)operator returns thenumber of bytesand notoctets, so the size of a byte may not be 8 bits. How can one identify the size of a byte in bits on any platform?
I think you can dosizeof(type) * CHAR_BITto determine the number of bits. Include limits.h for the definition of CHAR_BIT.
If I dosizeof('r'), the character 'r' requires 4 bytes in memory. Alternatively, if I first declare acharvariable and initialize it like so: ``` char val = 'r'; printf("%d\n", sizeof(val)); ``` The output indicates that 'r' only requires 1 byte in memory. Why is this so?
This is because the constant'c'is interpreted as anint. If you run this: ``` printf("%d\n", sizeof( (char) 'c' ) ); ``` it will print1.
``` for (n=0;n<sizeof(arr)/sizeof(*arr); n++) ``` i got this piece of code and don't know what this '/' does. is it just a arithmetic operater and means 'divide by' ? 'arr' is my array, so does it just divide the size of my array by the size of the array itself? I'm confused
/is the division operator andsizeof arr / sizeof *arris the idiomatic way to get the number of elements of an array (number of bytes of the array / number of bytes of the first element of the array).
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.Closed7 years ago.Improve this question I would like to generate a random string of only lower-case ASCII characters (meaning low...
``` #define N 588 #include <stdlib.h> #include <time.h> void gen(char *dst) { int i, n; srand(time(NULL)); /* init seed */ if ((dst = malloc(N)) == NULL) /* caller will need to free this */ return; for (i = 0; i < N; ) if ((n = rand()) < 'A' && n > 'Z') d...
I have started learning C language now a while ago. Let's say i want to add the birth date, month and year of a random person. So the user types the date, month and year in the program. I want it to be displayed like this! Birthday: 20/12/1987 for example but not with the printf! I want it to be done with the scanf!...
It's really not that difficult. Just try to do it like you asked: For a[integer]/[integer]/[integer]format, just try this: ``` int day, month, year; scanf("%d/%d/%d", &day, &month, &year); ```
I want to create a function like this but with priority. For that, I need the pid, but I don't know how to get it. Any idea? Mine is to usesetpriority (0, pid, value), but I need the pid. ``` void cmd_exec(char * tr[]) { if (execvp(tr[0], tr)== -1) perror("Error"); } ```
To get the process-id of the calling process usegetpid(). Please find the Linux man-page here.current(Issue 7) POSIX documentation here.
My code: ``` #inlcude <math.h> #include "draw.h" /*int draw(int x, int y)*/ draw(rintf(10 * x), rintf(8 * y)); ``` I get this warning: Conversion to ‘int’ from ‘float’ may alter its value. I can't changedrawto float, since I need it to draw points. So rounding is inevitable. Any ideas?
The return type ofrintfisfloatwhich produces the warning. You can either explicitly cast tointto suppress the warning (i.e.,(int) rintf(10 * x), or you could use another way of rounding (e.g., if the values are known to be non-negative,(int) (10.0f * x + 0.5f)) orlrint(preferably fromtgmath.h), although it returns alo...
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.Closed7 years ago.Improve this question I would like to generate a random string of only lower-case ASCII characters (meaning low...
``` #define N 588 #include <stdlib.h> #include <time.h> void gen(char *dst) { int i, n; srand(time(NULL)); /* init seed */ if ((dst = malloc(N)) == NULL) /* caller will need to free this */ return; for (i = 0; i < N; ) if ((n = rand()) < 'A' && n > 'Z') d...
I have started learning C language now a while ago. Let's say i want to add the birth date, month and year of a random person. So the user types the date, month and year in the program. I want it to be displayed like this! Birthday: 20/12/1987 for example but not with the printf! I want it to be done with the scanf!...
It's really not that difficult. Just try to do it like you asked: For a[integer]/[integer]/[integer]format, just try this: ``` int day, month, year; scanf("%d/%d/%d", &day, &month, &year); ```
I want to create a function like this but with priority. For that, I need the pid, but I don't know how to get it. Any idea? Mine is to usesetpriority (0, pid, value), but I need the pid. ``` void cmd_exec(char * tr[]) { if (execvp(tr[0], tr)== -1) perror("Error"); } ```
To get the process-id of the calling process usegetpid(). Please find the Linux man-page here.current(Issue 7) POSIX documentation here.
My code: ``` #inlcude <math.h> #include "draw.h" /*int draw(int x, int y)*/ draw(rintf(10 * x), rintf(8 * y)); ``` I get this warning: Conversion to ‘int’ from ‘float’ may alter its value. I can't changedrawto float, since I need it to draw points. So rounding is inevitable. Any ideas?
The return type ofrintfisfloatwhich produces the warning. You can either explicitly cast tointto suppress the warning (i.e.,(int) rintf(10 * x), or you could use another way of rounding (e.g., if the values are known to be non-negative,(int) (10.0f * x + 0.5f)) orlrint(preferably fromtgmath.h), although it returns alo...
C statement ``` A= A? C[0] : B; ``` Is is correct to write in assembly instruction this way? Assuming$t1=A, $t2=B, $s1=baseaddress of Array C: ``` beq $t1, $0, ELSE lw $t1, 0($s1) ELSE: add $t1, $t2, $0 ```
No, it doesn't seem correct becauseadd $t1, $t2, $0will be executed even if$t1 != $0. I hope that this works (not tested): ``` beq $t1, $0, ELSE sll $0, $0, 0 # NOP : avoid the instruction after branch being executed lw $t1, 0($s1) j END sll $0, $0, 0 # NOP : avoid the ins...
when i use this code, the program aborted after inserting first char when i delete the star(*) inside the function it works but it becomes as C++ referencing . I want to keep it pure (C) ``` void info(char *first, char *second, char *third) { printf("insert three char: "); scanf(" %c %c %c", *first,*second,*...
change your scanf it will work and it is in pure c ``` scanf(" %c %c %c", first, second, third); ``` and you can't do like*firstbecause in scanf it required address of variable so it is aborting after insert of first char in your case. In function you are passing addresses and not reference.