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 pri...
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 = (tE...
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 ...
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 l...
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) { /*...
``` 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 pri...
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 = (tE...
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 pri...
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 = (tE...
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: ...
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 ...
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(ad...
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, st...
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...
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...
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...
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_p...
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 expl...
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 ...
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 sin...
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; } ```...
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++) { ...
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 *__rest...
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 ...
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 alignm...
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 imple...
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 implementa...
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 ...
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 alignm...
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()) { pr...
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 : "); sca...
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 u...
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:...
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...
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...
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 ...
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", my...
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 c...
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 increm...
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, b...
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...
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 v...
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 ca...
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++ ){ ...
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 cons...
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...
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 ...
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; ...
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] = NU...
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[10...
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 point...
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...
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 cou...
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 or...
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[10...
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 point...
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...
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 cou...
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 or...
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 extens...
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 ...
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+...
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[...
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...
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; pr...
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 y...
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. ```...
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 progra...
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 ($?) { .\...
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 y...
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. ```...
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 progra...
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 ($?) { .\...
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 ...
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 ...
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() { ...
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() { ...
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; } ``` I...
``` 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 actuall...
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...
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); ...
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) ...
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() { ...
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() { ...
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 ...
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 =...
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...
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 ...
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 =...
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...
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 t...
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 elem...
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 statemen...
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 ...
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 -pth...
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) { stri...
``` 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...
``` 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 ac...
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 b...
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,a...
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 <str...
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"], 0x7ffc3...
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,a...
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 <str...
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"], 0x7ffc3...
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 signa...
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: foun...
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 er...
``` #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); } ```