question
stringlengths
25
894
answer
stringlengths
4
863
I am practicing algorithms problems online, and encountered an input problem: I know how to read ``` 1 2 3 -4 5 ``` using ``` int *p = (int*)malloc(sizeof(int) * size); while(scanf("%d", p++) != EOF) { // } ``` But the problem's input is defined as ``` [1, 2, 3, -4, 5] ``` how to read this format input into integer array?
I believe this can get you started, ``` int main () { int size = 5; int *p = (int*)malloc(sizeof(int) * size); char buf[200] = {0}; fgets(buf, 200, stdin); char *token = strtok(buf, "[, "); while(token) { *p = atoi(token); printf("next is %d,\n", *p); token = strtok(NULL, ", "); ++p; } } ``` Note this assumes that you only have an input of 5 numbers.
I have aconst char*which represents a path I want to split it into an array of strings at character/so I can do the search step by step. I tried doing char* str2 = strtok(str1,"/") but my compiler returns a warning: initialization discards ‘const’ qualifier from pointer target type How can I do the split without any warning?
strtok(3)andstrtok_r(3)mutate the string in place, which prevents you from passing a const string. You will want to pass a copy anyway, as you don't want your initial string to be mutated and become unusable. Here's how you can do it withstrdup(3): ``` char* strtmp = strdup(str1); char* str2 = strtok(strtmp,"/"); // Use str2 here free(strtmp); ```
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.
Does anyone recognize what the value 1607293133099 might represent as a "timestamp"? The return data type is defined as: unsigned long long timestamp; .. with no reference point or documentation to tell me what the value represents. The value represents an action completed "now" result; but I am unable to convert it successfully to a datetime that is today's date and time.
Milliseconds since the start of the Unix epoch (1970): Sunday, December 6, 2020, 22:18:53.099 UTC. Is it a timestamp from about 20 minutes before you asked?
What is the time complexity of this little code? ``` int count = 0; for (int i = n; i > 0; i = i/2) { for (int j = 0; j < i; j++) { count++; } } ``` I want to know the time complexity of this code. To me I calculated as O(n log n) because outer loop runslogntimes and inner loop runsO(n)times. But i am confused because the inner loop j depends on i.So what will be the actual time complexity and why?
The exact sum is ``` n + n/2 + n/4 + ... + 1 ``` which is ``` n * (1 + 1/2 + 1/4 + ... + 1/n) ``` The sum of the non-negative powers of 1/2 is well known to approach 2 in the limit, so the total sum approaches2*n. As a result, the complexity isO(n);idecreases quickly enough to avoid thelinarithmicgrowth.
I am trying write a code for program in C, but i found a problem i am not able to solve. I get a set of input, but the input is not always the same. How do i use scanf to read not always the same amount of data? Input 1): ``` + 12345 Lala ``` Input 2): ``` - 12345 ``` If i use something like this: ``` scanf("%s %d %s", a[i], &b[i], c[i]); ``` the terminal requests more data for me (which i understand). So how do i use scanf to sometimes read all three (string, integer, string) and sometimes just two (string, integer)?
Start by reading the whole line ``` char line[100]; scanf(" %[^\n]", line); ``` or ``` fgets(line, 100, stdin); ``` Then usesscanfto read the values from the line. ``` int itemsRead = sscanf(line, "%s %d %s", a[i], &b[i], c[i]); ``` The return value of sscanf will tell you how many values you successfully read from the line.
How should I correctlycheck if given argument is anatural numberin C? I am a very beginner when it comes to C... I already have compared that argument to 1 and 2 by atoi(argv[1]) == 1 ..., but when I pass let's say 1.2137 as an argument, atoi cuts it to 1. Thanks for any help.
You can either uselong strtol(const char* nptr, char** endptr, int base)from the headerstdlib.hto check if your whole string can be converted to a number: ``` char* end; strtol( argv[1], &end, 10 ); if( *end == '\0' ){ printf( "String is a natural number\n" ); } else { printf( "String is not a natural number\n" ); } ``` Another way would be to check for characters that are not '+', '-' or digits ``` bool valid = true; for( const char* it = argv[1]; *it; ++it ){ if(!(( *it >= '0' && *it <= '9' ) || *it == '+' || *it == '-' )){ valid = false; } } printf( "String is%s a natural number\n", valid ? "" : " not" ); ```
Here is the code. ``` #include<stdio.h> int main(int argc,char* argv[]) { fprintf(stderr,"arg count:%d\n",argc); return 0; } ``` When type the following cmd: ``` ./a.out x 3 >1.txt //case1 ``` I got argc 3. (in this case, a.out x and 3) But when type the following cmd: ``` ./a.out x 3>1.txt //case2 ``` I got argc 2. It seems 3>1 was ignored. I expected the argc is 3 like case1. (Clarification: There is a space between 3 and > in case1) Why I got 2nd case? And how to solve it?
First of all you have to remember that all redirection is handled by the shell itself, it's not passed on to the program. The command ``` ./a.out x 3 >1.txt ``` have three arguments toa.out: The command itself,xand3. With ``` ./a.out x 3>1.txt ``` then3>1is all part of the redirection handled by the shell. It will redirect descriptor3to the file1.txt.
i'm trying to input characters to an array ``` char ArrayChar[3] ("Enter: \n"); for (int i=0; i<3; i++) scanf("%c", &ArrayChar[i]); for (int i=0; i<3; i++) printf("%c", ArrayChar[i]); ``` but i can only enter 2 characters and it can only print 2 characters. At first i thought "the size was 3, i enter 2, the last one is probably a \0". So i increase the size to 4 like this: ``` char ArrayChar[4] ("Enter: \n"); for (int i=0; i<4; i++) scanf("%c", &ArrayChar[i]); for (int i=0; i<4; i++) printf("%c", ArrayChar[i]); ``` but it is still stop at only 2. Now my guess is this is an "unidentified behavior" and the reason i got any result is due to a fluke? i need help please.
You need to add 1 space on thescanf(see below" %c"), so that it won't read\ncharacter from previous call. ``` scanf(" %c", &ArrayChar[i]); ```
I cant really update my C++ compiler right now, and would like to know how I can changestoitoatoiwithout getting a compiling error ``` int getInput(int columns) { // declare the variable to hold user input int userInput; string userValue; // prompt for the column number and read the column number cout << "Enter a column between 1 and " << columns << " to play in: "; cin >> userValue; // loop to check the input validation while (!validateUserInput(userValue) || (stoi(userValue) < 1) || (stoi(userValue) > columns)) { // re-prompt the user for the input cout << "Enter a column between 1 and " << columns << " to play in: "; cin >> userValue; } userInput = stoi(userValue); // return the input return userInput; } ```
Firstly, add#include <cstdlib>to your code to useatoiif you don't have that. Then, replacestoi(userValue)withatoi(userValue.c_str()).
I've been tryring to solve this problem for hours now. ``` void replaceLetters(char *text, char original, char new_char) { text = "Randoi"; for(int i = 0; i != '\0'; i++){ if(text[i] == original){ text[i] = new_char; } } ``` if I print out text in this function it's correct, but in the other function where this function is called the text doesn't change and i know there's something wrong with my pointers. Please give me a hint. Tanks a lot.
Please see my code. ``` #include <stdio.h> void replaceLetters(char *text, char original, char new_char) { for(int i = 0; text[i] != '\0'; i++) { if(text[i] == original) { text[i] = new_char; } } } int main() { char text[] = "Randoi"; replaceLetters(text,'n','T'); printf(text); return 0; } ``` The condition of for loop is "for(int i = 0; text[i] != '\0'; i++)"
Allocating and obtaining a pointer of a struct is quite simple: ``` memScoped { val str: StructType = alloc<StructType>() val strPtr: CPointer<StructType> = str.ptr } ``` But I'm struggling to allocate or get pointer of theInt,UInt,Long,ULongand other primitive data types. Neither there is any extension to these types: ``` val intData = 5 intData.ptr // <-- no extension like that ``` Searched a lot, but there seems no documentation for this. Any help is greatly appreciated :)
Michael is totally correct, Kotlin primitive types are not supposed to work like that. As explained in thedocumentation, one should use special types representing lvalues in such cases. Something like this should work: ``` memScoped { val i = alloc<IntVar>() i.value = 5 val p = i.ptr } ```
I need to do something like this: ``` sizeof(int[width][height][8]) ``` but unfortunately in c89 (the standard i have to use) this notation is forbidden, is there any way to do the same thing but using pointer notation? Here's the error i get It works fine in c99 but not in c89
You can write this instead: ``` (sizeof(int) * (width) * (height) * 8) ``` Make sure you put thesizeof(int)first to forcewidthandheightto be converted tosize_tand avoid a potential integer overflow onwidth * height * 8ifwidthandheighthaveinttype.
I have a code (not programmed by me) in which I have some parts where I have something like that: ``` #if CORE_DEBUG ee_printf("State Bench: %d,%d,%d,%04x\n",seed1,seed2,step,crc); #endif ``` My question is: what is the correct way to set up this environment variable? EDIT: I am building the code withthisMakefiles.
It's a compilation flag, like-DCORE_DEBUG. In some build environments you can enable/disable these as part of your build profile.
Allocating and obtaining a pointer of a struct is quite simple: ``` memScoped { val str: StructType = alloc<StructType>() val strPtr: CPointer<StructType> = str.ptr } ``` But I'm struggling to allocate or get pointer of theInt,UInt,Long,ULongand other primitive data types. Neither there is any extension to these types: ``` val intData = 5 intData.ptr // <-- no extension like that ``` Searched a lot, but there seems no documentation for this. Any help is greatly appreciated :)
Michael is totally correct, Kotlin primitive types are not supposed to work like that. As explained in thedocumentation, one should use special types representing lvalues in such cases. Something like this should work: ``` memScoped { val i = alloc<IntVar>() i.value = 5 val p = i.ptr } ```
I need to do something like this: ``` sizeof(int[width][height][8]) ``` but unfortunately in c89 (the standard i have to use) this notation is forbidden, is there any way to do the same thing but using pointer notation? Here's the error i get It works fine in c99 but not in c89
You can write this instead: ``` (sizeof(int) * (width) * (height) * 8) ``` Make sure you put thesizeof(int)first to forcewidthandheightto be converted tosize_tand avoid a potential integer overflow onwidth * height * 8ifwidthandheighthaveinttype.
I have a code (not programmed by me) in which I have some parts where I have something like that: ``` #if CORE_DEBUG ee_printf("State Bench: %d,%d,%d,%04x\n",seed1,seed2,step,crc); #endif ``` My question is: what is the correct way to set up this environment variable? EDIT: I am building the code withthisMakefiles.
It's a compilation flag, like-DCORE_DEBUG. In some build environments you can enable/disable these as part of your build profile.
``` #include<stdio.h> int main(void){ float a = 0.7; if(a<0.7) printf("C"); else printf("c++"); } ``` I was going through a text book test your c skills by an Indian author. I found this question in a floating point problems chapter. I am comparing(0.7<0.7)which is false. So why is the outputcand notc++.
Explanation: 0.7 is double constant (Default). Its binary value is written in 64 bit. Binary value of 0.7 = (0.1011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011) Now here variable a is a floating-point variable while 0.7 is double constant. So variable a will contain only 32 bit value i.e. ``` a = 0.1011 0011 0011 0011 0011 0011 0011 0011 while 0.7 = 0.1011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011.... ``` It is obvious a < 0.7
``` char port = 0xa5; ``` I wonder how the expression below evaluated according to standard. ``` (uint8_t) (~port) >> 4 ``` Does left argument first converted to uint8_t and then promoted to int or vice versa?
Casts havehigher precedencethan bit shifts, so the cast should be executed first. I also foundthis resourcewhich explains the need for the cast: In this compliant solution, the bitwise complement of port is converted back to 8 bits. Consequently, result_8 is assigned the expected value of 0x0aU.uint8_t port = 0x5a; uint8_t result_8 = (uint8_t) (~port) >> 4; Note that thecomplementis converted to 8 bits, not the final result of the entire expression.
I got a structure like this in a header file : ``` typedef struct { LIGNE *precedent; PERSONNE individu; LIGNE *suivant; } LIGNE; ``` But when I compile, I got this error : ``` error: unknown type name ‘LIGNE’ LIGNE *precedent; ^~~~~ error: unknown type name ‘LIGNE’ LIGNE *suivant; ``` I don't understand where is the problem.
As said in the commants and in theTomo Ceferin's answer, your compiler has no idea of whatLIGNEis until line 5. One solution would be to typedef your structure before its declaration: ``` typedef struct S_LIGNE LIGNE; struct S_LIGNE { LIGNE *precedent; PERSONNE individu; LIGNE *suivant; }; ``` This way, your compiler knoww thatLIGNEis a typedef forstruct S_LIGNE.
I have a complex directory structure for a C project in which CMAKE governs which files are used for a certain project. I tried using CMAKE extensions for VSCode, but it did not work very well. Is there a way to tell VSCode which files exactly are used to be able to navigate through the code?
Open the Command Palette (F1orCtrl+Shift+P), look for "C/C++: Edit configurations (UI)", and add the desired folders under "Include path". This will allow Visual Studio Code's IntelliSense to know where your header files are located. For an optimized experience, don't forget to also set up the path to the compiler, the IntelliSense mode appropriate for that compiler, and the C/C++ standards you are using. PS: For more on how to use VS Code for C and C++ programming, you may be interested inthese lecture notesI wrote for a graduate course I'm teaching.
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed2 years ago. What will compare if two character arrays in C language are compared using "==" ? The answer was Not Equal. ``` char string1 [] = "Hello"; char string2 [] = "Hello"; if (string1 == string2){ printf("Equal"); } else { printf("Not Equal"); } return 0; ``` }
What will compare if two character arrays in C language are compared using "==" ? Arrays base address will be compared. If you want to compare the contents of the arrays you need to usestrcmp.
I want to align a text with the help of a variable using the.*format specifier. Ideally I wanted a space of100length withSome Text Herewritten and then the|sign. But this doesn't seem to work. ``` #include <stdio.h> int main() { int prec = 100; // Assume this value to be calculated somehow and not a constant char s[20] = "Some Text Here"; printf("%.*s", prec, s); printf("|"); return 0; } ``` Why is this so? Thanks in Advance.
The mistake is, that you try to do a precision like with a float (n decimal places). That won't work with a string. You will need to do%*s, not%.*s
I have a complex directory structure for a C project in which CMAKE governs which files are used for a certain project. I tried using CMAKE extensions for VSCode, but it did not work very well. Is there a way to tell VSCode which files exactly are used to be able to navigate through the code?
Open the Command Palette (F1orCtrl+Shift+P), look for "C/C++: Edit configurations (UI)", and add the desired folders under "Include path". This will allow Visual Studio Code's IntelliSense to know where your header files are located. For an optimized experience, don't forget to also set up the path to the compiler, the IntelliSense mode appropriate for that compiler, and the C/C++ standards you are using. PS: For more on how to use VS Code for C and C++ programming, you may be interested inthese lecture notesI wrote for a graduate course I'm teaching.
Here's a test program I made. ``` #include <stdio.h> int main(){ char arr[10]; int res=0, p = 2; scanf(" %c",&arr[1]); if(arr[1]>=48 &&arr[1]<=57){ res = arr[1] * p; } res = res+10; printf("%d",res); } ``` For input2the output is coming110,which would happen when inres = arr[1] * p, instead of2*2, it will be performing50*2(ASCII value of 2). How to correct this and why is it happening?
If you read the character'2'into the array, which you do with"%c"(or" %c"), then the value arriving there will be the ASCII code of "2", not the value 2. The ASCII for "2" is much higher than 2. As Eugene mentions in a comment, the method to adapt to the offset is to subtract the difference of ASCII and "digit-value", most efficiently and self-explainingly by subtracting the character (not the value)'0'.
On my machine, where anintis 32 bits, the following code : ``` int64_t m = (int64_t) 1 << 60; int64_t n = (int64_t) 2048 * 2048 * 2048; ``` gives the mathematically expected results of 2^60 and 2^33 even though the standard seems to say that 1 and 2048 should be treaded as "int". Should I consider that result as luck, or does the C99 standard guarantees that I don't get overflow?
Casting has precedence on many other operations, you can see the order herehttp://users.eecs.northwestern.edu/~wkliao/op-prec.htm So you are actually working with int64_t all the time (as the name says, it's a signed integer with 64 bits) and that's why you don't overflow.
my string starts with abc or abcX, and ends with a number. For example abc0159 or abcX0159. I want to know if i can retrieve the number with sscanf, no matter if 'X' is there or not. ``` #include <stdio.h> void main() { char str1[14] = "abc1234567890"; char str2[15] = "abcX1234567890"; char num[11]; sscanf(str2, "abc%*c%[0-9]", num); //Correct num[0] = 0; sscanf(str1, "abc%*c%[0-9]", num); //Removes first digit (wrong). num[0] = 0; sscanf(str2, "abc%*[X]%[0-9]", num); //Correct. num[0] = 0; sscanf(str1, "abc%*[X]%[0-9]", num); //Gives emty string. } ``` Maybe it just doesn't work with sscanf? Thx.
``` sscanf(str1, "%*[^0-9]%10s", num); ``` works with both strings, with*the value will be read but won't be written into variable, the10protects from buffer overflows.
So I wanted to write a function to calculate the Gcd or HCF of two numbers using the Divison method.This is my code: ``` #include <stdio.h> #include <stdlib.h> void gcd(int x, int y) { int g,l; if (x >= y) { g = x; l = y; } else { g = y; l = x; } while (g % l != 0) { g = l; l = g % l; } printf("The GCD of %d and %d is %d", x, y, l); } int main(void) { gcd(8, 3); return 0; } ``` I am getting no output with this(error?):Process returned -1073741676 (0xC0000094) Is there a problem with my loop?
In: ``` g = l; l = g % l; ``` the assignmentg = lloses the value ofgbeforeg % lis calculated. Change it to: ``` int t = g % l; g = l; l = t; ```
getline reads the input and further modifies it with the help of sscanf, how can I keep spaces in a variable st.m_Jmeno in the form of "something something" ``` while ( getline(&str, &capacity, stdin) != -1 ) { sscanf(str,"%c %s %c %s", znak, st.m_Cislo,uvozovka, st.m_Jmeno); ... ```
You can use a%[pattern to get everything else in the line: ``` sscanf(str,"%c %s %c %[^\n]", &znak, st.m_Cislo,uvozovka, &tmp, st.m_Jmeno); ``` Note that this is (still) dangerous, in that it might overrun either string buffer if the input is too long.
Consider the following program: ``` int main() { int arr[8]; } ``` When compiling with gcc 9.3.0 on linux 20 the disassembly of the file looks like this at the beginning (this is NOT the whole assembly of the code above!): ``` ┌ 72: int dbg.main (int argc, char **argv, char **envp); │ ; var int[8] arr @ rbp-0x30 │ ; var int64_t canary @ rbp-0x8 │ 0x00001169 f30f1efa endbr64 ; test.c:2 { ; int main(); │ 0x0000116d 55 push rbp │ 0x0000116e 4889e5 mov rbp, rsp │ 0x00001171 4883ec30 sub rsp, 0x30 ``` Why is the assembler allocating 0x30 = 48 bytes on the stack whenarris only 8 ints = 8 * 4 bytes long (sub rsp, 0x30)?
That's: 32 bytes for your array8 bytes for astack canaryA further 8 bytes to ensure16-byte stack alignment. Total: 48 bytes.
How can I printf bytes of int when number 255 must be 255 not -1? I can see that when I scanf 128 my program prints -128 but when I scanf 127 my program prints 127. What can I do do printf 128 as 128. ``` #include <stdio.h> union byte_set{ int x; char tab[4]; }; int main(){ union byte_set byte_set; printf("Podaj liczbe: "); if(scanf("%d", &byte_set.x) != 1) { printf("Incorrect input"); return 1; } for(int i = 0; i < 4; i++) { printf("%02d ", *(byte_set.tab+i)); } return 0; } ```
Change the type of thetabfield tounsigned char. Then they'll have the correct values. ``` union byte_set{ int x; unsigned char tab[4]; }; ```
``` #include <stdio.h> int main(int argc, const char *argv[]) { char name1[] = {'f','o','o'}; char name2[] = "foo"; printf("%s\n", name1); printf("%s\n", name2); return 0; } ``` running the code above results in : ``` foox\363\277\357\376 foo Program ended with exit code: 0 ``` So, what's the difference between these 2 initializers?
name1is an array of three characters{'f', 'o', 'o'}. name2is an array offourcharacters{'f', 'o', 'o', '\0'}. printf("%s", ...)expects an array terminated with a null character. Becausename1isn't, you start dereferencing characters past the end of the array which can have the traditional undefined behavior.
I was trying a program which is requesting me to copy odd elements of one array to another array.This is the best logic that i can develeop until now. But it doesn't work properly. Could you please find my mistake and help me to correct it. Thanks in advance :) ``` #include<stdio.h> int main() { int array[10], oddArray[100], i, j = 0; for (i = 0; i < 5; i++) { printf("Element %d:", i + 1); scanf("%d", &array[i]); } for (i = 0; i < 5; i++) { if (array[i] % 2 != 0) { oddArray[j] = array[i]; j++; } } for (int k = 0; k < j; k++) { printf("%d\n", oddArray[j]); } return 0; } ```
Furkan, change the last loop's iterating variable in oddArray from j to k: ``` for(int k=0;k<j;k++) { printf("%d\n",oddArray[k]); } ```
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 I am trying to write a functionisZero(int x)that returns 1 if x is 0, and returns 0 otherwise. How can I only do this with two of the following operators? !~&^|+<<>>
What about!!!x? Look at following diagram for values zero and different than zero: ``` x == 0 | x <> 0 -------+------- !x 1 | 0 !!x 0 | 1 !!!x 1 | 0 ``` Isn't that what you want?
I am currently trying to multiply a__m512dvalue with a__m512ivalue. The__m512dvalue is ln(2), so the result is saved in another__m512dvariable. However, I am not able to find any intrinsics for multiplying a double with an integer in avx512. When I use the_mm512_castsi512_pdintrinsic on the__m512i, I get a wrong value, so I guess that intrinsic is not of much help either. I am glad for any help or workaround. Thanks in advance.
Thanks to @Peter Cordes for pointing out the mistake regarding the difference between casting and converting. The following code allows the multiplication: ``` __m512d a; __m512i b; _mm512_muld_pd(a,_mm512_cvtepi64_pd(b)); ```
So I have this part of code inside the main function: ``` char causatxt[10]; if(causa == CCOLA){ causatxt[0] = "COLA"; } else if(causa == CMURO){ causatxt[0] = "CHOQUE"; } printf("\n\nEl juego ha acabado por un '%s' con los siguientes datos:", causatxt); ``` The problem is that I want to print the sting incausatxtbut if I define char inside theifI get a non defined error and if I do what I've pasted here I can't getcausatxtto be either "COLA" or "CHOQUE". I'm trying to avoid using a for loop to add the characters to every position of the array so I don't know if I'm supposed to use pointers because I'm not that experienced with those, but if using a for loop is the way to go then I guess I'll do that. Thanks!
You can use strcpy from the string.h library ``` #include <string.h> char a[100]; strcpy(a,"test"); ```
``` #include <stdio.h> #include <stdlib.h> double cube(double num) { return num * num * num; } int main(){ Answer(cube(3.0)); return 0; } void Answer(double cube()) { printf("Answer: %.1f\n", cube()); } ``` If you try to run it, doesn't work, at least on my computer. I tried to change some things like adding some more parentheses, but I can't find the solution.
I don't think your code compiles. Here's some quick fixes: ``` #include <stdio.h> #include <stdlib.h> void Answer(double); // forward declaration, you could also define Answer before main double cube(double num) { return num * num * num; } int main(){ Answer(cube(3.0)); return 0; } void Answer(double value) { printf("Answer: %.1f\n", value); } ```
i am trying to make this basic program: -It asks for an input A : if it is a positive integer, thats good, and i can use that on the second part of the program. B : if the input is not a positive integer, it will ask for a new input until it gets a positive integer. ``` #include <stdio.h> #include <stdlib.h> int main() { int number; printf("Please enter a positive integer:\n"); do { scanf("%d", &number); } while (number >= 0); return 0; } ```
You have the loop condition backwards - you're supposed to continue looping as long as the input is not a positive integer: ``` do { scanf("%d", &number); } while (number <= 0); ```
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 I am trying to write a functionisZero(int x)that returns 1 if x is 0, and returns 0 otherwise. How can I only do this with two of the following operators? !~&^|+<<>>
What about!!!x? Look at following diagram for values zero and different than zero: ``` x == 0 | x <> 0 -------+------- !x 1 | 0 !!x 0 | 1 !!!x 1 | 0 ``` Isn't that what you want?
What will be the equivalent code in C for the following C++ code? ``` int main() { //... int count=0; fun(++count); //function call //... } void fun(int &count) //function definition { //... fun(++count); //Recursive Function call //... } ``` Herecountvariable is used to keep a track on number of calls offun()
You might use pointer: ``` int main() { int count = 0; ++count; fun(&count); //function call // ... } void fun(int *count) //function definition { // ... ++*count; fun(count); //Recursive Function call // ... } ```
The function was written to free a list i created earlier... ``` rekord *felszab(rekord *el) { rekord *temp; for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp) { temp=mozgo->kov; free(mozgo); } return el; } ```
You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types
After running the following C program with Valgrind, it says thepackets.payloadvariable is uninitialised. But I cannot figure out why since I've already put "1234567890" inpackets.payload ``` #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct packet { int payload_length; char payload[10]; } packet_t; int main () { packet_t packet; strncpy(packet.payload, "1234567890", 10); puts(packet.payload); } ```
A pointer toa string(a sequence of charactersterminated by null-character) must be passed toputs(). Yourpacket.payloaddoesn't contain terminating null-character, so you cannot use it forputs(). You can useprintf()with specifying length to print to print that: ``` printf("%.*s\n", 10, packet.payload); ```
This question already has answers here:How to read from stdin with fgets()?(6 answers)Closed2 years ago. ``` void name(record *el) { char k[100]; printf("Name: "); fgets(k,100,stdin); printf("\n"); } ``` I'm trying to write a function that reads a line from console and then searches for it in a list. I'm having some problem with reading a whole line. The program just skips the fgets line. The same happens if i try with scanf("%[^\n]%*c").
You probably read an integer before calling the function and the '\n' was left on the input stream. Try calling the function as the first command you do in main and you will see that it works. If you read a number right before the call with scanf for example, you could add a '\n' in the parameter string before calling the fgets: ``` scanf("%d\n", &x); ```
What will be the equivalent code in C for the following C++ code? ``` int main() { //... int count=0; fun(++count); //function call //... } void fun(int &count) //function definition { //... fun(++count); //Recursive Function call //... } ``` Herecountvariable is used to keep a track on number of calls offun()
You might use pointer: ``` int main() { int count = 0; ++count; fun(&count); //function call // ... } void fun(int *count) //function definition { // ... ++*count; fun(count); //Recursive Function call // ... } ```
The function was written to free a list i created earlier... ``` rekord *felszab(rekord *el) { rekord *temp; for(rekord *mozgo=eleje;mozgo=!NULL;mozgo=temp) { temp=mozgo->kov; free(mozgo); } return el; } ```
You call it without the prototype. Compiler assumes int as parameter and return value. Then it sees the definition having other types. Thus conflicting types
``` printf("%i\n",2&2==2); ``` This should print out a 1 but I get a 0, why is this? ``` int ans=2&2; printf("%i\n",ans==2); ``` This prints a 1, how come the first way does not work? This is the case with if statements as well
The order of operations is different than you think it is. A correct way to write it in a single line would be: ``` printf("%i\n", (2 & 2) == 2); // Prints 1 ```
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.Closed2 years ago.Improve this question I'm not too familiar with C, I'm just working through CSAPP, using a Mac Big Sur, and I've tried this with the VSCode terminal, ITerm, and the native mac terminal: ``` #include <stdio.h> int main() { setvbuf(stdout, NULL, _IOLBF, 0); printf( "hello world\n" ); return 0; } ``` ``` $ gcc thatfile.c $ ``` Nothing prints. What am doing wrong?
When you rungcc thatfile.c, this compiles your C code. This creates another file, normally calleda.out, which you have to execute. You can do this by./a.out.
This was asked in a written test of an interview : Question: write a function pointer prototype which takes three integer pointers as arguments and returns character pointer. My answer: ``` char (*funct_ptr) (int *a, int *b, int *c); ``` This was marked wrong. Can anyone please help me with the right answer to this? Thanks in advance.
Your prototype is declared to return a character, not a character pointer. To make the returned thing to a pointer, add*. ``` char* (*funct_ptr) (int *a, int *b, int *c); ```
``` int main() { x=5; printf("%d",x+3); } ``` xcould be either5or8after this example (I know that the output on the screen would be 8.)
The value at the address ofxremains unchanged in this example. Inside theprintf, we first get the value at the address ofxand then add it to 3 and output it to the screen. This is why we use statements likex=x+3to change the value.
I'm working in a project using SIMD instructions and I don´t know exactly how to create a vector aligned in memory. I´m using packets of 128 bits (4 floats per packet). ``` float redVector[vectorSize]; ``` I saw many places where people use structures and the property attribute... Any explanation is welcomed. Thank you guys.
Assuming your compiler supports C11, you can use_Alignas(): ``` _Alignas(16) float redVector[vectorSize]; ``` Some people prefer the more C++ compatible ``` #include <stdalign.h> alignas(16) float redVector[vectorSize]; ``` Pre C11 gcc can use ``` float redVector[vectorSize] __attribute__((__aligned__(16))); ```
I'm trying to read the next new line in a text file and place it into an array, I was able to place the first line to an array. But I want to place each line in the text file into in separate arrays, is there a way to jump to the next line in the text file? Code: ``` while(((ch = getc(file1))!= '\n') && (i < 30)) { day1_array[i] = ch; printf("%c",ch); } ``` Thanks in advance.
Do something like this: ``` while (fgets(buf, MAX_LEN - 1, fp)) { printf("%s", buf); } ``` where buf is some char array, MAX_LEN is the maximum expected line length and fp is the file pointer. The function fgets reads until either (n-1) characters are read, the newline character is read, or the end of file is reached. Must not be in this order, basically whichever come first
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 I have an algorithm that is written in C. I want to use Spark to run it on a cluster of nodes. How can I run my C executable on Spark? I have read about JNI and Java Process to execute my binary.
Here is a nice article from databricks on how we can run c and c++ codes in apache spark. https://kb.databricks.com/_static/notebooks/scala/run-c-plus-plus-scala.html After moving the c/c++ codes to the underlying distributed file system, You can compile the code and run on spark worker nodes.
Anytime I clear build folder in flutter (either withflutter cleanor manually), my jni folder rebuilds (~40 mins). Is that possible to compile library to some binary, and use it from android without breaking any interfaces and functionality? P.S. My library consists of many folders and contains .mk, .c, .cpp, .h files.
Is that possible to compile library to some binary, and use it from android without breaking any interfaces and functionality? Of course yes. Build you libraries like shared.soor static.aand use them like prebuilts. Here the example how to use native prebuilt libraries:How to link .a to .so and create new .so for android Moreover, you can also put them together with the used SDK, NDK, AS, and other thirdparties in Docker image and work with your project from Docker.
You should have a condition which should evaluate to true or false in order for anifstatement to work. I don't understand howp=fopen("test.txt", "r")part of the following code evaluates to true or false since it only contains an assignment operator=and not a==operator. ``` #include <stdio.h> int main() { FILE *p; if(p=fopen("test.txt","r")) { printf("yes\n"); } else printf("no\n"); return 0; ```
From theC11spec, chapter 6.5.16, " An assignment expression has the value of the left operand after the assignment [....]" So basically, you code is same as ``` p=fopen("test.txt","r"); if(p) { // or, if (p != NULL) for ease of understanding // do something } ```
I have 2 structures: ``` typedef struct { int a; } S1; typedef struct { S1[0xff]; } S2; ``` Let's say I only require the element 0xf0 out of S2->S1, and the rest will be zero or whatever, unimportant. I fill the struct like such: ``` S2 g_s2[] = { // 0x00 { 0 }, // 0x01 { 1 } } ``` Is there some way to pad the first X number of elements so I dont have to type {0},{0},{0}, 200 times to get there?
``` S2 g_s2[] = { [0xf0] = 12 }; ``` Here, we are initializing only0xf0th element to 12, remaining elements of the array will be zero.
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 So I'm doing CS50 and struggling with an error that occurs when I include the following two lines: ``` if (int i < (number -1)) if (int i =< number) ``` when compiling, 'error: expected expression' comes under 'int'. Am I using it incorrectly within while if statements?
No you can not declare variable in an if statement. But if you want your variable in a local scope you can create a block and declare your variable, initialize it and use. We have to use <= for checking less than or equal to instead of =< example: ``` { int i =5,number=10; if(i < number-1) { //Add your code } if(i <= number) { //Add your code } } ```
I am running this c program in gcc. The below works for one variable. ``` #define dataBlk_tx0 ((volatile unsigned int *) 0x20000ACB) ``` But if I want to create an array and write to it how would I do this, this array needs to be defined before main? ``` #define dataBlk_tx0 ((volatile unsigned int * x[8]) 0x20000ACB) main{ dataBlk_tx0[0] = 5; } ```
If you want to read or write directly to that address and memory, you can do it like this: InitializedataBlk_tx0as a pointer to the specific memory locationAccess that memory through the pointer. ``` volatile unsigned int * dataBlk_tx0 = (unsigned int *)0x20000ACB; int main () { dataBlk_tx0[0] = 5; return 0; } ``` If you want to create an array in a specific memoryregion(like Flash vs RAM on a micocontroller), then you'll need to look into linker scripts.
You should have a condition which should evaluate to true or false in order for anifstatement to work. I don't understand howp=fopen("test.txt", "r")part of the following code evaluates to true or false since it only contains an assignment operator=and not a==operator. ``` #include <stdio.h> int main() { FILE *p; if(p=fopen("test.txt","r")) { printf("yes\n"); } else printf("no\n"); return 0; ```
From theC11spec, chapter 6.5.16, " An assignment expression has the value of the left operand after the assignment [....]" So basically, you code is same as ``` p=fopen("test.txt","r"); if(p) { // or, if (p != NULL) for ease of understanding // do something } ```
I have 2 structures: ``` typedef struct { int a; } S1; typedef struct { S1[0xff]; } S2; ``` Let's say I only require the element 0xf0 out of S2->S1, and the rest will be zero or whatever, unimportant. I fill the struct like such: ``` S2 g_s2[] = { // 0x00 { 0 }, // 0x01 { 1 } } ``` Is there some way to pad the first X number of elements so I dont have to type {0},{0},{0}, 200 times to get there?
``` S2 g_s2[] = { [0xf0] = 12 }; ``` Here, we are initializing only0xf0th element to 12, remaining elements of the array will be zero.
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 So I'm doing CS50 and struggling with an error that occurs when I include the following two lines: ``` if (int i < (number -1)) if (int i =< number) ``` when compiling, 'error: expected expression' comes under 'int'. Am I using it incorrectly within while if statements?
No you can not declare variable in an if statement. But if you want your variable in a local scope you can create a block and declare your variable, initialize it and use. We have to use <= for checking less than or equal to instead of =< example: ``` { int i =5,number=10; if(i < number-1) { //Add your code } if(i <= number) { //Add your code } } ```
I am running this c program in gcc. The below works for one variable. ``` #define dataBlk_tx0 ((volatile unsigned int *) 0x20000ACB) ``` But if I want to create an array and write to it how would I do this, this array needs to be defined before main? ``` #define dataBlk_tx0 ((volatile unsigned int * x[8]) 0x20000ACB) main{ dataBlk_tx0[0] = 5; } ```
If you want to read or write directly to that address and memory, you can do it like this: InitializedataBlk_tx0as a pointer to the specific memory locationAccess that memory through the pointer. ``` volatile unsigned int * dataBlk_tx0 = (unsigned int *)0x20000ACB; int main () { dataBlk_tx0[0] = 5; return 0; } ``` If you want to create an array in a specific memoryregion(like Flash vs RAM on a micocontroller), then you'll need to look into linker scripts.
I'd like to subscript an array literal at the point of definition, since I don't need the array after that initial access: ``` int func(int index) { return {1, 2, 3, 4, 5}[index]; } ``` Note: the array elements are more complex than this example. Also I'm omitting boundary checks. I'm simply curious whether the C syntax allows this kind of construct/shortcut. Compiling the above code results in: ``` error: syntax error before `{' token ``` The Python equivalent of what I'm trying to achieve in C: ``` def func(index): return [1,2,3,4,5][index] ```
You can use the so-calledcompound literals: ``` #include <stdio.h> int main(void) { printf("%d\n", (int[]){1,2,3,4,5}[2]); return 0; } ``` Refer to C standard draft section6.5.2.5 Compound Literals
How can i do this senquence without a recursive function the mean of ( ^ ) is && in this question in rec i wrote but without i cant get it right ``` Sn(int n) { if (n <= 2) return 1; if (n % 2 == 0) return ex4_rec(n - 1) + ex4_rec(n - 2) + ex4_rec(n - 3); else return ex4_rec(n - 1) - ex4_rec(n - 3); } ```
No recursion: ``` #include <stdio.h> int foo(int n) { long long s0 = 1, s1 = 1, s2 = 1; printf("1, 1, 1"); for (int k = 3; k < n; k++) { long long next; if (k % 2 == 0) { next = s2 + s1 + s0; } else { next = s2 - s0; } printf(", %lld", next); s0 = s1; s1 = s2; s2 = next; } puts(""); return 0; } int main(void) { foo(100); } ``` Edited: moved most functionality out ofmain()
I'm trying to do I/O redirection in the open shell on repl.it. Taking the input from one file to run through the program. Outputting to a new file but nothing shows up? I'm only used to doing it from Windows using the CMD. Shell: ``` ~/maybe-lab6and7$ clang-7 -pthread -lm -o main main.c < address.txt > open.txt ~/maybe-lab6and7$ ```
After compiling and linking your program, if no compile problems and no link problems occur, you will have an executable in the current directory. (Lets say the executable is named:main.) Then, after changing the program permissions somainis executable,you can execute the program similar to: ``` ./main < sourcedata.txt > destinationdata.txt ``` The result is thatmaincan read thesourcedata.txtfile fromstdinand the output from the program (instead of being displayed on the terminal) will be written todestinationdata.txt.
Consider a structure with the following data members: ``` struct Data { unsigned int count; const char *Name; }; ``` A variable of typestruct Datais created later in the code: ``` PERSISTENT(struct Data log); ``` wherePERSISTENT()maps a variable to the battery-backed SRAM memory space. WhenNameis later assigned to in the code (log.Name = "Sensor1";), where does the character string"Sensor1"get stored. From what I understand, the pointerNameis stored in battery-backed SRAM, but does the string it points to get stored in MCU memory? If that is the case, if the MCU is restarted, the string gets lost, but the pointer (stored in battery-backed SRAM) still points to that address which is empty now. Would that be the case? This code is running on an ARM7 microcontroller (LPC2368 to be specific).
The string literals will be stored in the FLASH memory where the.rodatasegment is located.
Greeings, I have a rather peculiar question. I'm currently coding in C and I wanted to implement a shortcut command for the user (CTRL + C) that can be used at any moment during an .exe being run and I have no idea on how to make it, without having to resort toscanf(). I want the user to be able to just cancel whatever he was doing by just pressing that combination of buttons. Is there a way or do İ have to resort to awhilewithscanf()? Thank you in advance!
you can use signals for that .For example you can create a function where there put what ever you want to do lets say : ``` void action(int handle){ //do something here ,put here your code for this user } ``` and in your main function you can handle ctr+c like that : ``` signal(SIGINT,action); ```
This code will take the user input and use it to build blocks. Entering a number between 1 and 8 it should print something like this. ``` ### ### ### ``` I want it to take the integer from the user and instead print the blocks like this. Say the user enters the number 5. Currently you'll get this. ``` ##### ##### ##### ##### ##### ``` However I want it to do this. ``` # ## ### #### ##### ``` Can anyone help me understand how to implement this? ``` #include <cs50.h> #include <stdio.h> int main(void) { int n; do { n = get_int("Size: "); } while (n < 1 || n > 8); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { printf("#"); } printf("\n"); } } ```
changefor (int j = 0; j < n; j++) tofor (int j = 0; j <= i; j++) The number of#will increase with each loop asiincreases
Imagine I have a program with a main function that creates several threads. In each thread I redirect theCTRL + Cinterruption (SIGINT) to afunctionAviasignal(SIGINT, functionA)and in the main process I redirect the same interruption to afunctionB(signal(SIGINT, functionB). When the program is running and the interruptionSIGINTis sent, what will the program do? It will executefunctionAin all threads thenfunctionBin the main process?
Signal handler action (SIG_IGN, SIG_DFL, or a handler function) is a per-process property, not a per-thread property. This means that if say different threads usesigaction()to set the same signal action, then the latest one wins. Furthermore, if you have multiple threads that do not block the signal, the kernel simply chooses one (at random, basically) to use to deliver the signal. That is, it is only delivered once, not once per thread.
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 I need to send a signed short integer but thesendtofunction requires me to give a char buffer. The buffer:char SendBuffer[1024]; I was thinking of making the integer into a string and storing it like that but I am wondering if there is a better way to do it.
Actually, this is the declaration of sendto(): ``` ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen); ``` The buffer is of type void* so you can pass it a pointer to any type of variable. In your case: ``` short your_variable; short *buffer = &your_variable; sendto(sockfd, buffer, sizeof(your_variable), flags, ...); ```
``` int *f1(int i) { return &i; } int main(void) { int x = 10; int *p = f1(x); printf("%d\n", *p); printf("%d\n", *p); return 0; } ``` Even if I write ``` int *p; p = f1(10); ``` This still gives segmentation fault. Can somebody explain, Why is the code not working ?
You're returning the address ofi, which only exists untilf1returns. Oncef1returns,iceases to exist, and the pointer you created is no longer usable. Dereferencing it is undefined behaviour. Maybe you wanted ``` #include <stdio.h> #include <stdlib.h> int *f1(int i) { int *p = malloc(sizeof(int)); *p = i; return p; } int main(void) { int *p = f1(10); printf("%d\n", *p); free(p); return 0; } ```
Using '-' in an identifier cause the error: ``` ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘-’ token ``` Why this happenned?
'-' is not used as token in c standard. Your premise is wrong. - is used as a token. Quote from C11 standard draft: 6.4 Lexical elementsSyntaxtoken: ... punctuator 6.4.6 PunctuatorsSyntaxpunctuator: ... - ... Ellipses represent an omission. When will '-' character be represented in an identifier? Never, I suspect. It would be ambiguous with the minus operators.
I have the following code: ``` #define MAX_NAME_LEN 15 #define PRINT_CELL(x) \ printf("|%" #MAX_NAME_LEN "s|", #x); ``` When I try to compile, I get the following error: ``` main.c:9:21: error: '#' is not followed by a macro parameter 9 | #define PRINT_CELL(x) \ | ^ ``` I'm not quite sure what I did wrong. How do I fix this?
#MAX_NAME_LENis illegal becauseMAX_NAME_LENis not an identifier in the replacement list of thePRINT_CELL(x)macro. Use the following, instead: ``` #define PRINT_CELL(x) printf("|%*s|", MAX_NAME_LEN, #x); ```
i'm trying to read values from a txt file. the following code works well, but it only print the values to the standard output, i don't know how to store those values in a variable. Thankyou in advance. ``` char *value = NULL; double Training[401], Test[50]; int i=0; size_t line_buf_size = 0; while(i<4) { getline(&value, &line_buf_size, in_file); fscanf(in_file,"%s%*[^\n]",value); printf("value %s \n",value); Training[i]=(double)value; // error : pointer value used where a floating point value was expected //printf(" training %d i %d \n",Training[i], i); i++; } ```
I think the problem you are facing is storing your "value" variable (type: char *) into "Training[i]" (type: double). You need to convert from char * to double:https://stackoverflow.com/a/10075336/7440867.
I am trying to build a C program in Eclipse CDT that usesOpusandAlsalibraries. I normally compile the program in command line as follows: ``` cc prog.c -o prog.exe -lopus -lasound ``` but I couldn't achieve the same in eclipse CDT. I add the linker flags at ``` Project > Properties > C/C++ Build > Settings > Tool Settings > GCC C Linker > Miscellaneous ``` resulting command during build by Eclipse is : ``` gcc -lopus -lasound -o "prog" ./src/prog.o ``` How can I make Eclipse put the linker flags at the very end? Otherwise, the code doesn't compile.
Don't add libraries as-lopusunderMiscellaneous. Rather, add them underProject > Properties > C/C++ Build > Settings > Tool Settings > GCC C Linker > Libraries, in theLibraries (-l)listbox. In there, just put the name of the library without the-l. Alternatively, you can list your libraries inProject > Properties > C/C++ General > Paths and Symbols > Libraries.
``` int *f1(int i) { return &i; } int main(void) { int x = 10; int *p = f1(x); printf("%d\n", *p); printf("%d\n", *p); return 0; } ``` Even if I write ``` int *p; p = f1(10); ``` This still gives segmentation fault. Can somebody explain, Why is the code not working ?
You're returning the address ofi, which only exists untilf1returns. Oncef1returns,iceases to exist, and the pointer you created is no longer usable. Dereferencing it is undefined behaviour. Maybe you wanted ``` #include <stdio.h> #include <stdlib.h> int *f1(int i) { int *p = malloc(sizeof(int)); *p = i; return p; } int main(void) { int *p = f1(10); printf("%d\n", *p); free(p); return 0; } ```
Using '-' in an identifier cause the error: ``` ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘-’ token ``` Why this happenned?
'-' is not used as token in c standard. Your premise is wrong. - is used as a token. Quote from C11 standard draft: 6.4 Lexical elementsSyntaxtoken: ... punctuator 6.4.6 PunctuatorsSyntaxpunctuator: ... - ... Ellipses represent an omission. When will '-' character be represented in an identifier? Never, I suspect. It would be ambiguous with the minus operators.
I have the following code: ``` #define MAX_NAME_LEN 15 #define PRINT_CELL(x) \ printf("|%" #MAX_NAME_LEN "s|", #x); ``` When I try to compile, I get the following error: ``` main.c:9:21: error: '#' is not followed by a macro parameter 9 | #define PRINT_CELL(x) \ | ^ ``` I'm not quite sure what I did wrong. How do I fix this?
#MAX_NAME_LENis illegal becauseMAX_NAME_LENis not an identifier in the replacement list of thePRINT_CELL(x)macro. Use the following, instead: ``` #define PRINT_CELL(x) printf("|%*s|", MAX_NAME_LEN, #x); ```
i'm trying to read values from a txt file. the following code works well, but it only print the values to the standard output, i don't know how to store those values in a variable. Thankyou in advance. ``` char *value = NULL; double Training[401], Test[50]; int i=0; size_t line_buf_size = 0; while(i<4) { getline(&value, &line_buf_size, in_file); fscanf(in_file,"%s%*[^\n]",value); printf("value %s \n",value); Training[i]=(double)value; // error : pointer value used where a floating point value was expected //printf(" training %d i %d \n",Training[i], i); i++; } ```
I think the problem you are facing is storing your "value" variable (type: char *) into "Training[i]" (type: double). You need to convert from char * to double:https://stackoverflow.com/a/10075336/7440867.
I am trying to build a C program in Eclipse CDT that usesOpusandAlsalibraries. I normally compile the program in command line as follows: ``` cc prog.c -o prog.exe -lopus -lasound ``` but I couldn't achieve the same in eclipse CDT. I add the linker flags at ``` Project > Properties > C/C++ Build > Settings > Tool Settings > GCC C Linker > Miscellaneous ``` resulting command during build by Eclipse is : ``` gcc -lopus -lasound -o "prog" ./src/prog.o ``` How can I make Eclipse put the linker flags at the very end? Otherwise, the code doesn't compile.
Don't add libraries as-lopusunderMiscellaneous. Rather, add them underProject > Properties > C/C++ Build > Settings > Tool Settings > GCC C Linker > Libraries, in theLibraries (-l)listbox. In there, just put the name of the library without the-l. Alternatively, you can list your libraries inProject > Properties > C/C++ General > Paths and Symbols > Libraries.
i'm trying to read values from a txt file. the following code works well, but it only print the values to the standard output, i don't know how to store those values in a variable. Thankyou in advance. ``` char *value = NULL; double Training[401], Test[50]; int i=0; size_t line_buf_size = 0; while(i<4) { getline(&value, &line_buf_size, in_file); fscanf(in_file,"%s%*[^\n]",value); printf("value %s \n",value); Training[i]=(double)value; // error : pointer value used where a floating point value was expected //printf(" training %d i %d \n",Training[i], i); i++; } ```
I think the problem you are facing is storing your "value" variable (type: char *) into "Training[i]" (type: double). You need to convert from char * to double:https://stackoverflow.com/a/10075336/7440867.
I am trying to build a C program in Eclipse CDT that usesOpusandAlsalibraries. I normally compile the program in command line as follows: ``` cc prog.c -o prog.exe -lopus -lasound ``` but I couldn't achieve the same in eclipse CDT. I add the linker flags at ``` Project > Properties > C/C++ Build > Settings > Tool Settings > GCC C Linker > Miscellaneous ``` resulting command during build by Eclipse is : ``` gcc -lopus -lasound -o "prog" ./src/prog.o ``` How can I make Eclipse put the linker flags at the very end? Otherwise, the code doesn't compile.
Don't add libraries as-lopusunderMiscellaneous. Rather, add them underProject > Properties > C/C++ Build > Settings > Tool Settings > GCC C Linker > Libraries, in theLibraries (-l)listbox. In there, just put the name of the library without the-l. Alternatively, you can list your libraries inProject > Properties > C/C++ General > Paths and Symbols > Libraries.
I have this line of code that I don't understand. ``` char string[100]; while(string[i]) { //statements i++; } ```
This: ``` while (string[i]) { //statements i++; } ``` is strictly equivalent to this: ``` while (string[i] != 0) { //statements i++; } ``` In C an expression if considered as false if its value is 0, and true if its value is different from zero. You could also write this ``` if (Foo) ... ``` instead of : ``` if (Foo != 0) ... ```
I installed MinGW, and i wrote the following code test ``` #include <stdio.h> int main() { #if defined(__WIN32__) printf("hello win."); #else printf("hello unix."); #endif return 0; } ``` then compiled and run. ``` V002294@DESKTOP-A0H4TOJ /c/Users/V002294 $ gcc test.c -o test V002294@DESKTOP-A0H4TOJ /c/Users/V002294 $ ./test.exe hello win. ``` why not"hello unix"?
__WIN32__must be defined given the result your getting. It looks like when you rungccit's using MinGW's gcc. Check yourPATHenvironment variable (echo $PATH) to see if the MinGW location is in it before the Linux version. Or just runwhich gccto see which one is being used. Or maybe you don't have any other gcc installed and it that's why its using MinGW gcc by default.
I need to change the config bits in a EZBL bootloader project. I'm able to compile it, with version 2.11 and MPLAB X ide 5.4 The problem is that config bits are fully wrong, and if i modify them in mplab ide they are gone to the old value after recompile. That means that config bits are set programally or set in project. So, how do you change config bits in the project?
You can do it in your source code like this: ``` /*Config1*/ #pragma config FEXTOSC = OFF #pragma config RSTOSC = HFINT32 #pragma config CLKOUTEN = OFF ... ``` Have a look in the filepic_chipinfo.htmlwhich configuration bits are handeld in your controller
I've use cURL command-line tool with --libcurl and a url of mine(the url works in normal C), however I get the error "curl.h" does not exist, although it is in the same directory. I can't figure out how to include headers in emscripten. All of the supposed documentation on this usually ends up being about something else entirely.
I figured it out, I was being dumb
While getting familiarized with the operating systems course I'm taking, I came accross this code and I'm having trouble understanding the second part of the print (%s - &i). ``` unsigned int i = 0x00646c72; printf("H%x Wo%s", 57616, &i); ``` This yields the output of: ``` He110 World ``` First part is just hex representation of a number, how did the address ofiend up as'rld'though?
The address didn't end up being 'rld'. It works because %s expects a pointer to char (pointing to a null-terminated string of char). And because &i points to i, which is the bytes 0x72, 0x6C, 0x64, 0x00. Which is the null-terminated string of ascii character codes 'r', 'l', 'd'.
``` for (j = 0; j < 900; j++) { fptext = fopen("..\\n_file_list[j]", "w"); fseek(fptext, 0, SEEK_END); size = ftell(fptext); buffer_text = malloc(size + 1); memset(buffer_text, 0, size + 1); fseek(fptext, 0, SEEK_SET); fread(buffer_text, size, 1, fptext); } ``` n_file_list has 900 txt file name. I want to open these files but I can't. I know how to open the file in the folder. But I don't know how when the file name is in the array. How can I open it??
I think you made a mistake here : ``` fptext = fopen("..\\n_file_list[j]", "w"); ``` This line should be : ``` fptext = fopen(n_file_list[j], "w"); ```
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 So I have two unsigned 32bit ints, I need to find the difference between them in bytes. Essentially the task could be solved by shifting the bits and determining how many bits are set it and compare the two values. How exactly do I go about doing that?
Below is a function for calculating how many bytes an unsigned integer needs. Just use it on the two numbers and calculate the difference. Edit: Thanks to Eric Postpischil for his patience with my sloppiness. ``` #include <limits.h> int ByteCount(unsigned int n) { int result = 0; while (n != 0) { result++; n >>= CHAR_BIT; } return result; } ```
So I wanto to compile a program that has included these headers: ``` #include <stdio.h> #include "teclas_tictac.h" ``` The headerteclas_tictac.hhas prototypes for functions inteclas_tictac.cfile. How do I do that? I usually dogcc myprogram.c -o myprogram. Thanks
Not to get too technical, but the function implementations is what needs to be assembled, converted to object code and finally linked, the header file is not used directly in the compilation process, its contents are simply copied to where you use the#includedirective. So what you need for the compilation process is the.cfile not the header file. ``` gcc myprogram.c teclas_tictac.c -o myprogram ``` You can also includewarning flagsin the process which can help detect problems you may otherwise miss. Here are some of the more commonly used: ``` gcc myprogram.c teclas_tictac.c -o myprogram -Wall -Wextra -pedantic ```
I have a string representing a number, with some digits "hidden" behind the symbol '!'. I would like to generate and print all possible numbers obtained by replacing the '!' by '1' or '2'. For instance: ``` INPUT: 12!21! OUTPUT: 121211 121212 122211 122212 ``` I would like to solve this problem with a recursive function in C.
Let me write this in pseudo-code: ``` void combination(input_array){ boolean bExclamation_found = (index("!",input_array)>-1); if bExclamation_found then printout(input_array) else { combination(replace_one_exclamation(input_array, "1")); combination(replace_one_exclamation(input_array, "2")); } ``` Good luck
I am trying to understand why the output of this code would be 7 11 and I am lost. What isptr[1][2]andptr[2][1]referring to? ``` #include <stdio.h> #define SIZE 25 int main() { int a[SIZE]; int *ptr[5]; for (int i = 0; i < SIZE; i++){ a[i] = i; } //has values 0-24 ptr[0]=a; //ptr[0] is assigned with address of array a. for (int i=1; i < 5; i++){ ptr[i] = ptr[i-1]+5; //pp[1] = 5; pp[2] = 6?? } printf("\n%d %d",ptr[1][2],ptr[2][1] ); //output is 7 11 return 0; } ```
ptr[1] = ptr[0]+5which refer toa[0+5]=a[5] ptr[2] = ptr[1]+5which refer toa[5+5]=a[10] so prt[1][2]should bea[5+2]which isa[7]= 7 prt[2][1]should bea[10+1]which isa[11]= 11
While getting familiarized with the operating systems course I'm taking, I came accross this code and I'm having trouble understanding the second part of the print (%s - &i). ``` unsigned int i = 0x00646c72; printf("H%x Wo%s", 57616, &i); ``` This yields the output of: ``` He110 World ``` First part is just hex representation of a number, how did the address ofiend up as'rld'though?
The address didn't end up being 'rld'. It works because %s expects a pointer to char (pointing to a null-terminated string of char). And because &i points to i, which is the bytes 0x72, 0x6C, 0x64, 0x00. Which is the null-terminated string of ascii character codes 'r', 'l', 'd'.
``` for (j = 0; j < 900; j++) { fptext = fopen("..\\n_file_list[j]", "w"); fseek(fptext, 0, SEEK_END); size = ftell(fptext); buffer_text = malloc(size + 1); memset(buffer_text, 0, size + 1); fseek(fptext, 0, SEEK_SET); fread(buffer_text, size, 1, fptext); } ``` n_file_list has 900 txt file name. I want to open these files but I can't. I know how to open the file in the folder. But I don't know how when the file name is in the array. How can I open it??
I think you made a mistake here : ``` fptext = fopen("..\\n_file_list[j]", "w"); ``` This line should be : ``` fptext = fopen(n_file_list[j], "w"); ```
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 So I have two unsigned 32bit ints, I need to find the difference between them in bytes. Essentially the task could be solved by shifting the bits and determining how many bits are set it and compare the two values. How exactly do I go about doing that?
Below is a function for calculating how many bytes an unsigned integer needs. Just use it on the two numbers and calculate the difference. Edit: Thanks to Eric Postpischil for his patience with my sloppiness. ``` #include <limits.h> int ByteCount(unsigned int n) { int result = 0; while (n != 0) { result++; n >>= CHAR_BIT; } return result; } ```
So I wanto to compile a program that has included these headers: ``` #include <stdio.h> #include "teclas_tictac.h" ``` The headerteclas_tictac.hhas prototypes for functions inteclas_tictac.cfile. How do I do that? I usually dogcc myprogram.c -o myprogram. Thanks
Not to get too technical, but the function implementations is what needs to be assembled, converted to object code and finally linked, the header file is not used directly in the compilation process, its contents are simply copied to where you use the#includedirective. So what you need for the compilation process is the.cfile not the header file. ``` gcc myprogram.c teclas_tictac.c -o myprogram ``` You can also includewarning flagsin the process which can help detect problems you may otherwise miss. Here are some of the more commonly used: ``` gcc myprogram.c teclas_tictac.c -o myprogram -Wall -Wextra -pedantic ```
I have a string representing a number, with some digits "hidden" behind the symbol '!'. I would like to generate and print all possible numbers obtained by replacing the '!' by '1' or '2'. For instance: ``` INPUT: 12!21! OUTPUT: 121211 121212 122211 122212 ``` I would like to solve this problem with a recursive function in C.
Let me write this in pseudo-code: ``` void combination(input_array){ boolean bExclamation_found = (index("!",input_array)>-1); if bExclamation_found then printout(input_array) else { combination(replace_one_exclamation(input_array, "1")); combination(replace_one_exclamation(input_array, "2")); } ``` Good luck