question
stringlengths
25
894
answer
stringlengths
4
863
I can't understand why 'layout next' has stopped showing code. It worked for some time and i was happy with 'layout next' option but now i constantly see the error. Awkwardly enough i could find only onequestionrelating that topic which doesn't seem to solve the problem. Any ideas how to bring this function back? Maybe i should find some compilation flag to enable this? ``` EDIT: ``` Make sure you add -g flag on compilation and type run after 'layout next' window have appeared.
No Source Available The error means literally that: GDB doesn't know where the source for the current program location is. There are several possible reasons: you have not started the program yetyou built your program without debugging info (without-gflag)you are stopped inside a system libraryyou moved the source to a different location after the program was built
Hereyou'll find the following statement: #importis not a well designed feature. It requires the users of a header file to know that it should only be included once. What is the problem with this?
The article states the problem pretty exactly: If you write a header with the intention that it's been used with #import (aka without any include guards/etc), then youexpectthe user of that header file to use #import or other means to make sure that the file is only included once. If the user doesn't know that, or if the header is used with a compiler that doesn't support #import (or does something else with that command), then your header will not work properly. And, especially in big projects with many people working on it, there's a good chance that someday someone might accidantally #include that header instead, or that the project gets ported to a different compiler some time in the future.
In C we cannot assignint variable = true;, where as the below code executes. ``` typedef struct mystruct { int variable; } mystruct_; int main(void){ // Your code here! mystruct_ st = {true}; printf("%i",st.variable); } ``` Why true isn't valid value forint variable = true, but is valid for anintmember in a struct? Can someone please explain why?
In C we cannot assignint variable = true; This is not correct. It compiles and run successfully. The following code compiles and runs perfectly on GCC. ``` #include <stdio.h> #include <stdbool.h> typedef struct mystruct { int variable; } mystruct_; int main(void){ int variable = true; mystruct_ st = {true}; printf("%i %i",st.variable, variable); } ``` By the way, thestdbool.hcontains the following: ``` #define true 1 #define false 0 ``` That's why it should work withint.
What's the difference between the implementation ofstrstr()andstd::string::find()? Eg: ``` char* str = "abc\0hijk@#$%"; char* temp; std::string str1; for (int i=0; i <=12; i++) { str1.push_back(str[i]); } strstr(temp, "@#");// can not handle'\0' str1.find("@#");// success ```
Thestd::stringclass is a C++ class that represents a string which can contain a null character. Its member functions, likefind, are designed to handle those embedded nulls. strstr(a function from C) works withchar*pointers, which point to C-style strings. Because C-style strings are null-terminated, they cannot handle embedded nulls. To this effect,strstris documented as follows: Locate substringReturns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.The matching process does not include the terminating null-characters, but it stops there. The italicized part is relevant here.
I was wondering whether clang's new amazing custom size (things like 13-bit int, or 70-bit int, etc.) will get added to gcc.
Well. C23 has finally implemented them as_BigInt
I can't understand why 'layout next' has stopped showing code. It worked for some time and i was happy with 'layout next' option but now i constantly see the error. Awkwardly enough i could find only onequestionrelating that topic which doesn't seem to solve the problem. Any ideas how to bring this function back? Maybe i should find some compilation flag to enable this? ``` EDIT: ``` Make sure you add -g flag on compilation and type run after 'layout next' window have appeared.
No Source Available The error means literally that: GDB doesn't know where the source for the current program location is. There are several possible reasons: you have not started the program yetyou built your program without debugging info (without-gflag)you are stopped inside a system libraryyou moved the source to a different location after the program was built
I can't understand why 'layout next' has stopped showing code. It worked for some time and i was happy with 'layout next' option but now i constantly see the error. Awkwardly enough i could find only onequestionrelating that topic which doesn't seem to solve the problem. Any ideas how to bring this function back? Maybe i should find some compilation flag to enable this? ``` EDIT: ``` Make sure you add -g flag on compilation and type run after 'layout next' window have appeared.
No Source Available The error means literally that: GDB doesn't know where the source for the current program location is. There are several possible reasons: you have not started the program yetyou built your program without debugging info (without-gflag)you are stopped inside a system libraryyou moved the source to a different location after the program was built
``` int main() { int nodes = 7; int var_1 = (int)(log((double)(nodes + 1))/log(2) - 1); int var_2 = (int)(log((double)(7 + 1))/log(2) - 1); printf("%d\n", var_1); printf("%d\n", var_2); return 0; } ``` The above code initializes the varialbesvar_1andvar_2to values 1 and 2, accordingly. Why they have different values since the variablenodeshas the value of 7, same as the constant in the next equation. Edit: I dont try to "fix" the code, or else I could just assignnodes+1to a variable.
The first statement is probably calculated at runtime by the code pre-compiled in the standard library (with libm), the second statement is probably calculated at compile time by the compiler (with MPFR). Probablylog(8)bylibmis a tiny little bit less than byMPFR. ``` 2.079441541...7 / 0.69314... = 2.999999... 2.079441541...8 / 0.69314... = 3.000000... ```
Every time I run the program, the last "if" statement is not working, it means if I type "no", the loop won't break. Can someone please help me here? ``` #include <stdio.h> int main() { int age, i; char ans; for (i = 0; i < 3; i++) { printf("\n enter your age:"); scanf("%d", &age); if (age > 18) { printf("your age is %d, you are allowed to enter", age); } else if (age == 18) { printf("I don't know what to do with you"); } else { printf("your age is %d, you are not allowed to go in", age); } printf("\n continue?"); scanf(" %c", &ans); if (ans == 'no') { // <-- here break; } else { continue; } } return 0; } ```
useif (ans == 'n'). If you want to use the word"no", you have to change the type of variableansto char array and usestrcmp()method to compare strings.
This question already has answers here:Why cast an unused function parameter value to void?(2 answers)Closed3 years ago. I saw the piece of the code. But do not know what the purpose is. ``` void a() { static const char *string = "STRING"; ... (void)string; // <---- What the purpose of the line is? ... } ```
(void)before a variable like that creates an empty expression and is used to silence warnings about a variable not being used by the program. In this specific case it would be better to simply comment out the variable declaration.
I know that %f means float, althought, I don't know if the brackets make any difference. I have this: ``` void print_LIST(LIST L){ CORD *c; while(L != NULL){ c = L->value; printf("%d%d",c->col,c->lin); printf("(%f) ",distance(c)); L = L->next; } printf("\n"); } ```
Not everything in a format specifier is a conversion specifier (carry special meaning). For example: assumingiholds a value of10, following statement: ``` printf ("The value of i is %d", i); ``` will printThe value of i is 10, so the rest of the string is printed as-is. Following this, in your case ``` printf ("(%f)", distance(c)); ``` will print thedoublevalue returned by thedistance(c)function call. Assuming a value 1.23, it will print(1.23)(with the parenthesis).
I'm reading a book about C and I don't understand this concept: Another common misconception is thinking of a const qualified variable as a constant expression. In C, const means "read-only", not "compile time constant". So, global definitions like const int SIZE = 10; int global_arr[SIZE]; and const int SIZE = 10; int global_var = SIZE; are not legal in C. I also don't understand very good the diference between const variable and constant expression. All const variables are constant expressions, right? I have readed other questions about this topic but I still without understantig. Thanks.
suppose you have ``` int a = 42; const int *b = &a; ``` now*bisconstieread-only. You are not allowed to change*bwithout casting theconstaway (thanks Eric Postpischil) ``` // *b = -1; // not allowed a = -1; printf("%d\n", *b); // print -1 ``` The point is: the value of aconstqualified objectmaychange. A constant valueneverchanges.
auto, register, static and extern are called storage classes in C. But why are they called classes when there are no classes in C?
The word "classes" (plural of "class") isa common English termand in this case is being used as such. classPronunciation /klas/ /klæs/NOUNA set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality."the accommodations were good for a hotel of this class""a new class of heart drug"
Suppose we are given a task to write a function that sums 2 numbers. I wrote the following code: ``` int main(int ac, char **av) { int x = atoi(av[1]); int y = atoi(av[2]); if (x > 0 & y > 0) { sum(x, y) } else { return 0; } return 0; } ``` But when I am given an input: ``` ./a.out 2 ``` I catch SIGSEVG. Please explain how do I deal with that problem.
The way you're calling your program,argv[2]isNULL. Theatoifunction, therefore, is dereferencing an invalid pointer, hence the segfault. You should always check the value ofargcbefore using any of the command-line arguments.
I'm reading a book about C and I don't understand this concept: Another common misconception is thinking of a const qualified variable as a constant expression. In C, const means "read-only", not "compile time constant". So, global definitions like const int SIZE = 10; int global_arr[SIZE]; and const int SIZE = 10; int global_var = SIZE; are not legal in C. I also don't understand very good the diference between const variable and constant expression. All const variables are constant expressions, right? I have readed other questions about this topic but I still without understantig. Thanks.
suppose you have ``` int a = 42; const int *b = &a; ``` now*bisconstieread-only. You are not allowed to change*bwithout casting theconstaway (thanks Eric Postpischil) ``` // *b = -1; // not allowed a = -1; printf("%d\n", *b); // print -1 ``` The point is: the value of aconstqualified objectmaychange. A constant valueneverchanges.
auto, register, static and extern are called storage classes in C. But why are they called classes when there are no classes in C?
The word "classes" (plural of "class") isa common English termand in this case is being used as such. classPronunciation /klas/ /klæs/NOUNA set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality."the accommodations were good for a hotel of this class""a new class of heart drug"
Suppose we are given a task to write a function that sums 2 numbers. I wrote the following code: ``` int main(int ac, char **av) { int x = atoi(av[1]); int y = atoi(av[2]); if (x > 0 & y > 0) { sum(x, y) } else { return 0; } return 0; } ``` But when I am given an input: ``` ./a.out 2 ``` I catch SIGSEVG. Please explain how do I deal with that problem.
The way you're calling your program,argv[2]isNULL. Theatoifunction, therefore, is dereferencing an invalid pointer, hence the segfault. You should always check the value ofargcbefore using any of the command-line arguments.
I'm reading a book about C and I don't understand this concept: Another common misconception is thinking of a const qualified variable as a constant expression. In C, const means "read-only", not "compile time constant". So, global definitions like const int SIZE = 10; int global_arr[SIZE]; and const int SIZE = 10; int global_var = SIZE; are not legal in C. I also don't understand very good the diference between const variable and constant expression. All const variables are constant expressions, right? I have readed other questions about this topic but I still without understantig. Thanks.
suppose you have ``` int a = 42; const int *b = &a; ``` now*bisconstieread-only. You are not allowed to change*bwithout casting theconstaway (thanks Eric Postpischil) ``` // *b = -1; // not allowed a = -1; printf("%d\n", *b); // print -1 ``` The point is: the value of aconstqualified objectmaychange. A constant valueneverchanges.
auto, register, static and extern are called storage classes in C. But why are they called classes when there are no classes in C?
The word "classes" (plural of "class") isa common English termand in this case is being used as such. classPronunciation /klas/ /klæs/NOUNA set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality."the accommodations were good for a hotel of this class""a new class of heart drug"
Suppose we are given a task to write a function that sums 2 numbers. I wrote the following code: ``` int main(int ac, char **av) { int x = atoi(av[1]); int y = atoi(av[2]); if (x > 0 & y > 0) { sum(x, y) } else { return 0; } return 0; } ``` But when I am given an input: ``` ./a.out 2 ``` I catch SIGSEVG. Please explain how do I deal with that problem.
The way you're calling your program,argv[2]isNULL. Theatoifunction, therefore, is dereferencing an invalid pointer, hence the segfault. You should always check the value ofargcbefore using any of the command-line arguments.
Suppose we are given a task to write a function that add 2 numbers. ``` #include <stdio.h> int main(int argc, char ** av) { int a = atoi(av[1]); int b = atoi(av[2]); add_and_print(a, b) return 0; } ``` It works fine untill I pass following code: ``` ./a.out ``` Just passing empty strings. Then it writes the following: ``` 1495 segmentation fault (core dumped) ``` Could you please explain what is the problem and how do I deal with it ?
argccontains the number of arguments provided to the program, and if you don't check it then you might get a segfault trying to read fromargv. You can display an error message and exit if there aren't enough arguments: ``` if (argc < 3) { puts("Please provide 2 numbers as command line arguments."); return 1; } ```
I am using the Win32 API. I have this code that creates an edit control: ``` CreateWindowW(L"Edit", L"", WS_VISIBLE | WS_CHILD, 100, 100, 200, 20, hand, NULL, NULL, NULL); ``` How do I put placeholder text inside of this edit box?
You can useSendMessagewithEM_SETCUEBANNER: ``` HWND editCtlHandle = CreateWindowW(L"Edit", L"", WS_VISIBLE | WS_CHILD | WS_BORDER, 100, 100, 200, 20, hWnd, NULL, hInstance, NULL); WCHAR placeholderText[] = L"Enter here"; SendMessage(editCtlHandle, EM_SETCUEBANNER, FALSE, (LPARAM)placeholderText); ``` Or useEdit_SetCueBannerTextmacro: ``` Edit_SetCueBannerText(editCtlHandle, placeholderText); ``` The result will like this:
I am getting the following error when I try to compile and run my code. " error: expected ‘{’ before ‘*’ token struct ". ``` The code it is referring to: #ifndef node #define node struct node { int datum; struct node * next; } ; #endif ``` The above code is for a user-defined header file called "node.h". It will be used to create a linked list.
``` #define node ``` That will replace with an empty token wherever there is anodeafter that point. So after preprocessing the code becomes: ``` struct { int datum; struct * next; } ; ``` So need to pick a name for thedefinethat is not used as an identifier in the file. Commonly the define reflects the file name: ``` #ifndef NODE_H #define NODE_H struct node { int datum; struct node * next; }; #endif ```
Can I pass a timeval struct as the argument for a sleep function? I want to do this since the timeval struct can get very precise, since you can control the microseconds and I would like to sleep for a certain amount of microseconds. Can I do this?
You could do something like: ``` struct timeval {long tv_sec; long tv_usec;}; struct timezone {int tz_minuteswest; int tz_dsttime; }; struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); ``` And using that you can implement a delay function. Please seethis example. However if you want a precise delay you could use functions that enable you to get more precise delay such asnanosleep() ``` struct timespec tim, tim2; tim.tv_sec = 1; tim.tv_nsec = 1000000000L; //1,000,000,000 nanoseconds = 1 second nanosleep(&tim , &tim2); /*code after 1 second sleep*/ ```
I want to copy two parts of string s to two strings a and b: ``` #include <stdio.h> #include <string.h> int main() { char s[] = "0123456789ABCDEF"; char a[10]; char b[6]; strncpy( a, s, 10 ); a[10] = '\0'; printf("%s\n", a); strncpy( b, s+10, 6 ); b[6] = '\0'; printf("%s %s\n", a, b); return 0; } ``` Result: ``` 0123456789 ABCDEF ``` I had expected ``` 0123456789 0123456789 ABCDEF ``` What has happened to a? Can anybody tell me what is wrong?
The arrays a and b do not contain strings. Declare them like ``` char a[11]; char b[7]; ``` that is reserve one more element for the terminating zero character. Otherwise these statements ``` a[10] = '\0'; b[6] = '\0'; ``` use invalid indices.
This question already has answers here:What are the rules of automatic stdout buffer flushing in C?(5 answers)Closed3 years ago. Does theprintf()function in C need a\nat the end in order to work ? I tried printing out a simple statement without a newline at the end and it didn't work. Thanks.
The likely reason isa line bufferedstdout, (this is implementation defined so I can't be 100% sure). In these implementations the content written to the buffer won't immediately be transferred to the output. Using"\n", causes a flush of the buffer to the output and theprintfwill print the contents, the downside is that the"\n"will also be printed. As an alternative, you can usefflush(stdout)if you don't want a that newline character to be printed. For output streams (and for update streams on which the last operation was output), writes any unwritten data from the stream's buffer to the associated output device.
I'm playing with Python's C-API. Specifically, I want to see if I can inspect how many elements the value stack currently has. Here's my code: ``` #include <Python.h> #include <frameobject.h> int test() { PyFrameObject* f = PyEval_GetFrame(); return (int)(f->f_stacktop - f->f_valuestack); } ``` I'm not sure whether this can work, but this line exists inPython's source code, so I gave it a try. This usually results in negative number, something like-547715639. So clearly I'm doing it wrong, probably because what'e described in the documentation:"Frame evaluation usually NULLs it (f_stacktop)". What's the right way to do it, or is it even possible?
It's impossible. Seethis answer. In short, I should use ``` (int)(stack_pointer - f->f_valuestack); ``` However,stack_pointeris a local varaible inside the_PyEval_EvalFrameDefaultfunction, thus can't be accessed from outside.
Linux has theO_PATHflag to open() which allows one to get a fd to be used in fstat, fcntl and others without actually opening the file for reading (or having permissions to do so). However theO_PATHflag is Linux specific. Is there an equivalent to theO_PATHflag to open() in MacOS? For example, how can I use fstat() on a file I don't have read permissions for?
macOS doesn't have an equivalent toO_PATH, so it's impossible to have a reference to a file without opening it. Regarding the one bit of functionality that you mentioned, you can callstatwith a given file path as long as you have "execution" rights to its parent directory, regardless of whether you have any rights to that file.
Can anyone tell me the mistake in this code ``` #include <stdio.h> int main(void) { int a=5, i=0, j; while(a<1 && a>8) { printf("Height:"); scanf("%d",&a); } for(i=0; i<a; i++) { for(j=a; j>i+1; j--) { printf(" "); } for(j=i+1; j>0; j--) { printf("#"); } printf("\n"); } } ``` here is there a mistake in the while loop? i thought it would prompt the user for height again if the condition is true
That is basic mathematics: a number cannot be smaller than 1 and bigger than 8 at the same time. You used&&(logical AND) instead of||(logical OR).
Is there any difference between ``` const int* ptr[5]; ``` and ``` const int (*ptr)[5]; ``` ? I am trying to point to a const 5*5 2D int array, but I am not sure of the best way to do it
``` const int* ptr[5]; ``` This is an array of five elements, each element is a pointer toconst int. ``` const int (*ptr)[5]; ``` This is a pointer to an array of five elements, each element is aconst int.
I wrote a simple code to reverse a string and its somehow not returning any result. Could someone please help me understand the problem. ``` #include <stdio.h> #include <string.h> void reverse_character(char *s){ int i; int p = strlen(s); for(i=(p-1);i<0;i--){printf("%c",s[i]);} } int main(){ char name[20]; printf("Enter a name"); scanf("%s",name); reverse_character(name); } ```
i=(p-1);i<0;i-- Change it to i=(p-1);i>=0;i--
``` float m; int lftovr,x; scanf("%.2f", &m); lftovr = m%100; x=m/100; ``` why does it show error: ``` ||=== Build file: "no target" in "no project" (compiler: unknown) ===| E:\c programme\naeem\change.c||In function 'main':| E:\c programme\naeem\change.c|6|error: invalid operands to binary % (have 'float' and 'int')| ```
Because the modulus division '%' apply just to integers, not to float. This is because there is no remainder if it is not an integer division.
I am working on a project,in which I need to extract data from the device: InertialUnit. I get a single value in real time, but I need data for the first 10 s and in 1 ms increments, or all the data for the entire cycle of the device. Please help me implement this if possible.
Webots controllers are like any other programs, so you can easily get the values of the inertial unit and save them in a file at each step. Here is a very simple example in Python: ``` from controller import Robot robot = Robot() inertial_unit = robot.getInertialUnit('inertial unit') inertial_unit.enable(10) while robot.step(10) != -1: values = inertial_unit.getValues() with open('values.txt','a') as f: f.write('\n'.join(values)) ```
I was studying some macro operations, and I got this Code and I was unable to figure out how this code is actually working and generates the output? and is there any (i-+) operator that exists or not? Here is the code ``` #include<stdio.h> #define p(a,b) a##b #define call(x) #x int main() { do{ int i=14,j=3; printf("%d",p(i-+,+j)); }while(*(call(625)+3)); return 0; } ``` Output is 10. It will be very helpful if you explain it with some examples.
The##in the macro is the concatenation operator, it glues its operands together. So after the preprocessor is done, that expression will be ``` i-++j ``` which of course just meansi - (++j), i.e.14 - 4which of course is10.
``` float m; int lftovr,x; scanf("%.2f", &m); lftovr = m%100; x=m/100; ``` why does it show error: ``` ||=== Build file: "no target" in "no project" (compiler: unknown) ===| E:\c programme\naeem\change.c||In function 'main':| E:\c programme\naeem\change.c|6|error: invalid operands to binary % (have 'float' and 'int')| ```
Because the modulus division '%' apply just to integers, not to float. This is because there is no remainder if it is not an integer division.
I am working on a project,in which I need to extract data from the device: InertialUnit. I get a single value in real time, but I need data for the first 10 s and in 1 ms increments, or all the data for the entire cycle of the device. Please help me implement this if possible.
Webots controllers are like any other programs, so you can easily get the values of the inertial unit and save them in a file at each step. Here is a very simple example in Python: ``` from controller import Robot robot = Robot() inertial_unit = robot.getInertialUnit('inertial unit') inertial_unit.enable(10) while robot.step(10) != -1: values = inertial_unit.getValues() with open('values.txt','a') as f: f.write('\n'.join(values)) ```
I was studying some macro operations, and I got this Code and I was unable to figure out how this code is actually working and generates the output? and is there any (i-+) operator that exists or not? Here is the code ``` #include<stdio.h> #define p(a,b) a##b #define call(x) #x int main() { do{ int i=14,j=3; printf("%d",p(i-+,+j)); }while(*(call(625)+3)); return 0; } ``` Output is 10. It will be very helpful if you explain it with some examples.
The##in the macro is the concatenation operator, it glues its operands together. So after the preprocessor is done, that expression will be ``` i-++j ``` which of course just meansi - (++j), i.e.14 - 4which of course is10.
so I am new to low-level language. And I was going through some learning materials for C, and I could not really distinguish the difference between the following expressions. ``` struct Node *temp; struct Node *head; //expression 1 temp->next = head; //expression 2 temp = head; ``` Don't the two expressions mean the same thing which is directing the pointer of the temp node towards WHERE the pointer of the head node points to?
tempis a pointer. Presumably, before your “expression 1,” it has been set to point to some nodex. Thentemp->next = head;sets thenextmember ofxtohead. It changesx(thenextmember inx). It does not changetemp. In contrast,temp = head;setstemptohead. It changestemp.
so I am new to low-level language. And I was going through some learning materials for C, and I could not really distinguish the difference between the following expressions. ``` struct Node *temp; struct Node *head; //expression 1 temp->next = head; //expression 2 temp = head; ``` Don't the two expressions mean the same thing which is directing the pointer of the temp node towards WHERE the pointer of the head node points to?
tempis a pointer. Presumably, before your “expression 1,” it has been set to point to some nodex. Thentemp->next = head;sets thenextmember ofxtohead. It changesx(thenextmember inx). It does not changetemp. In contrast,temp = head;setstemptohead. It changestemp.
``` struct sigaction act; memset(&act,0,sizeof act); sigaction(SIGALRM, &act, NULL); alarm(any_seconds); ``` My alarm code in linux. I met "Alarm clock" message. But I don't want met this message. How can I do? please help.
You can catch the signal ``` static void alarmHandler(int signo) { (void)signo; printf("Another message\n"); // or skip this line } ... alarm(any_seconds); signal(SIGALRM, alarmHandler); ```
I try to get strings as many as the input value in c.But a leading white space located first line is removed. I had already use the fgets and scanset. I want the input and output to be the same. ``` fgets(str[i], 100, stdin); ``` ``` scanf("%[^\n]%*c]", str); ``` Code ``` int n = 0; scanf("%d\n", &n); char str[10][100] = {0}; for (int i = 0; i < n; i++) { fgets(str[i], 100, stdin); } ``` Input ``` 3 ** * ** ``` Output ``` ** * ** ``` What should I do?
You have to use getchar() after reading n because the newline character '\n' will remain in the input buffer and your fgets in for loop will read that and also remove\nfrom scanf. Use following line of code: ``` int n = 0; scanf("%d\n", &n); getchar(); char str[10][100] = {0}; for (int i = 0; i < n; i++) { fgets(str[i], 100, stdin); } ```
How can i create N elements of this struct after the input N? ``` typedef struct cat{ int code; int age; float weight; enum {kibbles,canned_food,tuna_fish}food; } cats; int n,i; printf("Insert a number: "); scanf("%d",&n); for(i=0;i<n;i++){ .... } ``` I want to create N cats (named cat1,cat2 etc..)
Make a function to input a singlestruct cat ``` struct cat inputsinglecat(void); ``` After you know how many cats you need, get the amount of memory required ``` struct cat *memcat; memcat = malloc(n * sizeof *memcat); if (memcat == NULL) exit(EXIT_FAILURE); ``` Then, to enter cats, use a loop and the function defined above ``` for (int k = 0; k < n; k++) { memcat[k] = inputsinglecat(); } ``` Don't forget to release the memory when you don't need it anymore ``` free(memcat); ```
Can anyone explain to me how this return works when there are logic operators? Also explain when this function is going to return itself and the array elements? ``` #include<stdio.h> int consecutive_3(int x, int y, int z, int a[], int n) { if(n<3) return 0; return ((a[n-3] == x) && (a[n-2] == y) && (a[n-1] == z)) || consecutive_3(x, y, z, a, n-1); } ```
should be the same ``` int consecutive_3(int x, int y, int z, int a[], int n) { if (n < 3) return 0; if ((a[n-3] == x) && (a[n-2] == y) && (a[n-1] == z)) return 1; return consecutive_3(x, y, z, a, n - 1); } ``` notice: c evaluates logical expressions from left to right and&&has ahigher precedence(is evaluatet first) than||.
I want to add a leading zero in a C integer. I am making a clock. Here is the code I have so far: ``` int main(){ while (1){ time_t present; time(&present); struct tm *myTime = localtime(&present); printf("%2d:%2d:%2d\n", myTime->tm_hour,myTime->tm_min, myTime->tm_sec); sleep(1); } return 0; } ``` Here is the current output: ``` 11:30: 0 11:30: 1 11:30: 2 11:30: 3 11:30: 4 11:30: 5 11:30: 6 11:30: 7 11:30: 8 11:30: 9 11:30:10 ``` Here is the output I want: ``` 11:30:00 11:30:01 11:30:02 //and so on... ```
Fill a0betwen the%and the length modifier, here2, at each format specifier in theprintf()call: ``` printf("%02d:%02d:%02d\n", myTime->tm_hour,myTime->tm_min, myTime->tm_sec); | | | here here here ```
From the Wikipedia article it seemsones' complement representationfor signed integers is mostly obsolete, but they mention some Unisys systems, namely theUNIVAC 1100/2200 seriesasstill supportingthis representation. Do the latest systems in theUnisys Clearpath seriesstill support and use ones' complement? Since they use intel chips, do they require an emulator? How performant is this? Are there C compilers targeting this architecture?
Yes, the 2200 line still uses ones complement. Emulating one's complement on a two's complement machine is not hard, you just need to add the carry back in (end around carry). And the MCP line still uses signed magnitude.
I am programming a tree of processes in Linux and I wonder if there is any signal that can be used just to send from A process to B processwithout affectingB process. For example, assumeB_pidis the process B's ID, if process A callskill(B_pid, SIGSTOP);then A will pause B. What I am looking for is a signal, let's saySIGNOTHING, that when A callskill(B_pid, SIGNOTHING), then it just simply sends a message to B rather than doing something to both B and the system.
SIGUSR1andSIGUSR2are designed for that purpose.
This question already has answers here:Are the members of a global structure initialized to zero by default in C?(5 answers)Closed3 years ago. I didn't find anything online about what happens when objects are created in C: like their value are initialized or they take garbage value. ``` #include <stdio.h> struct temp { int a; } s; int main() { printf("%d", s.a); } ``` OUTPUTis :0. So is 0 a garbage value?? Or is it an undefined behavior?
Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be). You have used a global structure variable. Therefore initialised to default value, i.e., 0.
I have a code where i give an argv[1] that eventually will open a file: ``` int main(int argc, char** argv) { read(argv[1]); } ``` The thing is that the.hhas the following error, "error expected ‘FILE * {aka struct _IO_FILE *}’ but argument is of type ‘char *’" This is the .h: ``` #include <stdio.h> struct node{ int id; int *link_ids; int links; }; struct node *nodes; void read(FILE * openedfile); ``` The thing is that argv[1] is going to be the name of the FILE (txt). Void read is the one that will do everything with the file. Also i i cant modify in any way main.c Can someone help me with my error?
argv[1]is a char array, you are passing it to a function expecting aFILE*parameter. If you just want to pass the name of the file as an argument of the function it should be: ``` void read(char * openedfile); ```
I am learning C and was trying to help debug a friends code. He was defining his function parameters in the global scope and then passing them into the function def like so: ``` #include <stdio.h> double x; double myfunc(x){ return x; } void main(){ } ``` I get this is wrong, but not why the following error comes up: ``` main.c:14:8: warning: type of ‘x’ defaults to ‘int’ [-Wimplicit-int] ``` Can someone help me understand how the computer is interpreting this code?
He was defining his function parameters in the global scope No, he does not. The globalxis unrelated to the function's parameterx. The former is a globaldouble, the latter is local to the function and, as the compiler is warning, "defaults toint". I get this is wrong It is not wrong, but not possible.
I want to control a 4 bit multiplexer with my nucleo board. I understand I have to write either to the higher or lower parts of the BSRR resgister, to set bits high and set bits low. I want to increment some variable, saymultp_selectand then output it to GPIOA (in AVR I can do this just by writingPORTA = multp_selectfor example) what is the best way to do this?
Use the registerODRinstead. My advice is: read the Reference Manual - everything is described there.
I suffered complex C style code logic like as ``` if (A || (B && (X || Y))) foo(); ``` Is any better way to read the boolean table, or redesign to human readable?
better way This is mostly a matter of taste. A different way to look at OR's and AND's is to treat them as if/elseif/elseif or if/if/if constructs. So this ``` if (A || (B && (X || Y))) ``` would become ``` if A foo(); else if B { if X foo(); else if Y foo(); } ```
Is it possible to create login dialog in C like this: If it's possible, how can i do this?
You'll have to use a GUI library if you want to achieve this using C. My recommendation would beQt. There are some great starter tutorials on theirsite If you would prefer not using a library and start from scratch then you will have to look into using the Windows API. However, that by nature won't be platform agnostic. Hope this helps! Edit: Qt isn't made for C, you will need to use C++ for the UI components. If you need pure C, please look into using GTK instead.
This question already has answers here:#define IDENTIFIER without a token(4 answers)Closed3 years ago. Quick question about the following snippet: ``` #ifndef __LZO_MMODEL #define __LZO_MMODEL /*empty*/ #endif ``` In an empty define like this what does it represent? It's used in like manner: ``` #define lzo_bytep unsigned char __LZO_MMODEL * #define lzo_charp char __LZO_MMODEL * ```
Those answers do not cover many other possible cases. Another example. ``` #ifndef DEBUG #define SINLINE static inline __attribute__((always_inline)) #else #define SINLINE #endif ``` and then ``` SINLINE void myfunc() { /* ... */ } ``` and if theDEBUGis defined function will not be inlined making it more debugger friendly. There are many other use cases. ``` ```
This is the codehttps://ide.geeksforgeeks.org/8bYOzDDC9Uto run this ``` #include <stdio.h> char *c[] = {"GeksQuiz", "MCQ", "TEST", "QUIZ"}; char **cp[] = {c+3, c+2, c+1, c}; char ***cpp = cp; int main() { cpp++; printf("%s", cpp[0][0]); // TEST printf("%s ", cpp[-1][-1]); // TEST return 0; } ``` The output of both the printf() is TEST. Why is it so? When I do cpp++, the pointer moves to c+2. SO I understand that cpp[0][0] will be at the starting of "TEST" and that's why it is printing TEST. Can someone explain me for cpp[-1[-1]?
char ***cpp = cp;initializescppto point to the first element ofcp, that is,cp[0]. Aftercpp++,cpppoints tocp[1]. Thencpp[-1]refers tocp[0]. cp[0]containsc+3, which is a pointer toc[3]. Socp[0][-1]refers toc[2]. c[2]contains"Test", in the sense that it is a pointer to the first element of"Test", so printing it prints"Test".
``` #include <stdio.h> #include <stdlib.h> int main() { int i; for (i = 0;;) { printf("%d\n", ((i++) * i) ^ i); } } ``` Compiling , it runs till the Limit and goes to negative integer.Why this behaviour?Did it for fun while reading the For statement syntax...
Consideringinttype to be of 32 bits. Since 'i' starts from zero, it will be something like this: 00000 ..... 32 times After i++: 00000000000000000000000000000001 This will keep on incrementing until it becomes: 0111 .. (31 1's) After the next increment you go into the negative number: 10000 ...(31 0's) In 2's complement above is -((2^32)). Further after many post increments it becomes: 11111111111111111111111111111111 (32 times 1) Above is -1. When the next increment occurs it becomes: 0000 ... (all 32 zeroes) and this process continues.
gcc has no problem with this, but I struggle to achieve the same thing with link.exe (visualc) in dll.c, I define ``` int myint = 0 ; int myfunc ( .... ) { ... } ; ``` in dll.h ``` extern int myint ; int myfunc ( .... ) ; ``` in dll.def ``` LIBRARY mydll EXPORTS myint myfunc ``` Everything works fine, the dll is created, I can link with it, my executable calls myfunc() successfully. But I don't know how to tell the linker that myint is a variable and not a function. So when I try ``` myint = 1 ; ``` the application crashes.
If I remember well, with c++ you need to explicitly import global variable (it's implicit with function). I'd try with__declspec( dllimport ) int myint; If you want to compile for windows and you are already developing under linux with GCC, I'd cross-compile from linux with mingw, it's a lot easier in my opinion.
``` #include <stdio.h> int main() { int n, i; char arr[20]; clrscr(); printf("Enter size of array(<=20)"); scanf("%d", &n); printf("Enter array"); for (i = 0; i < n; i++) { scanf("%s", &arr[i]); } for (i = 0; i < n; i++) { printf("%s", arr[i]); } getch(); return 0; } ``` The program does not prints the array and instead showsProgram terminationmessage The image shows the program termiantion message
The problem is with the line printf("%s", arr[i]);. If you change this line to printf("%c", arr[i]); then it will work because%sis used with character arrays that contain strings I am just giving the solution for your program termination. Still we can do some modification in your code. Thanks
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.Closed3 years ago.Improve this question I want to write ac codeforsquare wave converterfor some calculation purposes.But I don't have any idea about c code logic for a square wave . Please suggest me any logic which can help me to write a c code for the square wave converter.
A square wave is the easiest, after all its either high or low, on or off, true of false. If you're wanting to output a square wave then just toggle an output on your FPGA (if that is what this is) in relation to a timer. If you're converting an analogue signal to a square wave then you'll need to test against a value,that you set, below which your output is low and above which your output high. This is the basis of digitizing an analogue signal.
I need to create a character double pointer that will have 401 character arrays. Willchar *xx[401]work, or will I have to use malloc and friends? If so, how should I do it?
With ``` char *xx[401]; ``` you are declaring an array of 401pointers tochar. All of them will need to be initialized to some other existing char array, for example in this way ``` char foo[20] = "Hello"; xx[107] = foo; ``` ormalloc'ed, if they are intended to be a dynamically allocated array of strings. If all thesemallocs bother you, you can always define it statically ``` char xx[401][20+1] = { 0 }; /* Population of element at index 137 with a string defined somewhere else in the code: */ char str[] = "Hi guys"; strncpy(xx[123], str, 20); ``` (in this example every string will be of the fixed length of 20+1). But it will have to be a global variable: placing it in the stack wouldn't be the best solution.
This question already has answers here:Pre increment vs Post increment in array(3 answers)Closed3 years ago. ``` #include<stdio.h> int main(){ int array[10] = {3,0,8,1,12,8,9,2,13,10}; int x,y,z; x =++array[2]; y =array[2]++; z =array[x++]; printf("%d\t%d\t%d\n",x,y,z); return(0); } ``` I guessed the output of this would be 9,9,1 orsomething(Actually Not sure)But this broke out when compilied 10,9,10 PS:Forgive me, I am anoob
Here are the values step by step: ``` int array[10] = {3,0,8,1,12,8,9,2,13,10}; int x,y,z; x = ++array[2]; // array[2] becomes 9 before assignment to x // x:9 array[2]:9 y = array[2]++; // array[2] becomes 10 after assignment to y // x:9 y:9 array[2]:10 z = array[x++]; // z becomes array[x] (last element) // x:10 y:9 z:10 ```
``` #include <stdio.h> #include <stdlib.h> int main() { int i; for (i = 0;;) { printf("%d\n", ((i++) * i) ^ i); } } ``` Compiling , it runs till the Limit and goes to negative integer.Why this behaviour?Did it for fun while reading the For statement syntax...
Consideringinttype to be of 32 bits. Since 'i' starts from zero, it will be something like this: 00000 ..... 32 times After i++: 00000000000000000000000000000001 This will keep on incrementing until it becomes: 0111 .. (31 1's) After the next increment you go into the negative number: 10000 ...(31 0's) In 2's complement above is -((2^32)). Further after many post increments it becomes: 11111111111111111111111111111111 (32 times 1) Above is -1. When the next increment occurs it becomes: 0000 ... (all 32 zeroes) and this process continues.
gcc has no problem with this, but I struggle to achieve the same thing with link.exe (visualc) in dll.c, I define ``` int myint = 0 ; int myfunc ( .... ) { ... } ; ``` in dll.h ``` extern int myint ; int myfunc ( .... ) ; ``` in dll.def ``` LIBRARY mydll EXPORTS myint myfunc ``` Everything works fine, the dll is created, I can link with it, my executable calls myfunc() successfully. But I don't know how to tell the linker that myint is a variable and not a function. So when I try ``` myint = 1 ; ``` the application crashes.
If I remember well, with c++ you need to explicitly import global variable (it's implicit with function). I'd try with__declspec( dllimport ) int myint; If you want to compile for windows and you are already developing under linux with GCC, I'd cross-compile from linux with mingw, it's a lot easier in my opinion.
``` #include <stdio.h> int main() { int n, i; char arr[20]; clrscr(); printf("Enter size of array(<=20)"); scanf("%d", &n); printf("Enter array"); for (i = 0; i < n; i++) { scanf("%s", &arr[i]); } for (i = 0; i < n; i++) { printf("%s", arr[i]); } getch(); return 0; } ``` The program does not prints the array and instead showsProgram terminationmessage The image shows the program termiantion message
The problem is with the line printf("%s", arr[i]);. If you change this line to printf("%c", arr[i]); then it will work because%sis used with character arrays that contain strings I am just giving the solution for your program termination. Still we can do some modification in your code. Thanks
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.Closed3 years ago.Improve this question I want to write ac codeforsquare wave converterfor some calculation purposes.But I don't have any idea about c code logic for a square wave . Please suggest me any logic which can help me to write a c code for the square wave converter.
A square wave is the easiest, after all its either high or low, on or off, true of false. If you're wanting to output a square wave then just toggle an output on your FPGA (if that is what this is) in relation to a timer. If you're converting an analogue signal to a square wave then you'll need to test against a value,that you set, below which your output is low and above which your output high. This is the basis of digitizing an analogue signal.
I need to create a character double pointer that will have 401 character arrays. Willchar *xx[401]work, or will I have to use malloc and friends? If so, how should I do it?
With ``` char *xx[401]; ``` you are declaring an array of 401pointers tochar. All of them will need to be initialized to some other existing char array, for example in this way ``` char foo[20] = "Hello"; xx[107] = foo; ``` ormalloc'ed, if they are intended to be a dynamically allocated array of strings. If all thesemallocs bother you, you can always define it statically ``` char xx[401][20+1] = { 0 }; /* Population of element at index 137 with a string defined somewhere else in the code: */ char str[] = "Hi guys"; strncpy(xx[123], str, 20); ``` (in this example every string will be of the fixed length of 20+1). But it will have to be a global variable: placing it in the stack wouldn't be the best solution.
This question already has answers here:Pre increment vs Post increment in array(3 answers)Closed3 years ago. ``` #include<stdio.h> int main(){ int array[10] = {3,0,8,1,12,8,9,2,13,10}; int x,y,z; x =++array[2]; y =array[2]++; z =array[x++]; printf("%d\t%d\t%d\n",x,y,z); return(0); } ``` I guessed the output of this would be 9,9,1 orsomething(Actually Not sure)But this broke out when compilied 10,9,10 PS:Forgive me, I am anoob
Here are the values step by step: ``` int array[10] = {3,0,8,1,12,8,9,2,13,10}; int x,y,z; x = ++array[2]; // array[2] becomes 9 before assignment to x // x:9 array[2]:9 y = array[2]++; // array[2] becomes 10 after assignment to y // x:9 y:9 array[2]:10 z = array[x++]; // z becomes array[x] (last element) // x:10 y:9 z:10 ```
This question already has answers here:What is the difference between ++i and i++?(20 answers)Closed3 years ago. Why is the output "false2", when the condition at the if block is 1 which is true ? ``` #include<stdio.h> int main(){ int x=0; if (x++) printf("true1"); else if (x==1) printf("false2"); return 0;} ```
x++means first use the value ofxand then increment it's value by 1. So your if condition isif(0), Thenxvalue increments and becomes 1. So your else if condition iselse if(1). Whereas++xmeans first increase the value ofxby 1 and then use it so your first condition isif(1).
I have this big printf, tha fills with a file. ``` printf("\n%s \t\t%s \t\t%s \t%s \t%s \t%s \t%s \t%s \t%s \t%s \t%s\n", instante, territorio, blancos, nulos, subscritos,elegidos,porcentaje, validos, votos, hondt, estimados); ``` The thing is that I need to format the alignment stdout because now is like this:
You can specify how many characters should be used and rest would be filled with spaces,%20swould give you 20 characters for instance, or%-20sif you want padding on the right side. ``` #include <stdio.h> int main() { char *items[] = { "First", "Second one", "Third" }; char *clients[] = { "Jon Doe", "Carol Anne", "Roscoe Williams" }; printf("%-20s\t%-20s\n", "Item", "Client"); for (int i = 0; i < 3; i++) printf("%-20s\t%-20s\n", items[i], clients[i]); } ```
I'm currently have a code base that uses integer overflow prone additions and multiplications. I'm trying to replace that with__builtin_add_overflow()functions. Reading the source, I found many occurences in the following format: ``` x += y; ``` Can I replace that with__builtin_add_overflow(x, y, &x)or do I need a temporary variable as seen below? ``` int tmp; if (__builtin_add_overflow(x, y, &tmp)) { ... } x = tmp; ```
The first two arguments are passed by value. Only the last one is a pointer. There can be no aliasing issue in such a scenario. Passing by values creates copies (at least conceptually, since inline/static functions and builtins can cheat around the regular function call ABI). The builtin function gets copy ofxand that copy can no longer affect the originalx.
``` #include<stdio.h> void decrease(int *i); int main(){ int i = 10; decrease(&i); printf("%d",i); } void decrease(int *i){ *i = *i - 1; } ``` What would be the Java program for the same?
As you pointed out (no pun intended), Java does not support pointers. So, there is no way to directly manipulate the value of a primitive passed to a method, because only a copy of the primitive would be used in the method. One way to get around this would be to just return the updated value, and then overwrite the integer in the calling scope: ``` public static int decrease(int i) { return i - 1; } public static void main(String[] args) { int i = 10; i = decrease(i); System.out.println(i); // prints 9 } ```
My question is simple: If I have an input of ./foo 3 6 9 the output should be: average : 6 min value: 3 max value: 9 now the question lies. Is it possible to store the command line arguments into an array? I was thinking something like: ``` int numbers[50]; int i = 0; int j = 1; while(argv[j]!=null) { numbers[i] = atoi(argv[j]); i++; j++; } ```
Yes it is possible to store the command line arguments in an array. You can do something like the following to store the arguments after argv[0]: ``` int numbers[50]; int i = 0; while(i+1 < argc) { numbers[i] = atoi(argv[i+1]); printf(" %d ", numbers[i]); i++; } ``` You should useargcas it indicates the number of arguments that were used in the invocation of the program. Please note that this is only an example and I'm not considering any validations on the input.
I want to understand this error. Printing UID of a process, code: ``` printk(KERN_INFO "User ID = %d\n", (task)->cred->uid); ``` The error: ``` error: dereferencing pointer to incomplete type ‘const struct cred’ ```
It's pretty straightforward: the compiler is telling you that the typestruct credis incomplete. In other words, the compiler does not know its definition, and therefore it does not know whether there is auidfield or where in the struct the field is located. Therefore it cannot compile that->uid. To fix this, simply include a correct definition ofstruct cred: ``` #include <linux/cred.h> ```
Say I have variablesdouble x, y, z;and I want to make a txt file with a name based on those variables e.g. "GenericName_x_y_z.txt". How would I create the string? I know functions likeprintf("GenericName_%.2f_%.2f_%.2f.txt", x, y, z)you can do, but how would I define a string like that, not just print it? So then I can use ``` char filename[] = "GenericName_%.2f_%.2f_%.2f.txt"; FILE* fPointer; fPointer = fopen(filename, "w"); ``` I'm sorry the phrasing is really terrible and its probably a really basic thing I'm not getting! Thanks
You're looking forsnprintf(): ``` char filename[128]; snprintf(filename, sizeof(filename), "GenericName_%.2f_%.2f_%.2f.txt", x, y, z); ```
I need to imitate the command: "cat > " using c with exec family. I cant find a way to do it because it doesn't recognize the symbol '>', I've already tried using execlp but maybe my syntax is wrong. Thanks for the help! appreciated.
The command iscat. The>is interpreted by the shell, redirecting the stdout of the command to a specific file. Thus, you would need to connect the stdout (file descriptor 1) of the process runningcatto a file: ``` /* emulating `cat >file` */ int fd = open("file", …); /* use our own fd 1 */ dup2(fd, 1); close(fd); /* with new stdout, exec `cat` */ exec("cat"); ```
I need to imitate the command: "cat > " using c with exec family. I cant find a way to do it because it doesn't recognize the symbol '>', I've already tried using execlp but maybe my syntax is wrong. Thanks for the help! appreciated.
The command iscat. The>is interpreted by the shell, redirecting the stdout of the command to a specific file. Thus, you would need to connect the stdout (file descriptor 1) of the process runningcatto a file: ``` /* emulating `cat >file` */ int fd = open("file", …); /* use our own fd 1 */ dup2(fd, 1); close(fd); /* with new stdout, exec `cat` */ exec("cat"); ```
I need to imitate the command: "cat > " using c with exec family. I cant find a way to do it because it doesn't recognize the symbol '>', I've already tried using execlp but maybe my syntax is wrong. Thanks for the help! appreciated.
The command iscat. The>is interpreted by the shell, redirecting the stdout of the command to a specific file. Thus, you would need to connect the stdout (file descriptor 1) of the process runningcatto a file: ``` /* emulating `cat >file` */ int fd = open("file", …); /* use our own fd 1 */ dup2(fd, 1); close(fd); /* with new stdout, exec `cat` */ exec("cat"); ```
For example: ``` struct sth { int t; char *p; struct sth *next; } ``` And the init code: ``` struct sth *data = malloc(sizeof(*data)); memset(data, 0, sizeof(*data)); data->t = 0; // A data->p = NULL; // B data->next = NULL; // C ``` Since I have usedmemset, do I still need to writeA, B, C? This is just a sample, I have a struct with lots of pointers...
No need. You can also use thecalloc()instead of themalloc(), it will set memory to zero without requiring an additional call to thememset()andmay be faster.
I was studyingstrcat_sand I wrote the following code to practice it. ``` int main(void) { char szPath[128] = { "C:\\Program Files\\" }; strcat_s(szPath + strlen("C:\\Program Files\\"), sizeof(szPath), "CHS\\"); strcat_s(szPath + strlen("C:\\Program Files\\CHS\\"), sizeof(szPath), "C programming"); puts(szPath); return 0; } ``` The output worked properly likeC:\Program Files\CHS\C programming but a debug error window popped up, Stack around the variable 'szPath' was corrupted.What is the cause?
If you sendszPath + strlen("C:\\Program Files\\")as a parameter, then the size of the string issizeof(szPath) - strlen("C:\\Program Files\\"). Same for the second line - size issizeof(szPath) - strlen("C:\\Program Files\\CHS\\"). The string size is 128, but you send a pointer to the middle, where the number of available characters is smaller.
My program return the wrong results. I honestly dont know where the problem is.a==5andb==3, instead of returning the correct results, they return 2 fora ^ 2 + b ^ 2and 10 for(a + b) ^ 2. Unless I am using pointers the wrong way, I do not know what is the problem. ``` #include <stdio.h> #include <stdlib.h> int main() { int a=5; int b=3; int c,d; koko(&a,&b,&c,&d); printf("Rezulat brojeva %d i %d je %d i %d",a,b,c,d); } int koko(int *x,int *y,int *z,int *u) { *z=(*x)^2+(*y)^2; *u=(*x+*y)^2; } ```
The^operator is not for exponentiation in c.it is bitwise XOR operator, see thislink. you can use this instead: ``` int koko(int *x,int *y,int *z,int *u) { *z=((*x)*(*x))+((*y)*(*y)); *u=(*x+*y)*(*x+*y); } ```
I am using the C programming language, and I need to print out a pointer string's length. I triedsizeofandstrlenbut both did not work because I am using a pointer string. This is my main function: ``` char userInput[100], *split[NPTR] = { NULL }, **p = split; ... while (*p) execute(*p++); ``` And here is my execute function: ``` int i = 0; // Array *history; void execute(char *p) { printf(strlen(p)); } ```
Use ``` printf("%zu\n", strlen(p)); ``` printfneeds a format specifier to know what the type of thestrlen(p)is
I need to measure a time inside the C program. I googled and found two options:gettimeofday()andtime()syscalls. For example: ``` #include <time.h> ... time_t start, end; double seconds; time(&start); /* Run some complex algorithm ... */ time(&end); seconds = difftime(end, start); ``` Or ``` #include <sys/time.h> ... struct timeval start, end; double elapsed_time; gettimeofday(&start, NULL); /* Data processing */ gettimeofday(&end, NULL); /* calculate time in ms. */ elapsed_time = (end.tv_sec - start.tv_sec) * 1000.0; elapsed_time += (end.tv_usec - start.tv_usec) / 1000.0; ``` So as I understand, the 2nd method is giving higher accuracy (milli/microseconds), while the first one returns elapsed time only in seconds. Am I right?
Yes, your understanding is correct. There is alsoclock_gettimewhich provides nanosecond resolution. (Whether it actually has nanosecondaccuracydepends on your hardware.)
I am currently messing around with sockets (on a UNIX based system) and would like to get the address and port of a client when they connect. How can I do this?
You can extract it from astruct sockaddr_in(orsockaddr_in6). ``` struct sockaddr_in { sa_family_t sin_family; /* address family: AF_INET */ in_port_t sin_port; /* port in network byte order */ struct in_addr sin_addr; /* internet address */ }; /* Internet address. */ struct in_addr { uint32_t s_addr; /* address in network byte order */ }; ``` See the man page:http://man7.org/linux/man-pages/man7/ip.7.html Also, you can see myDNS-server codeas a practical example (there is extracted IPV6 addresssin6.sin6_addr).
I declare double variables t and tau, and assign them values 1 and 0.00001 This line of code produces 536870912 in the console. What can be the reason? printf("%i\n",round(t/(tau*double(2)))); By the way, I write code in a C++ compiler, but practically it's C.
roundreturns adouble. Printing it with%iis undefined behaviour. Use%ffor printingdouble: ``` printf("%f\n",round(t/(tau*double(2)))); ```
I was studyingstrcat_sand I wrote the following code to practice it. ``` int main(void) { char szPath[128] = { "C:\\Program Files\\" }; strcat_s(szPath + strlen("C:\\Program Files\\"), sizeof(szPath), "CHS\\"); strcat_s(szPath + strlen("C:\\Program Files\\CHS\\"), sizeof(szPath), "C programming"); puts(szPath); return 0; } ``` The output worked properly likeC:\Program Files\CHS\C programming but a debug error window popped up, Stack around the variable 'szPath' was corrupted.What is the cause?
If you sendszPath + strlen("C:\\Program Files\\")as a parameter, then the size of the string issizeof(szPath) - strlen("C:\\Program Files\\"). Same for the second line - size issizeof(szPath) - strlen("C:\\Program Files\\CHS\\"). The string size is 128, but you send a pointer to the middle, where the number of available characters is smaller.
My program return the wrong results. I honestly dont know where the problem is.a==5andb==3, instead of returning the correct results, they return 2 fora ^ 2 + b ^ 2and 10 for(a + b) ^ 2. Unless I am using pointers the wrong way, I do not know what is the problem. ``` #include <stdio.h> #include <stdlib.h> int main() { int a=5; int b=3; int c,d; koko(&a,&b,&c,&d); printf("Rezulat brojeva %d i %d je %d i %d",a,b,c,d); } int koko(int *x,int *y,int *z,int *u) { *z=(*x)^2+(*y)^2; *u=(*x+*y)^2; } ```
The^operator is not for exponentiation in c.it is bitwise XOR operator, see thislink. you can use this instead: ``` int koko(int *x,int *y,int *z,int *u) { *z=((*x)*(*x))+((*y)*(*y)); *u=(*x+*y)*(*x+*y); } ```
I'm trying to learn C Language, and I'm reading and testing a lot about it, but sometimes is difficult to understand why somethings just don't work as expected. Why the example code showed on page 18 of The C Programming Language, Second Edition (Kernighan and Ritchie), don't work? It doesn't show any results for me. ``` #include <stdio.h> main() { long nc; nc = 0; while (getchar() != EOF) ++nc; printf ("%ld\n", nc); } ```
It doesn't show anything because it's waiting for input. If you're running this like./the_executable, it'll always be reading your input because ofgetchar(). And it'll show the results only after the input stream ends. You can cut it off manually by pressing Control+D. Or use the contents of a file as input: ``` ./the_executable < test_file.txt ```
About Leap Year algorithm, ``` if( (year%4==0 && year%100!=0) || (year%400==0)) ``` Why does it use "or" instead "and"year%400==0?
Are you sure about knowing the meaning of what leap year is?
the purpose is to return the sum of *a into *sum but I am not very good with pointers, I believe there should be a & somewhere ``` int sumArray (int * a, int len , int * sum ){ if (a==NULL || sum==NULL ) return -1; int i; for (i=0;i<len;i++){ sum[i]+=a[i]; } return 0; } ```
From what I understand from your comment, the parameter sum is not an array, but rather the variable where the sum will be stored. And since sum is a pointer, to store values into it, you must access its value this way : (*sum) ``` int sumArray (int * a, int len , int * sum ){ if (a==NULL || sum==NULL ) return -1; int i; (*sum) = 0 ; for (i=0;i<len;i++){ (*sum) += a[i]; } return 0; } ```
About Leap Year algorithm, ``` if( (year%4==0 && year%100!=0) || (year%400==0)) ``` Why does it use "or" instead "and"year%400==0?
Are you sure about knowing the meaning of what leap year is?
the purpose is to return the sum of *a into *sum but I am not very good with pointers, I believe there should be a & somewhere ``` int sumArray (int * a, int len , int * sum ){ if (a==NULL || sum==NULL ) return -1; int i; for (i=0;i<len;i++){ sum[i]+=a[i]; } return 0; } ```
From what I understand from your comment, the parameter sum is not an array, but rather the variable where the sum will be stored. And since sum is a pointer, to store values into it, you must access its value this way : (*sum) ``` int sumArray (int * a, int len , int * sum ){ if (a==NULL || sum==NULL ) return -1; int i; (*sum) = 0 ; for (i=0;i<len;i++){ (*sum) += a[i]; } return 0; } ```
I m trying to make a function that checks if a matrix is lower triangular or not but I have a problem running it, it says n and int m are not declared ``` int lower_mat(int mat[n][m],int n, int m) { int i, j; int count=0; if (n==m) { for ( i = 0; i <n; i++) { for ( j = 0; j < m; j++) { if( i < j ) { if (mat[i][j]!=0) { return -1; } } } } return 0; } } ```
declaration ofint mandint nshould come first and then you should use them , you should sayint lower_mat(int n, int m, int mat[n][m])instead ofint lower_mat(int mat[n][m],int n, int m).
Is it possible to delete / unmap / remap a signal? For exemple, ctrl-c actually send a SIGINT signal. Can i modify this, so that ctrl-c keypress doesn't throw a signal but write its ascii value on stdin as any other key? I don't know if I'm very clear, don't hesitate to ask for more informations EDIT: I want my terminal to stop responding to ctrl-c as a signal
On a POSIX system, you can control which character sends SIGINT, or set it to no character. ``` struct termios t; if (tcgetattr(STDIN_FILENO, &t) == 0) { t.c_cc[VINTR] = 0; // set the INT character to 0 (disable) tcsetattr(STDIN_FILENO, TCSANOW, &t); } else { // stdin is not a terminal } ``` SeeGeneral Terminal Interface,tcgetattr,tcsetattr
I am optimizing a c program and I would like to know if it does make any sense to use__attribute__ ((pure))andstatic inlineboth in the same function declaration?
All three attributes are orthogonal to each other: staticsays that function is not used outside of compilation unit so it won't be exported and won't pollute external namespaceinlineincreases the chance that function is inlinedpuretells compiler that function does not have side effects so if inlining fails compiler will still be able to optimize code around function call more aggressively So none of them is a substitute to another and they should be used simultaneously.
I currently have files in .c and .cpp file format in my project. I wanted to automate the object file generation in Makefile to dynamically select the .c or .cpp file based on the availability of the file. Currently, ``` obj/%.o : %.cpp $(CXX) $(MKDEPEND) -c -o $@ $(CFLAGS) $(INCDIRS) $< ``` Sample solution ``` obj/%.o : %.cpp (OR) %.c $(CXX) $(MKDEPEND) -c -o $@ $(CFLAGS) $(INCDIRS) $< ``` Any solution for this? Thanks.
Just make two different rules. You don't want to use the same recipe for both anyway (you don't want to use a C++ compiler to compile C code). ``` obj/%.o : %.cpp $(CXX) $(MKDEPEND) -c -o $@ $(CXXFLAGS) $(INCDIRS) $< obj/%.o : %.c $(CC) $(MKDEPEND) -c -o $@ $(CFLAGS) $(INCDIRS) $< ``` Make will try to match both rules and use whichever one matches, ignoring the others.
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.Closed3 years ago.Improve this question I have looked at several examples of this bubble sort but can't seem to find out what's wrong in mine, I'm weak with loops and such. I have to explain this to my class tomorrow so it'd be great if someone could help,thanks. ``` int main(){ int i,n,j,temp; int a[] = {5,4,3,2,1}; n = 5; for(i=0;i<n;i++){ for(j = 0;j<n-i-1;j++){ if(a[j]>a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } printf("%d",a[i]); }} ```
the problem is not in your bubble sort.you have miss placedprintfremove it and add a loop like this after sorting loops: ``` for (i = 0; i < 5; i++) { printf("%d ", a[i]); } ```
I currently have files in .c and .cpp file format in my project. I wanted to automate the object file generation in Makefile to dynamically select the .c or .cpp file based on the availability of the file. Currently, ``` obj/%.o : %.cpp $(CXX) $(MKDEPEND) -c -o $@ $(CFLAGS) $(INCDIRS) $< ``` Sample solution ``` obj/%.o : %.cpp (OR) %.c $(CXX) $(MKDEPEND) -c -o $@ $(CFLAGS) $(INCDIRS) $< ``` Any solution for this? Thanks.
Just make two different rules. You don't want to use the same recipe for both anyway (you don't want to use a C++ compiler to compile C code). ``` obj/%.o : %.cpp $(CXX) $(MKDEPEND) -c -o $@ $(CXXFLAGS) $(INCDIRS) $< obj/%.o : %.c $(CC) $(MKDEPEND) -c -o $@ $(CFLAGS) $(INCDIRS) $< ``` Make will try to match both rules and use whichever one matches, ignoring the others.
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.Closed3 years ago.Improve this question I have looked at several examples of this bubble sort but can't seem to find out what's wrong in mine, I'm weak with loops and such. I have to explain this to my class tomorrow so it'd be great if someone could help,thanks. ``` int main(){ int i,n,j,temp; int a[] = {5,4,3,2,1}; n = 5; for(i=0;i<n;i++){ for(j = 0;j<n-i-1;j++){ if(a[j]>a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } printf("%d",a[i]); }} ```
the problem is not in your bubble sort.you have miss placedprintfremove it and add a loop like this after sorting loops: ``` for (i = 0; i < 5; i++) { printf("%d ", a[i]); } ```
How can I terminate a string pointer that already has a value? This is what I tried: ``` char* pointer = "Hello"; pointer = "\0" ``` This doesn't work. I am looking for a way to make something with the same concept of this work, since I am not the one declaring the value of the pointer (a function is). The function is therecvfunction in<sys/socket.h>and it doesn't null terminate it for me.
You should know thelengthof your string in order to null terminate it. In your case, therecvfunction returns the length upon successful execution. It returns-1otherwise. The variable, saystr, that stores your string should be capable of storing at leastlength + 1characters in it. Then you can do: ``` ssize_t length = /* Call to recv function */; if (length != -1) str[length] = '\0'; ```
How can I terminate a string pointer that already has a value? This is what I tried: ``` char* pointer = "Hello"; pointer = "\0" ``` This doesn't work. I am looking for a way to make something with the same concept of this work, since I am not the one declaring the value of the pointer (a function is). The function is therecvfunction in<sys/socket.h>and it doesn't null terminate it for me.
You should know thelengthof your string in order to null terminate it. In your case, therecvfunction returns the length upon successful execution. It returns-1otherwise. The variable, saystr, that stores your string should be capable of storing at leastlength + 1characters in it. Then you can do: ``` ssize_t length = /* Call to recv function */; if (length != -1) str[length] = '\0'; ```
I created a test project with the following code to check for problem: ``` #include <stdio.h> #include <math.h> int main(void) { int a; scanf_s("%d", &a); printf("%d", &a); } ``` I enter the input of 1 and it gives me random numbers of 7 digits like this and this can someone help please
Thescanffamily of functions needs addresses because itwritesto those addresses to populate the variables. Since theprintffamily only needs thevalues(although, for C strings, that's the same thing), you should get rid of the&operator: ``` printf("%d", a); ``` Otherwise you're trying to print out the address of that variable rather than the value.