question
stringlengths
25
894
answer
stringlengths
4
863
``` int * ptr = (int *) 0x108; // 264 in bin printf("%d\n", ptr); ``` I don't really understand whats going on- when I do operation like++its adds 4 to the value (probably because the sizeof(int) is 4) but can someone explain to me here whats going on? I obtain error accessing such pointer. Why?
Yes, that is a memory address, but no allocated to you. If you run this on valgrind: ``` int * ptr = (int *) 0x108; // 264 in bin printf("%d\n", *ptr); ``` You get this ==755107==Address 0x108 is not stack'd, malloc'd or (recently) free'd Your process have no access to the memory address. The reason why 264 is printed is because this is the decimal conversation of 0x108 ``` printf( "%d", 0x108); ``` You provided%dto printf,printftries to cast the value as integer. Pass%pto get back the address
I have a small, but annoying, problem here. So here are my structures. ``` typedef struct tElem { struct tElem *ptr; int data; } *tElemPtr; typedef struct { tElemPtr Act; tElemPtr First; } tList; ``` And here is the allocation. This is where theheap corruptionoccurs. ``` tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(tElemPtr)); . . . free(newElemPtr); ``` But it doesn't occur, when I use size of the actual structure. ``` tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(struct tElem)); . . . free(newElemPtr); ``` Could somebody please explain to me, what am I missing here? Thank you.
It's because you are mallocing a pointer not a new struct sizeof(tElemPtr)is going to return the size of a pointer not the size of the struct.
I was writing an algorithm in C/++ and when I was debugging using a print statement (very professional, I know), I saw an odd value:-0. Does this mean the same thing as a regular 0 or could this cause bugs? If so, how can I fix those bugs?
In both languages-0is the unary negation of theintconstant / literal0. If yourintis 2's complement (most likely in C, and must be from C++20), then it's exactly the same as0, and no sane formatter would ever print-0for0. If yourintis 1's complement or signed magnitude then-0is asigned negative zero. It will compare numerically equal to 0 but its bit patternwillbe different. You can convert a signed negative zero to a zero by adding zero! Most likely, your print statement is outputting a slightly negative floating point value, which your formatting is rounding towards zero and therefore you have nothing really to worry about.
Please help me understand this: I have a pointer to a pointerchar** word_array = NULL;Then I dynamically allocate memory in my code:n = 6; word_array = (char *) malloc(n* sizeof(char*));How do I delete all the memory allocated for the "array" of pointers? Is this call tofreeright?free(word_array);Or should I make a loop:for(int i = 0 ; i < n; i++) free(word_array + i);
You used onemalloc, so you should use onefree. Also the cast tochar*is nonsense:word_arrayhas typechar**, notchar*, and casting result ofmalloc()isdiscouraged. So the entire flow will be like this: ``` int n; char** word_array = NULL; n = 6; word_array = malloc(n* sizeof(char*)); if (word_array == NULL) { /* handle allocation error */ } else { /* do some work with word_array */ /* free pointers stored in word_array if they are dynamically allocated and not freed yet */ free(word_array); } ```
``` int * ptr = (int *) 0x108; // 264 in bin printf("%d\n", ptr); ``` I don't really understand whats going on- when I do operation like++its adds 4 to the value (probably because the sizeof(int) is 4) but can someone explain to me here whats going on? I obtain error accessing such pointer. Why?
Yes, that is a memory address, but no allocated to you. If you run this on valgrind: ``` int * ptr = (int *) 0x108; // 264 in bin printf("%d\n", *ptr); ``` You get this ==755107==Address 0x108 is not stack'd, malloc'd or (recently) free'd Your process have no access to the memory address. The reason why 264 is printed is because this is the decimal conversation of 0x108 ``` printf( "%d", 0x108); ``` You provided%dto printf,printftries to cast the value as integer. Pass%pto get back the address
I have a small, but annoying, problem here. So here are my structures. ``` typedef struct tElem { struct tElem *ptr; int data; } *tElemPtr; typedef struct { tElemPtr Act; tElemPtr First; } tList; ``` And here is the allocation. This is where theheap corruptionoccurs. ``` tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(tElemPtr)); . . . free(newElemPtr); ``` But it doesn't occur, when I use size of the actual structure. ``` tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(struct tElem)); . . . free(newElemPtr); ``` Could somebody please explain to me, what am I missing here? Thank you.
It's because you are mallocing a pointer not a new struct sizeof(tElemPtr)is going to return the size of a pointer not the size of the struct.
``` int * ptr = (int *) 0x108; // 264 in bin printf("%d\n", ptr); ``` I don't really understand whats going on- when I do operation like++its adds 4 to the value (probably because the sizeof(int) is 4) but can someone explain to me here whats going on? I obtain error accessing such pointer. Why?
Yes, that is a memory address, but no allocated to you. If you run this on valgrind: ``` int * ptr = (int *) 0x108; // 264 in bin printf("%d\n", *ptr); ``` You get this ==755107==Address 0x108 is not stack'd, malloc'd or (recently) free'd Your process have no access to the memory address. The reason why 264 is printed is because this is the decimal conversation of 0x108 ``` printf( "%d", 0x108); ``` You provided%dto printf,printftries to cast the value as integer. Pass%pto get back the address
I have a small, but annoying, problem here. So here are my structures. ``` typedef struct tElem { struct tElem *ptr; int data; } *tElemPtr; typedef struct { tElemPtr Act; tElemPtr First; } tList; ``` And here is the allocation. This is where theheap corruptionoccurs. ``` tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(tElemPtr)); . . . free(newElemPtr); ``` But it doesn't occur, when I use size of the actual structure. ``` tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(struct tElem)); . . . free(newElemPtr); ``` Could somebody please explain to me, what am I missing here? Thank you.
It's because you are mallocing a pointer not a new struct sizeof(tElemPtr)is going to return the size of a pointer not the size of the struct.
I have to take an input from command line argument. If the argument is invalid it will print an error message and exit. But whatever argument I am giving it is always producing error message. Even if I give the right argument. I don't know whats wrong. ``` if (argv[1][0] !='a' || arg[1][0] !='m') { printf("Error: Invalid arguments!\n"); exit(0); } ```
arg[1][0]is not valid. useargv[1][0]. ``` void printError(){ printf("Invalid Parameter\n"); exit(-1); } int main(int argc, char**argv){ if(argc < 2) printError(); switch(argv[1][0]){ case 'a': // your code break; case 'm': // your code break; default: printError(); } return 0; } ```
I am trying to read multiple lines of input from the user. My code below works fine, but my professor only allow us to use 'break' in switch statements. This is my function below: ``` void getaddress (char address [ ], int limit) { int len = 0; while(fgets(address+len, limit, stdin)) { if(strlen(address+len) == 1) break; limit = strlen(address); limit = limit - len; if(limit <= 0) break; } } ```
Consider simply reading until no room as the first test of thewhile()loop. ``` void getaddress(char address[ ], int limit) { int offset = 0; while(offset + 1 < limit && fgets(address+offset, limit - offset, stdin)) { offset += strlen(address + offset); } } ``` If is important thatsizeinfgets(ptr, size, stdin)is atleast 2to avoid problems.
I should simulate the operation of the strrev() function with an inscription from me. However, I don't understand why I have a series of special characters that don't make sense as output until you stop the program completely. I also tried to see if the problem was in the index "i" with the commented line of code, but it's ok. What could be the problem? thanks! ``` void strrev_new(char *s_to_rev) { int i = 0; int length = 0; length = strlen(s_to_rev); for (i = 0; i < length; i++) { s_to_rev[length - i] = s_to_rev[i]; // printf("%d ----- %d\n", (length-i), i); } } ```
You have an off-by-one error, sincestrlen()returns the length of the string (e.g. 5 forhello), but the last index in the string is 4 (counting from 0). Try ``` s_to_rev[length - 1 - i] = s_to_rev[i]; ```
This question already has answers here:Why my code which uses a logical expression as a case label throws error?(2 answers)Closed2 years ago. Since, there is notruefalseboolean type in C, what does the expressionx == yevaluate to, when it's true and when it's false? If it evaluates to 1 and 0 respectively, which are integers, why can't we use such expressions ascases for aswitchstatement? Is the correct reason behind this: case allows only integer expressions or expressions that evaluate to integers and x == y wouldn't evaluate to an integer (which I don't see how)? orif switch allowed such expressions as cases there is a good chance that mutiple cases will end up having the same value, i.e., wheneverx==y, we'll get a 1, so multiple such cases will evaluate to 1, or 0; which can't be allowed in switch statements.
The reason is not thetypeofx==y, but the fact thatcasetakes a constant.x==yis usually not a constant.
I'm beginning with C I want to change while to for ``` int test(int nb){ int rv = 0; if(nb=1) return (1) while(rv < nb) { // change this line if(rv * rv == nb) return (rv) rv++; } return (0); } ``` Can I do : ``` for (int rv=0; rv<nb.length; rv++) ``` Thanks for your help
So basic syntax offorloop is this :- ``` for(initialization; condition; increment){ // your code } ``` So you can rewrite yourwhileloop asforas follows :- ``` for (int rv=0; rv<nb; rv++){ //rest of code } ``` The problem with your code is :- ``` for (int rv=0; rv<nb.length; nb++) // ^^ nb is integer type so nb.length doesn't make sense ``` Also incrementingnbin your loop will make your loop to iterate forever. Note :-if(nb=1)here, in C,=an is assignment operator. To compare you need to use==.
I wondered if it is possible to initialize a function pointer in C with the declaration of a function without the need to declare it previously. Doing something like this: ``` FunctionPointer my_pointer = void MyFunction() {}; ``` I know that likely you should do something like this: ``` void MyFunction() {} my_pointer = MyFunction; ``` But I was interested to know if the compact's one is possible in some way. Thanks in advance!!
It is impossible. You may not use a declaration as an initializer because the initializer must be an expression.
Both the functionsSDL_GetRenderer(SDL_Window*)andSDL_CreateRenderer(SDL_Window*, int, Uint32)seem to do the same thing: return a pointer toSDL_Rendererfrom the window. However,what method is more appropriate for the task? TheSDL Wikidoes not provide much information on where which method should be used, so please explain what each method does, how they differ and where they should be used.
SDL_CreateRendererallows you to create a renderer for a window by specifying some options. It's stored in the specific window data which you can query withSDL_GetRenderer(so the latter is equivalent to(SDL_Renderer *)SDL_GetWindowData(window, SDL_WINDOWRENDERDATA)) If you callSDL_GetRendererwithout having created it beforehand, you'll get a NULL pointer. If you callSDL_CreateRendereron a window twice, the second call will fail withSDL_SetError("Renderer already associated with window");(see line 805). Seehere
I can make sense of this: ``` #define ADD( f1, f2 ) ( (f1) + (f2) ) ``` And I guess you could write something like ``` #define TWO (1+1) ``` to avoid precedence issues. But why do I often see something like that: ``` #define TCS34725_ADDRESS (0x29) ``` Is there any point in having those parenthesis around a single value?
Both0x29and(0x29)are primary expressions, so the only noticeable difference occurs when converted to string literals by macros: ``` #include <stdio.h> #define A1 (0x29) #define A2 0x29 #define MKSTR_(x) #x #define MKSTR(x) MKSTR_(x) int main(void) { printf("%s\n%s\n", MKSTR(A1), MKSTR(A2)); return 0; } ``` Output: ``` (0x29) 0x29 ``` If you only care about the numeric value, then parentheses around constants in the macro replacement text are superfluous and can be omitted.
The Fibonacci series is not obtained on running this program. The whole process terminates after giving input inscanf. ``` #include <stdio.h> #include <stdlib.h> int fibonacci(int); int main() { int n, i = 0, c; printf("Print the fibonacci series"); scanf("%d", n); for (c = 1; c <= n; c++) { printf("%d\n", fibonacci(i)); i++; } return 0; } int fibonacci(int n) { if (n = 0) return 0; else if (n = 1) return 1; else return (fibonacci(n - 1) + fibonacci(n - 2)); } ```
With scanf you need the give the address of the variable. ``` scanf("%d",&n); <= need to give the address of the integer ``` You can find some examples here:http://www.cplusplus.com/reference/cstdio/scanf/
``` int stat(const char *__restrict__ __file, struct stat *__restrict__ __buf); ``` This function needs to be stubbed in order to cover more branches in an unit test made using Google Unit Test. In file stubs.h I have to stub this function, so I provide the following prototype: ``` int stat_stub(const char *__restrict__ __file, struct stat *__restrict__ __buf); ``` Followed by: ``` #define stat stat_stub int stat_RET; ``` Implementation in stubs.c ``` int stat_stub(const char *__restrict__ __file, struct stat *__restrict__ __buf) { return stat_RET; } ``` The problem is that the define also replacesstruct statwithstruct stat_stub, and this causes a multitude of errors to appear when compiling. I would like to know if there is a workaround to this issue, as I am currently stuck on it.
You can use a macro with parameters. ``` #define stat(p1,p2) stat_stub(p1,p2) ```
I was just wondering if there was something like += but with bitwise instead this is just out of curiosity because I have a project like that coming up soon like what would this be ``` a += b ```
if you want to add using only the bitwise logical operators: ``` #include <stdio.h> int addb(int a, int b) { while (b) { int c = a & b; a = a ^ b; b = c << 1; } return a; } int main(void) { printf("%d\n", addb(5,8)); printf("%d\n", addb(5,-2)); } ```
so i started with aCtutorial online on youtube. i followed every steep but i dont know where i went wrong. i matched my steps many times but im unable to get the desired result. i made anew file>named it first.c>typed the code>new terminal>entered gcc f(tab)im suppose to get anexe fileaccording to the tutorial but it doesn't happen :( here is the screenshort im unable to keep up with the tutorial, every info and help appreciated. thank you:D p.s. extremely sorry if i was unable to present my question properly since its my firt time here, im struggling a bit.
I don't normally develop in Windows so this is a wild guess worth trying. 1- Save your file "Ctrl + s" 2- Do "gcc ./first.c" rather than "gcc .\first.c"
This question already has answers here:Set variable text column width in printf(2 answers)Closed2 years ago. // If I have an int, eg int num=3; //then how can I do this printf(" %nums", some_string); // to get it right aligned by 3 characters context: I need to use a loop to print statements with variable alignments depending on the order they are printed, if I cant use a variable I cant do that.
Yes, it's in theprintfmanpage: Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int.
I am implementing a socket which accepts connection using TLS. I found some information on SO on how it can be implemented using OpenSSL.Turn a simple socket into an SSL socket My question is, Do I have to use openssl (or some other library) to implement TLS compatible socket. Is there any standard C methods to implement it?
There is no standard C library for TLS. There is OpenSSL which is used a lot and works on many platforms but there are also platform specific libraries like SChannel (Microsoft) or Secure Transport (Apple). And there are many more cross-platform like NSS, GnuTLS, Botan, ... . SeeWikipedia: Comparison of TLS implementationsfor more information. Of course, you could in theory implement everything yourself but TLS is a complex protocol. And implementation of cryptographic stuff are much harder to get fully right than most other programming tasks, so better use an established library.
so i started with aCtutorial online on youtube. i followed every steep but i dont know where i went wrong. i matched my steps many times but im unable to get the desired result. i made anew file>named it first.c>typed the code>new terminal>entered gcc f(tab)im suppose to get anexe fileaccording to the tutorial but it doesn't happen :( here is the screenshort im unable to keep up with the tutorial, every info and help appreciated. thank you:D p.s. extremely sorry if i was unable to present my question properly since its my firt time here, im struggling a bit.
I don't normally develop in Windows so this is a wild guess worth trying. 1- Save your file "Ctrl + s" 2- Do "gcc ./first.c" rather than "gcc .\first.c"
This question already has answers here:Set variable text column width in printf(2 answers)Closed2 years ago. // If I have an int, eg int num=3; //then how can I do this printf(" %nums", some_string); // to get it right aligned by 3 characters context: I need to use a loop to print statements with variable alignments depending on the order they are printed, if I cant use a variable I cant do that.
Yes, it's in theprintfmanpage: Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the field width is given in the next argument, or in the m-th argument, respectively, which must be of type int.
This is my code ``` int front=-1, rear=-1, CQUEUE[MAX]; int isFull() { if((rear=MAX-1 && front==0) || front==rear+1) return 1; else return 0; } void enQueue() { printf("\nValue of rear=%d front=%d",rear,front); char ch; if(!isFull()) { printf("\nValue of rear=%d front=%d",rear,front); ...... ``` This is the output on calling the function enQueue() ``` Value of rear=-1 front=-1 Value of rear=0 front=-1 ``` The value ofrearis getting increased by 1 although I'm not increasing it manually.
Look at your first if statement. ``` if (rear=MAX-1 ...) // maybe better if you type: if (rear==MAX-1 ...) ```
This question already has answers here:When should I use ampersand with scanf()(3 answers)Closed2 years ago. I'm just learning the C programming language . Could you explain to me why isn't my output produced? ``` #include <stdio.h> int main (void) { int x , total ; printf("Enter the value of x : "); scanf("%i\n", x); total = (3 * x * x * x * x * x) + (2 * x * x * x * x) - (5 * x * x * x) - (2 * x * x) + (7 * x) - 6; printf("Total value of the polynomial is %i\n", total); return 0 ; } ```
Change the scanf to: ``` scanf("%i", &x); ``` You need to pass in the address of x to assign it a value from the scanf function. Also no \n
This question already has answers here:Are big endian and little endian values portable?(4 answers)Closed2 years ago. Here is a simple c statement: ``` uint32_t x = 0x04000000; ``` On my little endian machine I assumed x would equal 4. But instead it's 67108864. So there must be something very basic that I don't understand. Could you help explain please?
When you do an assignment to a variable, you're setting thevalue, not therepresentation. The hexadecimal number 0x04000000 is the same as the decimal number 67108864 so that is what gets assigned. The fact that the number is represented in hex doesn't change how the assignment works. If you did something like this: ``` unsigned char n[4] = "\x4\x0\x0\x0"; memcpy(&x, n, sizeof(x)); ``` Thenxwould contain the value 4 on a little-endian machine.
How can I get 'l' from this array pointer? ``` char *p[3][2] = {"abc", "defg", "hi", "jklmno", "pqrstuvw", "xyz"}; ``` like ``` printf("%c\n",*((*p)) + 2); ```
Let's use fully brace-enclosed declarations to make your array initializer clearer ``` char *p[3][2] = {{"abc", "defg"}, {"hi", "jklmno"}, {"pqrstuvw", "xyz"}}; ``` now you can see thatp[1]is the array{"hi", "jklmno"}.then you want to get the second string, which isp[1][1]and then the 3rd character:p[1][1][2]. Here is a running example:https://ideone.com/Jd9GWI
How can I get 'l' from this array pointer? ``` char *p[3][2] = {"abc", "defg", "hi", "jklmno", "pqrstuvw", "xyz"}; ``` like ``` printf("%c\n",*((*p)) + 2); ```
Let's use fully brace-enclosed declarations to make your array initializer clearer ``` char *p[3][2] = {{"abc", "defg"}, {"hi", "jklmno"}, {"pqrstuvw", "xyz"}}; ``` now you can see thatp[1]is the array{"hi", "jklmno"}.then you want to get the second string, which isp[1][1]and then the 3rd character:p[1][1][2]. Here is a running example:https://ideone.com/Jd9GWI
The following statement is in a c header: #define FOO_TOKEN_FILE "<foofile>" Does this mean that the string will be replaced by the contents of a file "foofile" (or some other function), or is this just a string literal that only exists exactly as it's written?
After preprocessing, all occurrences ofFOO_TOKEN_FILEin the source text will be replaced with the string literal"<foofile>"- no further expansion or replacement will be done by the preprocessor or compiler. If it's meant to be a placeholder for further processing, then that processing will be done by the source code that uses the macro.
For example, I'd like to access the 6th argument, which has a value of 6: ``` int myfun(int count, ...) { va_list ap; int 6th_arg; va_start(ap, count); // 6th_arg = va_arg(ap*sizeof(int)*5, int); va_end(ap); return 6th_arg; // return 6 } int main() { printf("%d\n", myfun(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); } ```
Theva_argmacro always gets the next argument in the list. If you want to read the 6th argument, you first need to read the 5 that come before it.
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 How do I hide an svg image if it’s globally in the footer. Can I use CSS and get page id and hide it on a certain page? ``` #page1 svg{ display: none; } ```
We use javascript for this ``` jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path $('svg').each(function() { if (this.href === path) { $(this).hide(); } }); }); ```
I bumped into a problem which prompted me to do some research. I have found that a piece of code like this: ``` #include <stdio.h> int main(void) { char i = 0; i++ && puts("Hi!"); printf("%hhd\n", i); } ``` only processes the increment, and outputs: ``` 1 ``` That is not the case if the postfix increment is replaced by a prefix one, it outputs: ``` Hi! 1 ``` Why does it behave like that? I apologise if the question is dumb.
In ``` i++ && puts("Hi!"); ``` iis evaluated before the increment. Because it's0the second part of the expression no longer needs to be evaluated,0 && 0is0,0 && 1is also0. The same expression with a pre-increment means thatiwill be1when it's evaluated, in this case the second part of the expression is important, because1 && 1is possible, but1 && 0is also possible, and these will render different results.
This question already has answers here:can i use c++ compiler to compile c source code? [duplicate](3 answers)What is the difference between g++ and gcc?(10 answers)Closed2 years ago. It's what I believe to be a very simple question. Context: I'm following a tutorial that allows me to run C++ code in Visual Studio Code, but I'm trying to run C code, not C++ code. The program I'm trying to run is a simple Hello World program (shown below), but this question applies to all C code. ``` #include <stdio.h> int main() { printf("Hello World!") } ```
C and C++ are different languages. And even though they share a similar syntax, the semantic meaning of certain constructs are different. C++ incorporates a large part of C, but it also diverges. Youcannotjust assume that C code compiled as C++ will give the same result. You can write code that is both valid C and valid C++ yet mean different things in the two languages.
I tried to develop a recursive function that finds the nth term of the sequence (1,1,3,7,17,41,99,239,577,1393 ...), however, I was unsuccessful: ``` int progRec(int n){ return 2*progRec(n-1) + progRec(n-2);} ``` Any thoughts?
Add the stop condition. I assume it's1 if n <= 2: ``` int progRec(int n) { if (n <= 2) { return 1; } return 2 * progRec(n - 1) + progRec(n - 2); } ``` You can optimize this recursion by eliminating the second branching, which is just recalculating already visited values. Just pass the previous calculated terms as an argument: ``` int progRec(int n, int val = 1, int prev = 1) { return n <= 2 ? val : progRec(n - 1, 2 * val + prev, val); } ``` You can optimize it further into aforloop because now it's just a tail-recursive function.
I have this quadratic algorithm and would like to reduce its asymptotic behavior. The input is an ``` n > 0 ``` corresponding to the progression cardinality, while the output is the sum and subtraction of the terms. Any thoughts? ``` int sum = 0; for (int i = 0; i < n; i++ ){ for (int j = 0; j < n; j++ ){ if (i == j) { sum = sum -1; } else { sum = sum + 1; } } } ```
Apparently the desired value can be calculated directly as follows. ``` int sum = n * n - 2 * n; ``` There aren * niterations of the inner loop's body. For most cases, sum is increased. Forncases (where the pair(i, j)lies on thediagonal) the sum is not only not contributed to, but decreased.
[cquery] type specifier missing, defaults to 'int' [-Wimplicit-int][cquery] redefinition of 'ptr' with a different type: 'int' vs 'int * ``` int *ptr,size=50; ptr=(int*) calloc(size,sizeof(int)); ``` How can i fix this error?Also what is the reason behind this.
For starters this ``` ptr=(int*) calloc(size,sizeof(int)); ``` is not a declaration but an expression statement. You may not place statements in a file scope. Moreover a variable with the static storage duration (and file scope variables have the static storage duration) may be initialized with a compile-time constant. So you should place the statement above in some function for example in main. Also consider a possibility of redesigning your program such a way that it had as few file scope variables as possible.
The short version: I'm trying to use a function in a shared library that hasn't been declared in a header file. Is it possible? If so, how? The long version: I'm trying to use GNU readline-7.0 as a shared library. Unfortunately it will echo input by default unless you turn it off with an api call. Sadly this api call wasn't declared in their header, because someone forgot.see details hereNote: I can't update to a newer readline, so I'm stuck with this library. How do I use this undeclared function?
As noted in the linked bug, there is no external declaration in the header file even though the function exists in the implementation. The link also shows the fix with the added declaration: ``` extern int rl_tty_set_echoing PARAMS((int)); ``` So you can add this in your code right after#include <readline.h>
TL;DR Why does ``` printf("%d\n", 042/10 ); ``` return 3 and not 4? Hey so i actually i actually had this doubt while i was in the Arduino IDE, but then just to verify I did try in another C compiler. The code in Question is here: ``` Serial.println(42/10); ``` This works fine, displays 4. The is the funny bit ``` Serial.println(042/10); ``` This return 3. This seems very fundamental but I couldn't find a suitable post answering this. Thanks in Advance!
The leading zero means it’s octal. 042 is equal to 34 in decimal. And 34/10 is indeed 3 using int math.
samplefile1.txt contains same a name that i want to write twice in a new file. samplefile1.txt - John output that i want is as below samplefile2.txt - JohnJohn ``` #include <stdio.h> int main() { FILE *ptr1; FILE *ptr2; ptr1=fopen("samplefile1","r"); ptr2=fopen("samplefile2.txt","w"); char a; for(int i=0;i<2;i++){ a=fgetc(ptr1); while(a!=EOF){ fprintf(ptr2,"%c",a); printf("%c",a); a=fgetc(ptr1); } } fclose(ptr1); fclose(ptr2); return 0; } ```
The second time you run the loop, you're already at the end of the file, so it never enters the body of thewhileloop because the comparison fails.
I'm getting that problem and don't know how to solve it: That error: ``` error C2440: '=': cannot convert from 'void *' to 'node_t' ``` Code is: ``` node_t* arr = malloc(sizeof(node_t) * temp3); for (int i = 0; i < temp3; i++) arr[i] = NULL; ``` Thanks.
The type ofarr[i]isnode_twhich is not a pointer type (I guessed this from the error message). This code reproduces the problem: ``` #include <stdio.h> #include <stdlib.h> typedef struct { int a, b; } node_t; int main() { node_t* arr = malloc(sizeof(node_t) * 10); for (int i = 0; i < 10; i++) arr[i] = NULL; } ``` You probably need something like this: ``` void initialize_node(node_t *node) { // adapt this to your actual node_t type node->a = 0; node->b = 0; } int main() { node_t* arr = malloc(sizeof(node_t) * 10); for (int i = 0; i < 10; i++) initialize_node(&arr[i]); } ```
When I received packet withrecvat linux, is the kernel did de-fragmentation so I will get de-fragmentation data? Or should I take care of it on user-space?
When receiving UDP data via a socket of typeSOCK_DGRAM, you'll only receive the complete datagram (assuming your input buffer is large enough to receive it). Any IP fragmentation is handled transparently from userspace. If you're using raw sockets, then you need to handle defragmentation yourself.
So im getting left alignment right now with%-<width>sand%-<width>.<decimal places desired> But what if i want to right align? The table im getting now is: ``` DAY MONTH YEAR LAT LONG 01 09 2020 123.4 113.31 ```
Get rid of the minus in your format statement. %<width>s example: ``` #include <stdio.h> int main() { printf("%15s %5d %5.2f 0x%08X\n", "hello", 42, 3.14, 0xDEAD); return 0; } ``` output: ``` Chris@DESKTOP-BCMC1RF ~ $ ./main.exe hello 42 3.14 0x0000DEAD ```
I'm getting the below warning on a C program. It does run. However, how do I fix the warning? ``` warning: format specifies type 'char *' but the argument has type 'char (*)[100]' [-Wformat] printf("%s\n", &buf); ``` The code looks like this: ``` FILE *fp = fopen(filename, "r"); int len = 0; char buf[100]; printf("\n sorting \n"); while (fscanf(fp, "%s", buf) != EOF) { printf("%s\n", &buf); len++; } printf("Sorted\n"); ```
This line is wrong: ``` printf("%s\n", &buf); ``` As the warning says, you need to match%swith achar *parameter.bufis an array, so just using its name in this context will cause it to decay into a pointer to its first element - exactly what you want: ``` printf("%s\n", buf); ``` Using the&explicitly passes a pointer to your array; it'll be the same literal address, but has a different type, and that's what your warning is saying.
An expression generates a value, statements alter the status of the machine, aka, side effects. However, I keep reading that function return is a statement. If I call a function that returns a void, how does that change any status of the machine? Or if I call a function that returns a non-void value, if I don't use it but just calling it how this changes any status? I just don't get why thereturnis a statement? Source:Concepts in Programming Languages. Cambridge: Cambridge University Press, 3.4.1 Statements and Expressions, p. 26
It changes the call stack and program counter. It puts the return value in a known place (depending on calling conventions) Even if you don’t use the return value, the compiler still needs to store it somewhere as it may be called from different compiler units that are unknown.
I'm doing a write up about the concept of the call stack and I want to touch on the limitations of the call stack in different languages. I know there are ways to see how many frames can be on the call stack such as: Python ``` import sys print(sys.getrecursionlimit()) ``` Javascript ``` let count = 0; const counter() { count++; counter(); } counter(); ``` I'd also like to know the same for C. But my main question is whether this number is a number set by the language or if that number is totally dependent on how much ram the device has.
It depends on a lot of things like the operating system, the device, and the amount of RAM. In lots of compiled languages, the operating system lets you grow the stack until the OS decides it doesn't want to give you anymore. In many embedded devices, hackers intentionally grow the stack beyond expected bounds in order to break into the device.
I'm getting the below warning on a C program. It does run. However, how do I fix the warning? ``` warning: format specifies type 'char *' but the argument has type 'char (*)[100]' [-Wformat] printf("%s\n", &buf); ``` The code looks like this: ``` FILE *fp = fopen(filename, "r"); int len = 0; char buf[100]; printf("\n sorting \n"); while (fscanf(fp, "%s", buf) != EOF) { printf("%s\n", &buf); len++; } printf("Sorted\n"); ```
This line is wrong: ``` printf("%s\n", &buf); ``` As the warning says, you need to match%swith achar *parameter.bufis an array, so just using its name in this context will cause it to decay into a pointer to its first element - exactly what you want: ``` printf("%s\n", buf); ``` Using the&explicitly passes a pointer to your array; it'll be the same literal address, but has a different type, and that's what your warning is saying.
An expression generates a value, statements alter the status of the machine, aka, side effects. However, I keep reading that function return is a statement. If I call a function that returns a void, how does that change any status of the machine? Or if I call a function that returns a non-void value, if I don't use it but just calling it how this changes any status? I just don't get why thereturnis a statement? Source:Concepts in Programming Languages. Cambridge: Cambridge University Press, 3.4.1 Statements and Expressions, p. 26
It changes the call stack and program counter. It puts the return value in a known place (depending on calling conventions) Even if you don’t use the return value, the compiler still needs to store it somewhere as it may be called from different compiler units that are unknown.
I'm doing a write up about the concept of the call stack and I want to touch on the limitations of the call stack in different languages. I know there are ways to see how many frames can be on the call stack such as: Python ``` import sys print(sys.getrecursionlimit()) ``` Javascript ``` let count = 0; const counter() { count++; counter(); } counter(); ``` I'd also like to know the same for C. But my main question is whether this number is a number set by the language or if that number is totally dependent on how much ram the device has.
It depends on a lot of things like the operating system, the device, and the amount of RAM. In lots of compiled languages, the operating system lets you grow the stack until the OS decides it doesn't want to give you anymore. In many embedded devices, hackers intentionally grow the stack beyond expected bounds in order to break into the device.
Doesprintf()seterrnoto an appropriate value apart from just returning 'a negative value' upon failure ? I can't seem to find man pages that say anything about this on Google . Close this question if it's a duplicate. Link the answer .
Yes it does, on any POSIX system, but not necessarily in any ISO C implementation. Fromhttps://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html: If an output error was encountered, these functions shall return a negative valueand set errno to indicate the error. The bolded part is marked as an extension to ISO C.
I am a complete beginner to reverse engg. In recent times I have been going through gdb and how to debug the programss. I have a big doubt bear me if it is a simple one ``` #include <stdio.h> #include <stdlib.h> int flag(void){ puts("okay you got this"); } int main(void){ puts("nope try again"); } ``` So i compiled this this program successfully, When I try run this program it gives me main function output ``` nope try again ``` so now how do i call the flag function to give the "okay you got this" output in gdbI tried my best evrything and surfed blogs to get the answer but i endded up in failureHope ill get the solution and kindly suggest me what am I missing and what i needed to know on how does this works
You mean how to callflag()and skip theputsinmain?, in this case: ``` (gdb) break main (gdb) run (gdb) print flag() okay you got this (gdb) break 10 (gdb) jump 10 (gdb) quit ```
Can anyone point out what's wrong with this code and why the first print case won't work but the second won't? Thanks! ``` char source[] = "hello folks"; char destination[11]; strcpy(destination, source); for(int i = 0; source[i]; i++) { printf("%c" , source[i]); } printf("\n"); for(int i = 0; destination[i]; i++) { printf("%c" , destination[i]); } printf("\n"); ```
You declaredestinationas an array of 11 chars, but then you usestrcpyto copy 12 chars fromsourceinto it. Every string needs to have a NUL terminator, which is part of the string, so it is important to count it when figuring out the size of an array needed to hold the string.
How would i store any type of file with text ex. sasm, mach(for machine code) etc. I dont want to have to write it like this and put it directly into the arrayhttps://ttm.sh/hPS.pngi want to be able to take text from a file with text on it like this ``` 0x1000 0x30C3 0x11FC ``` and store that into the array program[] and have a new line be a new spot into an array
How about: ``` unsigned program[] = { #include "program.mach" }; ``` With program.mach looking like: ``` 0x1000, 0x30C3, 0x11FC ```
I can print to four decimal places withprintf("Value: %0.4f\n", value); however, is there a way to make the number of decimals a value inserted with%d?, for example, something like: ``` double x = 3.434244; int decimalPlaces = 4; printf("Value: %0.%df\n", x, decimalPlaces); ```
You can put a*in place of the field width or the precision, in which case anintis expected to fill in the value. ``` printf("Value: %0.*f\n", decimalPlaces, x); ```
This code is printing the present date but I want to save it for future records like the amount was deposited on this date. How to do it and how to save it in a way that it could be used with other functions also? ``` #include <stdlib.h> #include <stdio.h> #include <time.h> int main(void) { time_t now = time(NULL); struct tm *t = localtime(&now); printf( "%d-", t->tm_mon+1 ); printf( "%d-", t->tm_mday ); printf( "%d\n", t->tm_year+1900 ); return 0; } ```
Use a file and print via fprintf() into that file.
I came across a quiz using C language relating to pointers, but I don't know if I got the answers right or wrong. The following code is given and finding out the result. By the way, the address for variablea, p, q, ris seen as500, 600, 700, 800. ``` int main(void) { int a = 10, *p = &a, **q = &p, ***r = &q; printf("%u %u %u %u %u", &a, p, q, r, *r); return 0; } ``` What I thought was p points to a's address, q points to p's address, and r points to q's address. Therefore,&aequals top, andqequals to*r. Therefore, I assumed the results would be500 500 600 700 600. Would this be the correct answer?
if p holds the address of a,then p=500,again q holds the address of p,so q=600,r holds address of q,so r=700,and *r=600..so final ans is 500,500,600,700,600.that means your assumption is absolutely right.
My question: Is this: ``` if (...) { } else if (...) { } ``` Equal to this? ``` if (...) { } else { if (...) { } } ``` Indeed, I guess that in the two cases the result would be the same but is else..if a different statement in C ?
The C language has no feature calledelse if. That one is only obtained through coding style. Your example is 100% equivalent to this: ``` if (...) { } else if (...) { } ``` Where the secondifis a single statement belowelse, so we can write it without{}.
I have this basic program: ``` #include<stdio.h> int main() { printf("Hello, world!"); return 0; } ``` but how can I saw the compiler said: Hello, world! and how can I start it? sorry if it's simple but I'm new.
If you're using any UNIX (Linux/Mac) machine it's pretty simple: You open up the terminal in the folder your program is located.For example you type ingcc "program_name.c" -o "program_name"to compile the programAnd now you have to execute the program in the terminal typing this./"program_name" you can put whatever you like in the "program_name" :)
This is my prime number sum code. The input is unlimited but has to finish with 0. For example, the input 11, 4, 9, 17 should output the sum of prime numbers which in this case is 28. My code prints just 11. The loop stops once it has reached any derivative of 2 and I can not find a solution to this easy problem. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char*argv[]) { int n, i, flag; int sumOfPrimeNumbers; sumOfPrimeNumbers = 0; flag = 0; do { for(i=2;i < n;i++) { scanf("%d", &n); if(n%i==0) { flag=1; } } if(flag==0) { sumOfPrimeNumbers = sumOfPrimeNumbers + n; break; } } while (n != 0); printf("%d\n", sumOfPrimeNumbers); return 0; } ```
Both the commentors are right. You are using 'n' variable before accepting value from user and storing it in 'n' variable.
I have written a simple c program and given it a name ofprogramWhen The code is made to run using code runner extension it uses this kind of statement ``` PS C:\Users\user_name> cd "c:\Users\user_name\Desktop\" ; if ($?) { gcc program.c -o program } ; if ($?) { .\program } ``` In this i could understand ( gcc program.c -o program ) but what doesif ($?) and if($?) {.\program }mean ?
if($?) means if the previous step is successful ``` PS C:\Users\user_name> cd "c:\Users\user_name\Desktop\" ; if ($?) { gcc program.c -o program } ; ``` here if ($?) means if there exists a file named program.c then compile using the command ``` gcc program.c -o program ``` so does the next line, ``` if ($?) { .\program } ``` if the executable file is succesfully created then run the executable file using.\programcommand
I have this basic program: ``` #include<stdio.h> int main() { printf("Hello, world!"); return 0; } ``` but how can I saw the compiler said: Hello, world! and how can I start it? sorry if it's simple but I'm new.
If you're using any UNIX (Linux/Mac) machine it's pretty simple: You open up the terminal in the folder your program is located.For example you type ingcc "program_name.c" -o "program_name"to compile the programAnd now you have to execute the program in the terminal typing this./"program_name" you can put whatever you like in the "program_name" :)
This is my prime number sum code. The input is unlimited but has to finish with 0. For example, the input 11, 4, 9, 17 should output the sum of prime numbers which in this case is 28. My code prints just 11. The loop stops once it has reached any derivative of 2 and I can not find a solution to this easy problem. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char*argv[]) { int n, i, flag; int sumOfPrimeNumbers; sumOfPrimeNumbers = 0; flag = 0; do { for(i=2;i < n;i++) { scanf("%d", &n); if(n%i==0) { flag=1; } } if(flag==0) { sumOfPrimeNumbers = sumOfPrimeNumbers + n; break; } } while (n != 0); printf("%d\n", sumOfPrimeNumbers); return 0; } ```
Both the commentors are right. You are using 'n' variable before accepting value from user and storing it in 'n' variable.
I have written a simple c program and given it a name ofprogramWhen The code is made to run using code runner extension it uses this kind of statement ``` PS C:\Users\user_name> cd "c:\Users\user_name\Desktop\" ; if ($?) { gcc program.c -o program } ; if ($?) { .\program } ``` In this i could understand ( gcc program.c -o program ) but what doesif ($?) and if($?) {.\program }mean ?
if($?) means if the previous step is successful ``` PS C:\Users\user_name> cd "c:\Users\user_name\Desktop\" ; if ($?) { gcc program.c -o program } ; ``` here if ($?) means if there exists a file named program.c then compile using the command ``` gcc program.c -o program ``` so does the next line, ``` if ($?) { .\program } ``` if the executable file is succesfully created then run the executable file using.\programcommand
I am trying to separately run server and client on the port number 19345, but I want to compile them all at once by simply typingmakeusingMakefile. To do so, I created the followingMakefile: ``` target: run_server run_client run_server: ./server 19345 run_client: ./client 19345 server: server.c gcc -o server.c client: client.c gcc -o client.c clean: rm *.o run_server run_client target ``` Unfortunately, when I typedmake, the terminal result shows as follows: ``` ./server 19345 make: ./server: Command not found Makefile:4: recipe for target 'run_server' failed make: *** [run_server] Error 127 ``` How can I fix this problem?
You can probably just do: ``` .PHONY: target run_server run_client target: run_server run_client run_server: server ./server 19345 run_client: client ./client 19345 clean: rm -f *.o server client ```
I am trying to separately run server and client on the port number 19345, but I want to compile them all at once by simply typingmakeusingMakefile. To do so, I created the followingMakefile: ``` target: run_server run_client run_server: ./server 19345 run_client: ./client 19345 server: server.c gcc -o server.c client: client.c gcc -o client.c clean: rm *.o run_server run_client target ``` Unfortunately, when I typedmake, the terminal result shows as follows: ``` ./server 19345 make: ./server: Command not found Makefile:4: recipe for target 'run_server' failed make: *** [run_server] Error 127 ``` How can I fix this problem?
You can probably just do: ``` .PHONY: target run_server run_client target: run_server run_client run_server: server ./server 19345 run_client: client ./client 19345 clean: rm -f *.o server client ```
I expect Packcc parser generator "$0s" or "$0e" variables to throw an int in the parser actions, because theses variables represents a position in the input. I made a minimal parser that prints the position of the last char of the word. ``` word <- [a-z]+[\n] {printf("Position %i\n", $0e);} %% int main() { pcc_context_t *ctx = pcc_create(NULL); while(pcc_parse(ctx, NULL)); pcc_destroy(ctx); return 0; } ``` After parser generation using "packcc" command I compile the C generated file then Gcc sends this warning. warning: type defaults to 'int' in type name [-Wimplicit-int] Thank you in advance.
This looks like a bug in that version of the packcc parser generator. It is nowfixedin master, so try upgrading. Or you can simply ignore the warning as the type should indeed beint.
Some languages have easy ways of doing this, but my question revolves in C and C++. I wanna do something like this in Java: ``` public class sandbox { public static void main(String[] args) { System.out.println("Thank" + " you!"); } } ``` And transfer it in C: ``` #include <stdio.h> int main() { /* The easiest way is like this: char *text1 = "Thank"; char *text2 = " you"; printf("%s%s\n", text1, text2); */ printf("Thank" + " you."); // What I really want to do } ``` How do I concatenate strings in a language like this?
You use just nothing: ``` puts ("Thank" " you."); ```
I want to init my LinkedList, but failed. ``` typedef int ElemType; typedef struct LNode { ElemType data; struct LNode* next; }LNode, *LinkedList; void Init(LinkedList L) { L = (LNode *)malloc(sizeof(LNode)); L->next = NULL; } int main() { LinkedList head; Init(head); return 0; } ``` If I Init my LinkedList like this it works. ``` LNode node = (LNode *)malloc(sizeof(int)); node->data = 5; node->next = NULL; LinkedList head = node; ``` but this will make my head with a value.
``` void Init(LNode **L, ElemType data) { *L = malloc(sizeof(LNode)); (*L)->data = data; (*L)->next = NULL; } int main() { LinkedList head; Init(&head, 0); // ... free(head); return 0; } ``` Initializing your head to not contain a value doesn't really make sense, unless you actually wanthead = NULLwhich I assume is not the case.
I would like to print the remaining string by a deliminator. The expected output should be: String in C ``` int main() { /* loop over a string using subscript*/ char *s = "String in C"; char* ps; ps = s; while(*ps != ' ') { printf("%c",*ps); ps++; } } ``` I can get the firstString. How can I get the rest of it?
This is not the best solution but it works. ``` #include <stdio.h> int main() { char *s = "String in C"; char *ps; ps = s; while (*ps != '\0') { if (*ps == ' ') { printf("\n"); *ps++; } else { printf("%c", *ps); ps++; } } } ```
I am trying to create a bitmaped data in , here is the code I used but I am not able to figure the right logic. Here's my code ``` bool a=1; bool b=0; bool c=1; bool d=0; uint8_t output = a|b|c|d; printf("outupt = %X", output); ``` I want my output to be "1010" which is equivalent to hex "0x0A". How do I do it ??
The bitwise or operatorors the bits in each position. The result ofa|b|c|dwill be1because you're bitwiseoring 0 and 1 in theleastsignificant position. You can shift (<<) the bits to the correct positions like this: ``` uint8_t output = a << 3 | b << 2 | c << 1 | d; ``` This will result in ``` 00001000 (a << 3) 00000000 (b << 2) 00000010 (c << 1) | 00000000 (d; d << 0) -------- 00001010 (output) ``` Strictly speaking, the calculation happens withints and the intermediate results have more leading zeroes, but in this case we do not need to care about that.
I expect Packcc parser generator "$0s" or "$0e" variables to throw an int in the parser actions, because theses variables represents a position in the input. I made a minimal parser that prints the position of the last char of the word. ``` word <- [a-z]+[\n] {printf("Position %i\n", $0e);} %% int main() { pcc_context_t *ctx = pcc_create(NULL); while(pcc_parse(ctx, NULL)); pcc_destroy(ctx); return 0; } ``` After parser generation using "packcc" command I compile the C generated file then Gcc sends this warning. warning: type defaults to 'int' in type name [-Wimplicit-int] Thank you in advance.
This looks like a bug in that version of the packcc parser generator. It is nowfixedin master, so try upgrading. Or you can simply ignore the warning as the type should indeed beint.
Some languages have easy ways of doing this, but my question revolves in C and C++. I wanna do something like this in Java: ``` public class sandbox { public static void main(String[] args) { System.out.println("Thank" + " you!"); } } ``` And transfer it in C: ``` #include <stdio.h> int main() { /* The easiest way is like this: char *text1 = "Thank"; char *text2 = " you"; printf("%s%s\n", text1, text2); */ printf("Thank" + " you."); // What I really want to do } ``` How do I concatenate strings in a language like this?
You use just nothing: ``` puts ("Thank" " you."); ```
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 wrote a program to sum int array but i want if one input is string(character) then the program will give error "You Must Enter Int value". my following code: ``` #include <stdio.h> int main() { int a[1000],i,n,sum=0; printf("Enter size of the array : "); scanf("%d",&n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d",&a[i]); } for(i=0; i<n; i++) { sum+=a[i]; } printf("sum of array is : %d",sum); return 0; } ```
scanf()returns the number of successfully matched input items. So, check ifscanf()returns 1.
When analyzing core on different machine, that binary was built for I ran into: ``` warning: .dynamic section for "/lib64/libc.so.6" is not at the expected address (wrong library or version mismatch?) ``` Is there a way to change which libc gdb is looking for?
Thanks to@Kevin Boone! set sysroothelped I set it to./and put desired libc in./lib64and then loaded core usingcore-file
I use theMin-GW GCC compileronWindows 10. Every time I compile, I need to make a.exeand then run it. Could there be any way to do the whole thing in one step?
You can combine commands in windows like you do on linux or macos! ``` gcc compilefile && c:/executefile.exe ``` (you need to replace that stuff with min-gw and your exe path) links: How do I run two commands in one line in Windows CMD?How to run an executable in Windows Terminal?
I am using the following code: ``` #include <msp430.h> int flip(int flip){ if (flip) {flip = 0;} else {flip = 1;} return flip; } /*...*/ void main(void){ int ctrl = 0; while(1){ ctrl = flip(ctrl); } } ``` When I attempt to compile I get the error, referring to the line: ``` ctrl = flip(ctrl); error #110: expression preceding parentheses of apparent call must have (pointer-to-) function type ``` I don't understand why the compiler is giving me this error. Replies are correct: the compiler doesn't like it when I'm using the same name for a variable and a function. Fixed.
The compiler is getting confused because, in your context,fliprefers both to a function and to anint. You should change the name of the argument to something else.
I need to print text "Please, write something" if user run programm like "./programm". and don't print text in file if user use "./programm > file.txt". How can i detect, that user use redirect to file? My code on C: ``` #include <stdio.h> int main() { char buffer[100] = "It was readed..."; int cb; write(1,"Vvedite\n", 8); // записываем в 1 текст Vvedite кол-во байтов 8 cb = read(0, buffer+18, 80); cb+=18; write(1, buffer, cb); return 0; } ```
You could use theisatty()callto find out whether the standard output (1) is attached to a TTY (console).
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 wrote a program to sum int array but i want if one input is string(character) then the program will give error "You Must Enter Int value". my following code: ``` #include <stdio.h> int main() { int a[1000],i,n,sum=0; printf("Enter size of the array : "); scanf("%d",&n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d",&a[i]); } for(i=0; i<n; i++) { sum+=a[i]; } printf("sum of array is : %d",sum); return 0; } ```
scanf()returns the number of successfully matched input items. So, check ifscanf()returns 1.
When analyzing core on different machine, that binary was built for I ran into: ``` warning: .dynamic section for "/lib64/libc.so.6" is not at the expected address (wrong library or version mismatch?) ``` Is there a way to change which libc gdb is looking for?
Thanks to@Kevin Boone! set sysroothelped I set it to./and put desired libc in./lib64and then loaded core usingcore-file
I use theMin-GW GCC compileronWindows 10. Every time I compile, I need to make a.exeand then run it. Could there be any way to do the whole thing in one step?
You can combine commands in windows like you do on linux or macos! ``` gcc compilefile && c:/executefile.exe ``` (you need to replace that stuff with min-gw and your exe path) links: How do I run two commands in one line in Windows CMD?How to run an executable in Windows Terminal?
I am using the following code: ``` #include <msp430.h> int flip(int flip){ if (flip) {flip = 0;} else {flip = 1;} return flip; } /*...*/ void main(void){ int ctrl = 0; while(1){ ctrl = flip(ctrl); } } ``` When I attempt to compile I get the error, referring to the line: ``` ctrl = flip(ctrl); error #110: expression preceding parentheses of apparent call must have (pointer-to-) function type ``` I don't understand why the compiler is giving me this error. Replies are correct: the compiler doesn't like it when I'm using the same name for a variable and a function. Fixed.
The compiler is getting confused because, in your context,fliprefers both to a function and to anint. You should change the name of the argument to something else.
I need to print text "Please, write something" if user run programm like "./programm". and don't print text in file if user use "./programm > file.txt". How can i detect, that user use redirect to file? My code on C: ``` #include <stdio.h> int main() { char buffer[100] = "It was readed..."; int cb; write(1,"Vvedite\n", 8); // записываем в 1 текст Vvedite кол-во байтов 8 cb = read(0, buffer+18, 80); cb+=18; write(1, buffer, cb); return 0; } ```
You could use theisatty()callto find out whether the standard output (1) is attached to a TTY (console).
``` #define CONVERT(val, qin, qout) ((qin > qout) ? (val >> (qin-qout) ) : (val << (qout-qin))) void f(void) { ... y = CONVERT(x, 25, 31); } ``` Is the above macro going to be evaluated by GCC at compile time? I mean the(qin > qout)part. I am trying to have onlyy = x << (31-25)after the compilation is done.
Theqin > qoutpart will end up as aninteger constant expressionin this case, which the compiler can optimize into1or0in theory. In practice, it doesn't even do that. Looking at how real compilers actually treats your example, gcc and clang at-O0(optimizations off) only generates the code for the left shift, omitting the conditional check and branch of?:, as well as the second operand which is never true. The machine code ends up boiling down to the equivalent ofy = x << 6;, completely branch free.
I am going through a book and this example isn't explained properly. As far as I understand, the array variable (nums) is a pointer to an array. Next step I declare a variablechoiceand give it a value of the address of the array. Then I pass the value behind choice(which I thought would be {1, 2, 3}) to the last element of the array. Printing the last element I get 1. How come that? What don't I understand about pointers? ``` int nums[] = {1, 2, 3}; int *choice = nums; nums[2] = *choice; printf("%i", nums[2]); ```
numsisnota pointer to an array.numsisan array, and when used in an expression it is converted to a pointer to the first element. So when you do this: ``` int *choice = nums; ``` It makeschoicepoint to the first element ofnums. Then when you use*choiceyou get the value of the first element ofnums.
This question already has answers here:why negative number is taken as true in condition statement? [duplicate](5 answers)Closed3 years ago. In my current class I am seeing a lot of times where my teacher puts a number as the condition of an if statement then asks for the output. I'm confused as to how these statements are being evaluated. Example: ``` if(-1) { x = 35; } ``` or ``` if(0) { x = 35; } ``` Why does it go inside the if statement instead of just ignoring it? What is makingif(-1)evaluate true? And why doesif(0)evaluate false? This is an online class so I can't get help directly from the teacher usually. I have searched for a few hours on various websites about C for loops, but I haven't found anything relevant yet to my question.
C doesn't have a "real" boolean type. When evaluating integers,0is a "false", and anything else is a "true" value.
I am trying to use portaudio in one of my projects. Unfortunately, I cannot compile my main.c file. Error: "undefined reference to 'Pa_Initialize'"(Pa_Initialize is a function from the portaudio library) My working directory includes the .a file from portaudio as well as the portaudio.h. My current gcc command:gcc main.c libportaudio.a -lm -o main Update:these are the includes in my main.c ``` #include <stdio.h> #include <math.h> #include "portaudio.h" ```
If you get anundefined referenceerror, you have probably already integrated the header fileportaudio.h. As Kurt E. Clothier already mentioned, you must also mention the libraries inside your gcc command. According tothe portaudio website, the gcc command is ``` gcc main.c libportaudio.a -lrt -lm -lasound -ljack -pthread -o main ```
when I am executing the "script load" command through hiredis adapter I am getting the error wrong no of argument. The same command through Redis client is running fine. ``` reply_r= (redisReply *)redisCommand(con_r,"script","load", "return 1"); string stemp=""; if(reply_r->len>0) { string stt(reply_r->str); stemp=stt; //printf("Commad Reply : %s\n", reply_r->str); } freeReplyObject(reply_r);// should free the object after reading the data return stemp; ```
``` reply_r= (redisReply *)redisCommand(con_r,"scrips load %s", "return 1"); string stemp=""; if(reply_r->len>0 && reply_r!=NULL) { stemp=string(reply_r->str); } freeReplyObject(reply_r);// should free the object after reading the data return stemp; ```
``` char name[] = "Name123"; //string write(2, name[strlen(name)-1], 1); //required to write 3 to terminal ``` After compiling the above code, a warning is returned saying passing argument 2 of "write" makes pointer from integer without a cast. Upon running, I do not get an output. Can someone teach me how to access a character in the string of an index of my choice and write it into terminal using 'write()' only.
writeexpects a pointer. Add&to pass theaddressof3. ``` write(2, &name[strlen(name)-1], 1); ```
strspn("string", "chars")gives the length of the initial span in string consisting of characters in "chars", whilestrcspn("string", "chars")gives the length of the initial span in string consisting of characters not in "chars". What stands the "c" for?
What does the “c” in strcspn stand for? For the word "complementary". Fromcppreference strcspn: The function name stands for "complementary span" because the function searches for characters not found in src, that is the complement of src.
Is it possible to print '#'ntimes using aforloop in C? I am used toprint(n * '#')in Python. Is there an equivalent for that in C? ``` for(i=0; i < h; i++) { printf("%s\n", i * h); } ```
No. It's not possible by any mechanism in standard C. If you want a string of some sub-string repeated n times, you will have to construct it yourself. Simple example: ``` const char *substring = "foo"; // We could use `sizeof` rather than `strlen` because it's // a static string, but this is more general. char buf[8192]; size_t len = strlen(substring); char *ptr = buf; // Ideally you should check whether there's still room in the buffer. for (int i = 0; i < 10; ++i) { memcpy(ptr, substring, len); ptr += len; } *ptr = '\0'; printf("%s\n", buf); ```
Below is a command parsing function. It splits user input at the"-". If"time-10"is passed in,10is returned. If no"-"is found I want to returnNULLso I know that no"-"was found and the program can make decisions passed on that information. However, because the function return type ischarI have to return achar pointer,and am currently satisfying this requirement by returning the original argument. Is there a way around this, or do I HAVE to return a Char pointer and write code that determines if that return value equates to,'no - found'? ``` char * second_arg(char * arg) { char * j = strchr(arg, '-'); if(j==NULL) { return arg; } return ++j; } ```
The function return type is notchar; it ischar *. Since the function already returns a pointer tochar, it is very easy to return NULL. Just change the linereturn arg;to sayreturn NULL;
I have a parser method that is parsing an API call. I am usingstrstr()in my parsing function. Myparse_apifunction is allowing me to return the pointer returned bystrstr. Am I correct in assuming that this meansstrstrmallocs a memory space and I need to free it? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> char *parse_api(char *str); int main() { char str[] = "dadsadsdsdsdamountdsafoodsd"; puts(parse_api(str)); return 0; } char *parse_api(char *str) { char *needle; char *updated_needle; needle = strstr(str, "amount"); puts(needle); updated_needle = needle + 9; updated_needle[strlen(updated_needle) - 3] = '\0'; return updated_needle; } ```
Thestrstrfunction doesnotreturn alloc'ed memory. It returns a pointer to the start of the substring inside of thehaystackparameter. So in this casestrstrwill returnstr + 12.
In my C program on Linux, I fork off a child process and callvimon a file. The line is ``` execl(editor,path,NULL); ``` whereeditoris aconst char*pointing to"vim"andpathis aconst char*pointing to"../grr/engine/nfaRuntime.c". Under strace, I see ``` [pid 2022] execve("vim", ["../grr/engine/nfaRuntime.c"], 0x7ffc32f38ea8 /* 28 vars */) = -1 ENOENT (No such file or directory) ``` However, vim is installed on my computer (and withinPATH) and the specified file does exist. I also have read access to it. I have confirmed, viagetcwd, that my program is running inside thegrrdirectory.
execldoes not search the paths given byPATH.execlpdoes.
Below is a command parsing function. It splits user input at the"-". If"time-10"is passed in,10is returned. If no"-"is found I want to returnNULLso I know that no"-"was found and the program can make decisions passed on that information. However, because the function return type ischarI have to return achar pointer,and am currently satisfying this requirement by returning the original argument. Is there a way around this, or do I HAVE to return a Char pointer and write code that determines if that return value equates to,'no - found'? ``` char * second_arg(char * arg) { char * j = strchr(arg, '-'); if(j==NULL) { return arg; } return ++j; } ```
The function return type is notchar; it ischar *. Since the function already returns a pointer tochar, it is very easy to return NULL. Just change the linereturn arg;to sayreturn NULL;
I have a parser method that is parsing an API call. I am usingstrstr()in my parsing function. Myparse_apifunction is allowing me to return the pointer returned bystrstr. Am I correct in assuming that this meansstrstrmallocs a memory space and I need to free it? ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> char *parse_api(char *str); int main() { char str[] = "dadsadsdsdsdamountdsafoodsd"; puts(parse_api(str)); return 0; } char *parse_api(char *str) { char *needle; char *updated_needle; needle = strstr(str, "amount"); puts(needle); updated_needle = needle + 9; updated_needle[strlen(updated_needle) - 3] = '\0'; return updated_needle; } ```
Thestrstrfunction doesnotreturn alloc'ed memory. It returns a pointer to the start of the substring inside of thehaystackparameter. So in this casestrstrwill returnstr + 12.
In my C program on Linux, I fork off a child process and callvimon a file. The line is ``` execl(editor,path,NULL); ``` whereeditoris aconst char*pointing to"vim"andpathis aconst char*pointing to"../grr/engine/nfaRuntime.c". Under strace, I see ``` [pid 2022] execve("vim", ["../grr/engine/nfaRuntime.c"], 0x7ffc32f38ea8 /* 28 vars */) = -1 ENOENT (No such file or directory) ``` However, vim is installed on my computer (and withinPATH) and the specified file does exist. I also have read access to it. I have confirmed, viagetcwd, that my program is running inside thegrrdirectory.
execldoes not search the paths given byPATH.execlpdoes.
Let's say I have aforloop and an array of ints. In myforloop, I sayif (array[i] == 2)then I want to skip all the rest of theforloop and go to the next instance. now I can't use thebreakkeyword as that will exit out of the entire loop. What can I use to exit out of only one instance?
You have to use continue to go to the next iteration: ``` if (array[i] == 2) continue; ```
I would like to know which case is SIG_ERR among the return values ​​of the signal function. ``` __sighandler_t oldHandler = signal( SIGSEGV, newSignalHandler ); if( oldHandler == SIG_ERR ) { // In what case? } ```
The man page for each system call is supposed to list all possible error conditions under the "ERRORS" heading, along with the corresponding values to whicherrnois set in each case. Theman page forsignal(2)shows only: EINVALsignumis invalid. This occurs ifsignum(the first argument) isn't the number of a valid signal, or is eitherSIGKILLorSIGSTOPwhich cannot be caught or ignored. As such, if you have passedSIGSEGVas the first argument,signal()should never fail. (I initially thought it could also fail ifhandlerwas an invalid pointer, but it seems in this case that it just installs the invalid pointer as the handler, and thus will segfault or otherwise misbehave should the signal actually be raised.)
I expected to find a function along the lines ofkobject_check_refcount, that returned the current refcount without altering it, inkobject.c, but as far as I can see there isn't one. Is there such a function existing in the kernel source somewhere? I can see it being useful for debugging purposes at points. Edit: foundkref_readwhich sounds like it fits the bill. Just testing to see if it works as I'm expecting.
Yes, looks likekref_readis the right way to go. ``` static inline unsigned int kref_read(const struct kref *kref) { return refcount_read(&kref->refcount); } ```
I want to build a counting table from 1 to 20 using inner for loop but instead of using multiplication, I want to use summation to build up my answer. I wrote this code and for only number 1, I can see the correct answer.From number 2, I see that it adds up from the 10th multiplication. I want to correct my logic error here in this code and any help is highly appreciated. ``` #include <stdio.h> int main() { int m , n=1; int i; m = 0; for(n = 1; n <= 20; n++){ for(i = 1; i <= 10; i++){ m = m + n; printf("%d * %d = %d\n", n, i, m); } } return 0; } ```
``` #include <stdio.h> int main(void) { int m, n, i; for (n = 1; n <= 20; n++) { // reset m before additions m = 0; for (i = 1; i <= 10; i++) { m += n; printf("%d * %d = %d\n", n, i, m); } } return (0); } ```