question
stringlengths
25
894
answer
stringlengths
4
863
Suppose I allocate a piece of dynamic memory, and it was successful. Later on, there is a possibility that this piece of memory no longer belongs to the user. Is it possible to determine if the user still owns this piece of dynamic memory? i.e. ``` #include <stdio.h> #include <stdlib.h> int main(){ int* ptr = malloc(sizeof(int)); /* ... ptr may have been freed ... */ belongToUser(ptr); /* <- some sort of check? */ } ```
There is a (neither clean nor safe) possibility to check: Register a signal handler for SIGSEGVAccess the memoryReturn not mapped if the signal handler was run, mapped otherwise As mentioned, I'd never recommend to check, but to write C programs that remember (pointer = NULL).
i'm a new devopler in CUDA 8 and compiling my codes with nvcc how can i install conio.h into my compiler by the way i'm running my code on server at a company thanks
The short answer: you can't. CUDA is based on C, but is a different language and a different compiler. And conio.h is not even part of C standard. You ca however use printf from a Cuda kernel
This question already has answers here:C pointer to array/array of pointers disambiguation(12 answers)Closed6 years ago. What is the difference between these two in C. The first one is array of pointers. My main confusion is about the second declaration. What does it declare. Aren't the two the same ? ``` int *p []={&i,&j,&k}; int (*ar) []; ```
Just follow the"right-left" rule int *p []={&i,&j,&k};// reads: "p is an array of pointers to int" int (*ar) [];// "ar is a pointer to an array of ints"
The following program gives an output of1 1instead of1 2which is the output when I usestatic int count = 0instead of the separate initialisationcount = 0. ``` #include<stdio.h> int fun() { static int count; count = 0; count++; return count; } int main() { printf("%d ", fun()); printf("%d ", fun()); return 0; } ``` Does this mean that a separate initialisation overrides the static declaration which is supposed to preserve values between calls? I searched quite extensively but couldn't find any answer explicitly confirming my belief.
count = 0;is an explicit assignment of 0 tocount, which happenseverytime the function is called. Hence your output. Writingstatic int count;willinitialisecountto 0 due to it having static storage duration. Is that what you wanted? Finally,funis not thread safe due to a non-atomic type being used and incremented without mutual exclusion units.
Here is the code ``` struct stack { int item; struct stack *next=NULL; }; ``` I want to make the pointer initially point to null but this shows error error:expected ':' , ',' , ';' , '}' or 'attribute' before'=' token
The fragment posted does not define an object, it defines a type. In C you cannot specify the default value of a member in a type definition. You can specify the values of members in an initializer: ``` struct stack { int item; struct stack *next; }; struct stack my_stack = { 0, NULL }; ``` If you omit the last member in the initializer, it will be initialized to the zero of its type,NULLfor a pointer: ``` struct stack my_stack = { 0 }; // my_stack.next is NULL ```
"abc"string was stored to shared memory. The program has finished (quit) byreturn 0;but the string is still stored in memory. How long will it remain there?Will it remain there until system reboot?Can it be relied on that it will remain there? Relevant code: ``` int main() { int mem_id; key_t key; char * string; key = 01; int str_len; str_len = strlen("abc") + 1; mem_id = shmget(key, str_len, IPC_CREAT | 0666); string = shmat(mem_id, NULL, 0); strcpy ( string, "abc" ); return 0; } ```
The string will remain there until another process overwrites it or deletes the shared memory segment, or the system is rebooted. See alsoman ipcrmfor removing shared SysV resources from the command line.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago. here is very simple c program: ``` int main() { int i = 22; printf("%d %d %d",i,i++,i); return 0; } ``` The result is: ``` 23 22 23 ``` how exactly post increment is working here ?
You cannot test correctly in this context. The order of parameter evaluation for function parameters is undefined, hence you will have platform-dependent results. The way i++ works actually is by first returning the old value and later incrementing, but that is a bad test.
For a command line application I need to compare the input string to a command pattern. White spaces need to be ignored. This line should match input strings like " drop all " and " drop all": ``` int rc = sscanf( input, "drop all"); ``` But what does indicate a successful match here?
Use"%n"to record where the scanning stopped. Add white space in the format to wherever WS ininputneeds to be ignored. ``` int n = -1; sscanf( input, " drop all %n", &n); // v---- Did scanning reach the end of the format? // | v---- Was there additional text in `input`? if (n >= 0 && input[n] == '\0') Success(); ```
In this code: ``` #include <stdio.h> int fun (int *x, int i) { int r; printf("%d\n", *(x+i/2)); r = *x + i / 2 + *(x + i / 2); return r; } int main (void) { int x[] = {8, 7, 6, 5, 4, 3, 2, 1}; printf("%d", fun(x, 7)); return 0; } ``` I'm having trouble understanding, why is *(x+i/2) = 5?
*(x)would be the first element of the array, 8.*(x+i/2) == *(x+7/2) == *(x+3) == x[3] == 5 Notea) integer division (rounding down)b) pointer arithmetic,*(x+1)is looking at second array entry, not second byte
Here is the code ``` struct stack { int item; struct stack *next=NULL; }; ``` I want to make the pointer initially point to null but this shows error error:expected ':' , ',' , ';' , '}' or 'attribute' before'=' token
The fragment posted does not define an object, it defines a type. In C you cannot specify the default value of a member in a type definition. You can specify the values of members in an initializer: ``` struct stack { int item; struct stack *next; }; struct stack my_stack = { 0, NULL }; ``` If you omit the last member in the initializer, it will be initialized to the zero of its type,NULLfor a pointer: ``` struct stack my_stack = { 0 }; // my_stack.next is NULL ```
"abc"string was stored to shared memory. The program has finished (quit) byreturn 0;but the string is still stored in memory. How long will it remain there?Will it remain there until system reboot?Can it be relied on that it will remain there? Relevant code: ``` int main() { int mem_id; key_t key; char * string; key = 01; int str_len; str_len = strlen("abc") + 1; mem_id = shmget(key, str_len, IPC_CREAT | 0666); string = shmat(mem_id, NULL, 0); strcpy ( string, "abc" ); return 0; } ```
The string will remain there until another process overwrites it or deletes the shared memory segment, or the system is rebooted. See alsoman ipcrmfor removing shared SysV resources from the command line.
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago. here is very simple c program: ``` int main() { int i = 22; printf("%d %d %d",i,i++,i); return 0; } ``` The result is: ``` 23 22 23 ``` how exactly post increment is working here ?
You cannot test correctly in this context. The order of parameter evaluation for function parameters is undefined, hence you will have platform-dependent results. The way i++ works actually is by first returning the old value and later incrementing, but that is a bad test.
For a command line application I need to compare the input string to a command pattern. White spaces need to be ignored. This line should match input strings like " drop all " and " drop all": ``` int rc = sscanf( input, "drop all"); ``` But what does indicate a successful match here?
Use"%n"to record where the scanning stopped. Add white space in the format to wherever WS ininputneeds to be ignored. ``` int n = -1; sscanf( input, " drop all %n", &n); // v---- Did scanning reach the end of the format? // | v---- Was there additional text in `input`? if (n >= 0 && input[n] == '\0') Success(); ```
``` #include <stdio.h> #include <conio.h> void main() { int m = 20; int n = 30; int *x = (int *)m; int *y = (int *)n; printf("%d", y-x); //Output is 5 } ``` How is the output 5? One of the reason could be that x and y consider 20 and 30 as address and during pointer arithmetic the value could be (30-20)/(size of int) which is 10/2 = 5. My doubt is what is the difference between returning pointer and returning address ? Why the address of m was not stored in pointer variable x?
The behaviour of your program is undefined. Pointer arithmetic - including the difference between two pointers - is only valid within arrays (including one past the end of the arrray), or between the address of a scalar and one past that. The behaviour of your casts from an int to a pointer to an int is also undefined. If you do have a valid difference between two pointers, then use the format specifier %td to output it.
``` #include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ char array[2]; printf("Enter two of < or > or ="); scanf("%s",array); if ((2 array[0] 3)&&(4 array[1] 3)){ printf("It works\n"); } else printf("Yup! the code still works\n"); } ``` The above simplified code is meant to take input <> from the user and tries to use it to compare between two numbers but the compiler throws an error 'cause it is not accepting array[0] as >. please provide a solution to the problem.
You can't just use a char as an operator, but you can use an if else sequence based on the input to compare the values. Ex ``` if (array[0] = '>') some_variable = 2>3; else if (array[0] = '<') some_variable = 3>2; else if (array[0] = '=') some_variable = 3==2; ``` You could also use a switch statement if you prefer. You could then repeat a similar sequence for the second element in the array.
I need to #define a macros as a function. For example: ``` #define REGISTER 0x80000000 ... writel(addr, nic->regs + REGISTER); // arguments are address and register ``` I defined it like that: ``` #define WRITEL(addr, nic->reg + reg) ((writel(addr, nic->regs + (reg)))) ``` What's wrong here? Thanks
Macro arguments are a bit like normal function arguments. On the left side you just need a name that is used on the right ``` #define WRITEL(ADDR, REG) (writel(ADDR, nic->regs + (REG))) ```
I have the text file with 2000 lines and each line contains up to 256 characters. I need to detect EOF as I'm reading the file. Should the code process a line as it is read or should it read the lines into an array and then process the array one element at a time?
If the data don't change in your file, you should stock the data in an array. In the other case, you have to read your file each time you need to check a line.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed6 years ago.Improve this question I have the following problem: I have to build a DLL with some Header-Files from a supplier. There are some typedefs in those headerfiles which store WINAPI-Functionpointers. Example: ``` typedef struct { int(WINAPI *myFunc)(int, int); } ``` However, VS2015 always underlines the star ("*") saying it expected an ")". I cant change the functions stored in those pointers so I have to fix this. Anyone knows a solution for this?
Since the WINAPI-Macro is defined inWindows.h, I just forgot to include it. Result: Including the -Header seems to fix this problem.
``` int age, i; char name[10], address[10]; for( i=0; i<3; i++ ) { printf("Enter your name: "); gets(name); printf("Where do you live?"); gets(address); printf("What's your age? "); scanf("%d", &age); } ``` On the second iteration of the code, execution skips the "Enter your name: " part. Why?
There is a newline character at the end of entering the age. I would suggest you to usefgets()instead ofgets()and get rid of newline character after scanningage Consume the\ncharacter after reading age by placing a space after%d. ``` scanf("%d ",&age); fgets(name, sizeof(name), stdin); size_t n = strlen(name); if(n>0 && name[n-1] == '\n') { name[n-1] = '\0'; } ``` P.S:: There is a newline character at end offgets()so you need to get rid of it.
The code is suppose to print the initials of the users but the code has a bug instead it prints out the whole name with spaces between each letter. I know the bug lies in the for loop but im not sure how to debug this issue. Suggestions? ``` int main(void) { printf("Enter full name: "); string name = get_string(); { printf("%c", toupper(name[0])); } for(int i = 0, n = strlen(name); i < n; i++) { printf(" "); printf("%c", toupper(name[i + 1])); } } ```
I think that you mean to test to see if the next char is a space, and if it is, then print the char following the space: ``` if (name[i] == ' ') { printf("%c", toupper(name[i + 1])); } ``` Of course, before theforloop, you need to print the first initial since there won't be a space before it: ``` // print the first initial before the loop cout << static_cast<unsigned char>(toupper(name[0])); ```
In my simple code: ``` #include <sys/shm.h> #include <stdio.h> int main() { key_t key = ftok(".", 'b'); int shmid = shmget(key, 4, IPC_CREAT | 0444); if (shmid == -1) { perror("shmget"); return 1; } void* addr = shmat(shmid, NULL, 0); if (addr == (void*) -1) { perror("shmat"); return 1; } printf("success"); return 0; } ``` I already have read access, but I got "shmat: Permission denied". Do I have permission to write?
Fromman shmat: IfSHM_RDONLYis specified in shmflg, the segment is attached for reading and the process must have read permission for the segment. Otherwise the segment is attached for read and write and the process must have read and write permission for the segment. So you need to useSHM_RDONLYinstead of0when callingshmat().
Can you tell me what is the value of x in below code and explain the reasons? I thought x should be be 8, but the result show it is 2... ``` int x=3; x = 4? 2: 8; ```
It is returning output 2 because your condition is true as you are checking for 4 which is always true in second line of code. If you want result as 8: Then write code as below: ``` int x=3; x = x==4? 2: 8; ``` it will return 8 as condition is false because value of x is 3 and you are checking it against 4.
Lets say we have an array int a[4]; there was a neat trick using pointer arithmetics to find the last element. As far as i can recall it was using the address of 'a' and incrementing it so that it will go point immediately after the array and then going one position back. The thought behind the incrementing was that that there was an implicitsizeofbeing done. There was nowhere any explicitsizeof. Anyone have any idea how it was done? Thanks a bunch!
I can suggest the following solution ``` #include <stdio.h> int main( void ) { int a[4] = { 0, 1, 2, 3, }; int *p = (int *)(&a + 1) - 1; printf("*p = %d\n", *p); return 0; } ``` The program output is ``` *p = 3 ```
Here is the code: ``` #include <stdio.h> #include <stdint.h> int main() { uint8_t ui8 = 0xff; printf(" %x\n", ui8); printf(" %x\n", (uint8_t)24); printf(" %x\n", ui8 << (uint8_t)24); } ``` The output is : ``` ff 18 ff000000 ``` The question is: If I have twouint8_tvariables why the result is "promoted" to a higher rank. If it is not promoted, why do I get such a big number. I test it no MinGW win7-64bit platform
Botharguments of<<are converted tointprior to the evaluation,despitethe fact that you've attempted to force the issue with(uint8_t)24. This is necessarily true sinceuint8_tis narrower than aninton any platform. So the result,ff000000, you observe is consistent with anintbeing at least 32 bits wide on your platform.
I just find it in a .pod file but no more details, where the declaration in the c part?
In crypto/pem/pem.h : ``` /* * These macros make the PEM_read/PEM_write functions easier to maintain and * write. Now they are all implemented with either: IMPLEMENT_PEM_rw(...) or * IMPLEMENT_PEM_rw_cb(...) */ ... # define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \ type *PEM_read_bio_##name(BIO *bp, type **x, pem_password_cb *cb, void *u)\ { \ return PEM_ASN1_read_bio((d2i_of_void *)d2i_##asn1, str,bp,(void **)x,cb,u); \ } ``` And the RSA + PUBKEY part is in :crypto/pem/pem_all.c
Whenever I see aselectcall in C, I see it written as: ``` select(sock_fd + 1, &fdset, NULL, NULL, &tv) ``` or something similar. What is the meaning behind incrementing the file descriptor?
From thePOSIX specification ofselect: Thenfdsargument specifies the range of descriptors to be tested. The firstnfdsdescriptors shall be checked in each set; that is, the descriptors from zero throughnfds-1in the descriptor sets shall be examined. That is, you give thesizeof the set, where each descriptor is anindex. Descriptors sets are basically implemented as arrays, andsock_fd(in your case) is anindexinto that array, whilesock_fd + 1is thesizeof the array to check.
While going through my coursework, I came across a function that reads temperature from theTMP102 sensor(only required to measure positive temperatures).The function first reads the MSB and LSB using I2C. Since the temperature data is12-bit and left-justified, the function proceeds as follows: ``` temp = ( (MSB << 8) | LSB) >> 4 ``` I do not understand why this is done. Could someone please help me explain how the above line of code is related to the data being 12-bit and left-justified?
Letvbe a bit of the temperature value andpbe a padding bit on the right, then you have ``` MSB = vvvvvvvv LSB = vvvvpppp --- MSB << 8 = vvvvvvvv 00000000 (MSB << 8) | LSB = vvvvvvvv vvvvpppp ((MSB << 8) | LSB) >> 4 = 0000vvvv vvvvvvvv ``` In the last line, you see the correct representation as a 16bit value (with the upper 4 bits always0).
I am trying to understand the storage allocator program shown in Kernighan and Ritchie's book "The C Programming Language, 2nd edition". I think I understood most, but when I code the program inWindows 8.1 x86_64 with TDM GCC version 5.1.0. It outputs errorundefined reference to 'sbrk'. These are my includes: ``` #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> ``` I've searched quite a lot, but no other answers have helped me. It is supposed to be insideunistd.hbut it's not. Is it because, since it is a system call it cannot be found in Windows? What is wrong?
Yes,sbrkis a unix system call. It's not available on Windows. (Side note: Functions themselves aren't inside headers; headers generally only contain declarations. The actual functions are in some library (libc in this case).)
I'm having difficulties in understanding why this code results in3f000000. ``` float f = 5e-1; printf("%x", *(int*)&f); ```
This is undefined behavior: the standard does not guarantee pointers tointandfloatto have the same alignment, so(int*)&fcast is invalid (Q&A). In your case, the cast produced a value that is consistent with IEEE-754 representation of 0.5 (5e-1) below: ``` bin: 0011 1111 0000 0000 0000 0000 0000 0000 +--- ---- -=== ==== ==== ==== ==== ==== hex: 3 f 0 0 0 0 0 0 ``` where+is the sign bit,-are exponent bits, and=are mantissa bits. However, there is absolutely no guarantee that the same program is going to produce the same result when you run it on other systems, or even that the program is going to run to completion.
When seeing some piece of codes I saw this "declaration" - as far as I can understand this is a declaration - at/drivers/base/cpu.cin the kernel: ``` static CLASS_ATTR(probe, S_IWUSR, NULL, cpu_probe_store); ``` The file is written in C/C++ is cpu.c but with my limited knowledge of C/C++ I have no idea what the meaning of this "declaration" line. No need to explain about the actual meaning of parameters in this file, if possible just show me the role definition of this "declaration".
ClearlyCLASS_ATTRis a macro. These macros is well linked to its definition in the website you post. Just click the name, following the search result, especially in header files you'll find the definition. CLASS_ATTR __ATTR
I need to output the 32-bit value of an IP address (an example IP address: 208.40.244.65) in C. Don't know what this means, or how to do it?
Assuming IPv4, ``` const char* ip_addr_str = "208.40.244.65"; // In hex, D0.28.F4.41 uint32_t ip_addr_num; inet_aton(ip_addr_str, (struct in_addr*)&ip_addr_num); ``` The above copies the bytes exactly how they would be found in an IP packet, so the result varies by machine. You'll either get ``` 0xD028F441 // Big-endian machines ``` or ``` 0x41F428D0 // Little-endian machines ``` Follow up with the following to normalize to0xD028F441: ``` ip_addr_num = ntohl(ip_addr_num); ``` Note: I thinkinet_atonactually accepts domains as well as IP addresses.
Is it possible to programmatically find out count of processes which have opened object referenced by given file descriptor on linux? If yes, is there any difference if it is a file, a pipe or whatever?
Curiously, thefuserprogram and its output has been standardized by POSIX. You could call that usingpopenand parse its output. Unless the user is privileged, the list will be incomplete, and this approach is inherently prone to races. On Linux, you could read the contents of the/proc/*/fddirectories and check for referenced to the same file descriptor. (Same comment about privileges and races applies.) If you are interested in references to the same filedescriptionobject (which share not just the same file, but also the same file offset because they were created bydup/dup2orfork), you'll have to filter this further using thekcmpsystem call.
determine content-length and append '\0' ``` fseek(fp, 0, SEEK_END); long fp_len; fp_len = ftell(fp); fseek(fp, 0, SEEK_SET); char *text = malloc(sizeof(*text) * fp_len + 1); size_t len = fread(text, fp_len, 1, fp); text[fp_len] = '\0'; ``` fp_len prints : 400, while len prints : 1 ``` printf("%d", fp_len); printf("%d", len); ``` my understanding is this is wrong: ``` text[fp_len] = '\0'; ``` and this is correct : ``` text[len] = '\0'; ``` but if "len" is printing 1.. wouldn't '\0' be added to the 2nd spot in the array ?
Callfread(text, fp_len, 1, fp)asks to read one element of sizefp_lenso after succesful execution result is1(number of elements read) or it can be0if reading fails. If you want to count number of bytes (character) read from file, you can change places of arguments, like ``` fread(text, 1, fp_len, fp) ``` For more information refer toreferences
I'm trying to create a program that will show elements from the int array. But I keep getting the warning. This is probably going to get really downvoted but I don't know where I made a mistake. Here is the code: ``` #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <math.h> #include <time.h> int main() { int counter; int elements[3] = { 22, 52, 95 }; for (counter = 1; counter <= 3; counter++) { printf("Element %d: %d\n", counter, elements); } return 0; } ```
The problem here is that you are trying to print anintbutelementsis not anint; it is an array! You want to use[]to retrieve oneintat a timeArray inCare0-indexed. So it means that you should access them starting from the0th element. Check the following: ``` for(counter = 0; counter < 3; counter++) printf("Element %d: %d\n", counter, elements[counter]); ```
Main function should have a function call like adddiff(&p,&q) ... Function definition be like void adddiff(*a,*b) it should perform both addition and subtraction ,it should not return values and should not use print statement in adddiff method.
Both arguments are passed by reference, so you can use them to "return" the results to the main function. Remember to save their values locally before overriding them, though! ``` void adddiff(int* a, int* b) { int orig_a = *a; int orig_b = *b; *a = orig_a + orig_b; *b = orig_a - orig_b; } ```
``` #include<stdio.h> #include<stdlib.h> int main(){ struct nodeout { int out; struct nodein{int in; }; }; struct nodeout* p; p=(struct nodeout*)malloc(sizeof(struct nodeout)); p->out=10; printf("%d",p->out); } ``` ..Here is my code..How can I initialize the variable 'in' which is inside the structure nodein?
You did definestruct nodeinbut did not define thenodeinmember forstruct nodeout. Do as following: ``` #include<stdio.h> #include<stdlib.h> int main(){ struct nodeout { int out; struct nodein {int in; } node_in; }; struct nodeout* p; p = (struct nodeout*)malloc(sizeof(struct nodeout)); p->out = 10; p->node_in.in = 5 printf("%d %d”, p->out, p->node_in.in); } ```
Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state. Is this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.
Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.
I am getting an error in my compiler: ``` Warning: implicit declaration of function 'system' ``` I added: ``` system("cls"); ``` To be able to clear the screen, and now I get the error. I am using this code to test: ``` #include <stdio.h> int nothing; //random name int main() { printf("this is a msg"); scanf("%d",&nothing); system("cls"); printf("hello"); getchar(); return 0; } ``` This is just a test code, so it's very sloppy. I am new to coding so any help would be appreciated.
For C++:#include <cstdlib>, for C:#include <stdlib.h>. Or, you can do as follows: ``` #ifdef __cplusplus__ #include <cstdlib> #else #include <stdlib.h> #endif if (system("CLS")) system("clear"); ``` You can also see a full article w.r.tClear the screen.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed6 years ago.Improve this question Can anyone please provide me the code in c programming language of problem in which we enter "ABCD" as an input in run time and we get "ZYXW" as output and I tried to solve this using ASCII Code
Hope this will help you . Read about ascii code of character . Also you have to gain knowledge of pointer and string . ``` #include<stdio.h> int main(){ char ch[20]; scanf("%s",ch); for(const char *s = ch; *s; ++s) putchar('Z'-(*s-'A')); return 0; } ```
As you can see in the photo in the link, the answer comes up correctly, but the equation is wrong. please keep in mind that i am new to coding, and it might be a simple mistake https://pastebin.com/tVuuiNic( LINK TO THE CODE) ``` if ((operation_type == 'A') || (operation_type == 'a')) { printf("\n\nType the numbers you wish to have added.\n\n"); scanf("%d %d",&add_a, &add_b ); printf("\n\n%d + %d = %d", &add_a, &add_b, func_add(add_a,add_b) ); } ```
You are printing the address ofadd_aandadd_b(by using the&) just do this: ``` printf("\n\n%d + %d = %d", add_a, add_b, func_add(add_a,add_b) ); ```
I'm trying to create a program that will show elements from the int array. But I keep getting the warning. This is probably going to get really downvoted but I don't know where I made a mistake. Here is the code: ``` #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <math.h> #include <time.h> int main() { int counter; int elements[3] = { 22, 52, 95 }; for (counter = 1; counter <= 3; counter++) { printf("Element %d: %d\n", counter, elements); } return 0; } ```
The problem here is that you are trying to print anintbutelementsis not anint; it is an array! You want to use[]to retrieve oneintat a timeArray inCare0-indexed. So it means that you should access them starting from the0th element. Check the following: ``` for(counter = 0; counter < 3; counter++) printf("Element %d: %d\n", counter, elements[counter]); ```
Main function should have a function call like adddiff(&p,&q) ... Function definition be like void adddiff(*a,*b) it should perform both addition and subtraction ,it should not return values and should not use print statement in adddiff method.
Both arguments are passed by reference, so you can use them to "return" the results to the main function. Remember to save their values locally before overriding them, though! ``` void adddiff(int* a, int* b) { int orig_a = *a; int orig_b = *b; *a = orig_a + orig_b; *b = orig_a - orig_b; } ```
``` #include<stdio.h> #include<stdlib.h> int main(){ struct nodeout { int out; struct nodein{int in; }; }; struct nodeout* p; p=(struct nodeout*)malloc(sizeof(struct nodeout)); p->out=10; printf("%d",p->out); } ``` ..Here is my code..How can I initialize the variable 'in' which is inside the structure nodein?
You did definestruct nodeinbut did not define thenodeinmember forstruct nodeout. Do as following: ``` #include<stdio.h> #include<stdlib.h> int main(){ struct nodeout { int out; struct nodein {int in; } node_in; }; struct nodeout* p; p = (struct nodeout*)malloc(sizeof(struct nodeout)); p->out = 10; p->node_in.in = 5 printf("%d %d”, p->out, p->node_in.in); } ```
Thedocumentationsays thatMK_RBUTTON, and notMK_SHIFT, indicates the Shift key state. Is this correct or is this a typo? It differs fromthe behavior inWM_LBUTTONUP.
Yeah, it's a typo. Spy++ showsMK_SHIFTand notMK_RBUTTON.
I am getting an error in my compiler: ``` Warning: implicit declaration of function 'system' ``` I added: ``` system("cls"); ``` To be able to clear the screen, and now I get the error. I am using this code to test: ``` #include <stdio.h> int nothing; //random name int main() { printf("this is a msg"); scanf("%d",&nothing); system("cls"); printf("hello"); getchar(); return 0; } ``` This is just a test code, so it's very sloppy. I am new to coding so any help would be appreciated.
For C++:#include <cstdlib>, for C:#include <stdlib.h>. Or, you can do as follows: ``` #ifdef __cplusplus__ #include <cstdlib> #else #include <stdlib.h> #endif if (system("CLS")) system("clear"); ``` You can also see a full article w.r.tClear the screen.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed6 years ago.Improve this question Can anyone please provide me the code in c programming language of problem in which we enter "ABCD" as an input in run time and we get "ZYXW" as output and I tried to solve this using ASCII Code
Hope this will help you . Read about ascii code of character . Also you have to gain knowledge of pointer and string . ``` #include<stdio.h> int main(){ char ch[20]; scanf("%s",ch); for(const char *s = ch; *s; ++s) putchar('Z'-(*s-'A')); return 0; } ```
As you can see in the photo in the link, the answer comes up correctly, but the equation is wrong. please keep in mind that i am new to coding, and it might be a simple mistake https://pastebin.com/tVuuiNic( LINK TO THE CODE) ``` if ((operation_type == 'A') || (operation_type == 'a')) { printf("\n\nType the numbers you wish to have added.\n\n"); scanf("%d %d",&add_a, &add_b ); printf("\n\n%d + %d = %d", &add_a, &add_b, func_add(add_a,add_b) ); } ```
You are printing the address ofadd_aandadd_b(by using the&) just do this: ``` printf("\n\n%d + %d = %d", add_a, add_b, func_add(add_a,add_b) ); ```
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.Closed6 years ago.Improve this question What will happen if I use comparison operators to compare strings instead of strcmp in C? Will it compare its ASCII value and return results?
It will compare the addresses of the two pointers. so: ``` char* a = "hello"; char* b = "test"; char* c = "hello"; char* d = a; a == d; // true a == b; // false a == c; // true or false, depending on the compiler's behavior. ``` The third example will be true if the compiler decides to recycle the actual string data for "hello", but it has no obligation to do so.
This question already has answers here:How to fgets() a specific line from a file in C?(5 answers)Closed6 years ago. instead of using while loops. or instead of doing the following to get the 3rd line from a file. is there a better way ? perhaps with fseek ? if so how. ``` FILE *fp; fp = fopen(path, "r"); char line_one[100]; char line_two[100]; char line_three[100]; fgets(line_one, sizeof line_one, fp); fgets(line_two, sizeof line_two, fp); fgets(line_three, sizeof line_three, fp); fclose(fp); line_three[strcspn(line_three, "\n")] = 0; ```
try ``` fseek(fb,200,SEEK_SET); fread(buffer,sizeof(char),100,fb) ``` where buffer an array to read in
I am seeing this example where I have acrc32.cfile which contains: ``` inline int32_t crc32_compute(int32_t *buffer, size_t size) { ... } ``` In the header file I find: ``` extern inline int32_t crc32_compute(int32_t *buffer, size_t size); ``` To me theinlinekeyword has no effect because the function should be declared on the header file not on the C file. Is it that correct?
You are correct, whoever wrote this code put things the wrong way around. The header file should containinlinefunction, along with its full definition, while the.cfile should containextern inlinedeclaration, without a definition: Header: ``` inline int32_t crc32_compute(int32_t *buffer, size_t size) { ... } ``` C file: ``` extern inline int32_t crc32_compute(int32_t *buffer, size_t size); ``` The header will allow the function code to be inlined; the.cfile will instruct the compiler to emit an externally visible symbol for it.
``` char* p = init(); p = foo(p); /* this one */ ``` the functionfooprototype: ``` char* foo(char* p); ``` Is it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?
Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.
``` #include<stdio.h> #include<conio.h> void main() { int a[5][5]; int (*p)[5]; clrscr(); p=a; a[0][0]=5; printf("%d\n",p[0][0]); //This prints 5. getch(); } ``` My question is if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?
ais a 2D array. ``` int a[5][5]; ``` pis apointer to a 2D array ``` int (*p)[5][5] = &a; ``` if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it? ``` int (**dp)[5][5] = &p; printf("Value of dp %p\n", (void*) dp); printf("Value of *dp %p and p %p\n", (void*) *dp, (void*) p); printf("Value of **dp %p and a %p\n", (void*) **dp, (void*) a); printf("Value of int array element %d\n", (**dp)[0][0]); ```
``` char* p = init(); p = foo(p); /* this one */ ``` the functionfooprototype: ``` char* foo(char* p); ``` Is it permissible to callfoothat way, or does it fall in theUndefined Behaviorcategory?
Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.
``` #include<stdio.h> #include<conio.h> void main() { int a[5][5]; int (*p)[5]; clrscr(); p=a; a[0][0]=5; printf("%d\n",p[0][0]); //This prints 5. getch(); } ``` My question is if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?
ais a 2D array. ``` int a[5][5]; ``` pis apointer to a 2D array ``` int (*p)[5][5] = &a; ``` if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it? ``` int (**dp)[5][5] = &p; printf("Value of dp %p\n", (void*) dp); printf("Value of *dp %p and p %p\n", (void*) *dp, (void*) p); printf("Value of **dp %p and a %p\n", (void*) **dp, (void*) a); printf("Value of int array element %d\n", (**dp)[0][0]); ```
Relatively new to C, don't see what I'm doing wrong here, this piece of code crashes after assigning the 3rd string: ``` QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be*)); sentence->questionword->word = words[0]; sentence->verb->word = words[1]; sentence->subject->word = words[2]; //crashes here ? ``` words is an char *[ ], and here's the structure of "sentence": ``` typedef struct QW_Be{ Word *questionword; Word *verb; Word *subject; Word *rest[]; } QW_Be; ``` and here's the structure of 'Word': ``` typedef struct Word{ char *word; word_type type; char *context; } Word; ``` If you need any more info, just ask !
You should allocate the size of the struct and not the size of a pointer to the struct: ``` QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be)); ```
How to detect if cable is unplugged on W5100 Ethernet controller?. IndatasheetI can't find register for cable detection. But chip provides LAN status LED.
W5100does not support reading register to get status if cable is plugged or not (network available or not). You can only check by doingfake connectionand wait for either any response or timeout. Instead, you should useW5200which has this feature.
I have N statically allocated structures. ``` struct exemple{ ... } struct exemple array[N]; struct exemple *test_ptr = 0x3; /* random address */ ``` Can I check if test_prt points to a valid address? i.e. it points to one "struct example" allocated.
You can't. You have toknow. It's not a problem if you manage your pointers correctly. A good habit is to always set pointers to0/NULLas soon as you destroy the object they point to. Then you can just test withif (ptr)orif (!ptr)(or, more verbose:if (ptr == NULL)/if (ptr != NULL)). Note that your last assignment ``` struct exemple *test_ptr = 0x3; /* random address */ ``` isinvalid. you can't assign an integer to a pointer. but you cancastit to the pointer type; ``` struct exemple *test_ptr = (struct exemple *)0x3; /* random address */ ``` The result will depend on your implementation / system.
This question already has answers here:Determine size of dynamically allocated memory in C(15 answers)Closed6 years ago. if ``` fp_len = ftell(fp); ``` prints470 shouldn't this be printing "471" ? ( it prints8. probably first line only ) ``` char *text = malloc(sizeof(*text) * fp_len + 1); int text_len; text_len = sizeof(text); printf("text-len: %d --- ",text_len); ``` full: ``` FILE *fp; fp = fopen(path, "r"); fseek(fp, 0, SEEK_END); int fp_len; fp_len = ftell(fp); printf("%d---", fp_len); fseek(fp, 0, SEEK_SET); char *text = malloc(sizeof(*text) * fp_len + 1); int text_len; text_len = sizeof(text); printf("text-len: %d --- ",text_len); fread(text, fp_len, 1, fp); printf("%s",text); free(text); ```
sizeofgives the size of the type, not a string length. In case ofchar *text, the type is a pointer value, and the size of a pointer value on a 64 bit machine is probably 8.
error: invalid conversion from 'int' to 'int*'int *q = 8; Works fine.*q = 6; Why can't I directly assign an int to an int pointer like this:int *q = 6; and I can assign it safely in the next line?
Because they're different things at all. The 1st one is definition of variable with initializer expression, i.e aninitialization(of the pointer itself): ``` int * q = 8; ~~~~~ ~ ~~~ type is int*; name of variable is q; initialized with 8 ``` The 2nd one is assignment (of the object pointed by the pointer): ``` *q = 6; ~~ ~~~ dereference on q via operator*; assign the resulting lvalue pointed by q to 6 ``` And,int *p = 6;means define a variable namedpwith typeint*and initialize it with6, which fails because6can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'").
I only recently started programming. I have a shell script which contains a c-program. At the end of the script, the c-program is ran using the commands ``` gcc stadist.c -lm a.out < XXXXX | sort -n -k3 > YYYYY rm a.out rm stadist.c rm XXXXX ``` Running this script gives a.out: not found. The file YYYYY is created but it is empty. How can i solve this problem. I am on Linux ubuntu 16.04 LTS.
The shell cannot finda.outbecause it isn't looking in the current directory. That is best practice. (ie, donotadd.to PATH). Just do: ``` gcc stadist.c -lm && ./a.out < XXXXX | sort -n -k3 > YYYYY rm a.out rm stadist.c rm XXXXX ``` Note that I added&&after the invocation ofgccso that the script does not attempt to runa.outif the compilation fails. You'll probably want to add more robust error checking.
The following piece of code working fine: ``` #include <stdio.h> extern int foo; // Without constant int foo = 42; int main() { printf("%d\n",foo); return 0; } ``` But, the following piece of code give an error: ``` #include <stdio.h> const extern int foo; // With constant int foo = 42; int main() { printf("%d\n",foo); return 0; } ``` So, why doesconst externgive an error?
Standard says:C11-§6.7/4 All declarations in the same scope that refer to the same object or function shall specify compatible types const intandintare not compatible for the same objectfooin the same scope.
I am writing a C program to blink LED for Raspberry Pi. Its like (i) Blink LED (2) Stop blinking it. Now while the LED is blinking, if I press 2 it should stop blinking. How to do it ? If I includescanfinside the code will stop blinking. ``` while(1) { printf("Enter a command \n 1.Blink Led\n 2. Stop blinking\n"); scanf("%d",&choice); if(choice==1) for (;;) { digitalWrite (LED, HIGH) ; // On delay (500) ; // mS digitalWrite (LED, LOW) ; // Off delay (500) ; // If i press 2 the led should stop blinking } else if(choice==2){ digitalWrite (LED, LOW) ; } ```
if you don't want to interrupt theBlinkingyou should try to run the blinking in aparallel processusingpthread_t. i really want to give you the code but i'm not on my PC at the moment.
``` a = 4 b = 5 c = 7 if (a >= 4){ text1 = “a is high”; } if (b >= 8){ text2 = “b is high”; } if (c >= 6){ text3 = “c is high”; } ``` In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that onlyais high, or whatever the case may be. How would I go about doing this?
Use a single variable and keep on appending as you get the required information. ``` string text1; if (a >= 4) text1.append("a is high"); if (b >= 8) { if(text1.length()!=0) text1.append(" and "); text1.append("b is high"); } if (c <= 6) { if(text1.length()!=0) text1.append(" and "); text1.append("c is high"); } ```
This question already has answers here:Variable definition inside switch statement(5 answers)Closed5 years ago. ``` #include <stdio.h> int main(void) { int a = 1; switch(a) { int i = 2; case 1: printf("%d",i); break; default: printf("Hello\n"); } } ``` The following code sample is giving 36 as the output. How is this possible? I understand that the compiler will transfer the control to case 1 directly, without evaluatingi. But, why am I getting the output as 36? PS: I am using GCC.
In C++ this code is ill-formed because you cannot jump into the scope of a variable. In C the code is undefined behaviour:int i;inside the switch block exists, however by jumping tocase 1:you bypassed the part where the value2would have been assigned toi. So in fact you are attempting to print an uninitialized variable.
I've been working on some code that basically just tries to write a struct to a binary file in the form of a list, which isn't a problem, but I also need to write a macro at the end of every structure, the which is a char (I called it END_CHAR). What I use trying to do was: ``` #define END_CHAR 'F' /*Some irrelevant code here*/ fwrite(&END_CHAR,sizeof(char),1,file_output); ``` I understand that this doesn't work because I'm asking the memory address of a char that isn't stored in any variable. So, what is the proper way to do what I want to do?
In C,'F'is just a way of writing the number 70 (assuming ASCII), so it's just a number, and you can't take the address of a number, only a variable.#definedoesn't change that. So make a variable: ``` char endchar = 'F'; fwrite(&endchar, ... ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question For instance if I call ``` if (!fork()) ``` does this create a new process like calling ``` if (fork()) ``` or does it not?
It is the same,forkis evaluated before check is made. if (!fork())is the same asif (fork())for function itself but not the same forifstatement check.
I am working with little endian processor PIC 32 and am looking at a variable that is of type BOOL. One variable is initialized to TRUE and the other as false. ``` static BOOL A = TRUE; BOOL static B = FALSE; ``` In Memory when I look in memory for variable A, it shows It looks like the processor just assigns a 32 bit number for true and false and not 8 bits so that means its processor dependent. For an array of 6 elements of type BOOL, all set to TRUE. How would it be read? Is it going to show up as 6 elements of what is shown in the picture above?
BOOLis not a standard type. Depending on how it is defined in your environment, probably via atypedefin a header file, it may be any integer type, includingunsigned charwhich would use 1 byte orintwhich may use 4 bytes on your system and other sizes for other architectures.
I am trying to solve this question: Write a C program that reads in characters from the keyboard until the return key is entered and echoes the entered text on the screen. This is what I have so far, I am not sure what variable I can store the users input in so that I can print it back (assuming that is what they mean by echo): ``` #include<stdio.h> #include<string> int main () { char sentence; printf("Please enter anything you want: "); scanf("%c",&sentence); printf("%c",sentence); return 0; } ```
It seems that all you need is the following ``` #include <stdio.h> int main(void) { printf( "Please enter anything you want: " ); int c; while ( ( c = getchar() ) != EOF && c != '\n' ) { putchar( c ); } putchar( '\n' ); return 0; } ``` That is you need to use a loop that will iterate until the Enter key is pressed.
I am getting the following compilation error: prog.c:13:5: error: called object is not a function or function pointer a=250(n-1)+192; ``` #include <stdio.h> int main(){ long long n,a; int t; scanf("%d",&t); while(t--){ scanf("%lld",&n); a=250(n-1)+192; printf("%lld\n",a); } } ```
In C, you always have to write a*character for multiplication, as this: ``` a=250*(n-1)+192; ```
I only recently started programming. I have a shell script which contains a c-program. At the end of the script, the c-program is ran using the commands ``` gcc stadist.c -lm a.out < XXXXX | sort -n -k3 > YYYYY rm a.out rm stadist.c rm XXXXX ``` Running this script gives a.out: not found. The file YYYYY is created but it is empty. How can i solve this problem. I am on Linux ubuntu 16.04 LTS.
The shell cannot finda.outbecause it isn't looking in the current directory. That is best practice. (ie, donotadd.to PATH). Just do: ``` gcc stadist.c -lm && ./a.out < XXXXX | sort -n -k3 > YYYYY rm a.out rm stadist.c rm XXXXX ``` Note that I added&&after the invocation ofgccso that the script does not attempt to runa.outif the compilation fails. You'll probably want to add more robust error checking.
The following piece of code working fine: ``` #include <stdio.h> extern int foo; // Without constant int foo = 42; int main() { printf("%d\n",foo); return 0; } ``` But, the following piece of code give an error: ``` #include <stdio.h> const extern int foo; // With constant int foo = 42; int main() { printf("%d\n",foo); return 0; } ``` So, why doesconst externgive an error?
Standard says:C11-§6.7/4 All declarations in the same scope that refer to the same object or function shall specify compatible types const intandintare not compatible for the same objectfooin the same scope.
I am writing a C program to blink LED for Raspberry Pi. Its like (i) Blink LED (2) Stop blinking it. Now while the LED is blinking, if I press 2 it should stop blinking. How to do it ? If I includescanfinside the code will stop blinking. ``` while(1) { printf("Enter a command \n 1.Blink Led\n 2. Stop blinking\n"); scanf("%d",&choice); if(choice==1) for (;;) { digitalWrite (LED, HIGH) ; // On delay (500) ; // mS digitalWrite (LED, LOW) ; // Off delay (500) ; // If i press 2 the led should stop blinking } else if(choice==2){ digitalWrite (LED, LOW) ; } ```
if you don't want to interrupt theBlinkingyou should try to run the blinking in aparallel processusingpthread_t. i really want to give you the code but i'm not on my PC at the moment.
``` a = 4 b = 5 c = 7 if (a >= 4){ text1 = “a is high”; } if (b >= 8){ text2 = “b is high”; } if (c >= 6){ text3 = “c is high”; } ``` In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that onlyais high, or whatever the case may be. How would I go about doing this?
Use a single variable and keep on appending as you get the required information. ``` string text1; if (a >= 4) text1.append("a is high"); if (b >= 8) { if(text1.length()!=0) text1.append(" and "); text1.append("b is high"); } if (c <= 6) { if(text1.length()!=0) text1.append(" and "); text1.append("c is high"); } ```
This question already has answers here:Variable definition inside switch statement(5 answers)Closed5 years ago. ``` #include <stdio.h> int main(void) { int a = 1; switch(a) { int i = 2; case 1: printf("%d",i); break; default: printf("Hello\n"); } } ``` The following code sample is giving 36 as the output. How is this possible? I understand that the compiler will transfer the control to case 1 directly, without evaluatingi. But, why am I getting the output as 36? PS: I am using GCC.
In C++ this code is ill-formed because you cannot jump into the scope of a variable. In C the code is undefined behaviour:int i;inside the switch block exists, however by jumping tocase 1:you bypassed the part where the value2would have been assigned toi. So in fact you are attempting to print an uninitialized variable.
I've been working on some code that basically just tries to write a struct to a binary file in the form of a list, which isn't a problem, but I also need to write a macro at the end of every structure, the which is a char (I called it END_CHAR). What I use trying to do was: ``` #define END_CHAR 'F' /*Some irrelevant code here*/ fwrite(&END_CHAR,sizeof(char),1,file_output); ``` I understand that this doesn't work because I'm asking the memory address of a char that isn't stored in any variable. So, what is the proper way to do what I want to do?
In C,'F'is just a way of writing the number 70 (assuming ASCII), so it's just a number, and you can't take the address of a number, only a variable.#definedoesn't change that. So make a variable: ``` char endchar = 'F'; fwrite(&endchar, ... ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question For instance if I call ``` if (!fork()) ``` does this create a new process like calling ``` if (fork()) ``` or does it not?
It is the same,forkis evaluated before check is made. if (!fork())is the same asif (fork())for function itself but not the same forifstatement check.
I am working with little endian processor PIC 32 and am looking at a variable that is of type BOOL. One variable is initialized to TRUE and the other as false. ``` static BOOL A = TRUE; BOOL static B = FALSE; ``` In Memory when I look in memory for variable A, it shows It looks like the processor just assigns a 32 bit number for true and false and not 8 bits so that means its processor dependent. For an array of 6 elements of type BOOL, all set to TRUE. How would it be read? Is it going to show up as 6 elements of what is shown in the picture above?
BOOLis not a standard type. Depending on how it is defined in your environment, probably via atypedefin a header file, it may be any integer type, includingunsigned charwhich would use 1 byte orintwhich may use 4 bytes on your system and other sizes for other architectures.
I am trying to solve this question: Write a C program that reads in characters from the keyboard until the return key is entered and echoes the entered text on the screen. This is what I have so far, I am not sure what variable I can store the users input in so that I can print it back (assuming that is what they mean by echo): ``` #include<stdio.h> #include<string> int main () { char sentence; printf("Please enter anything you want: "); scanf("%c",&sentence); printf("%c",sentence); return 0; } ```
It seems that all you need is the following ``` #include <stdio.h> int main(void) { printf( "Please enter anything you want: " ); int c; while ( ( c = getchar() ) != EOF && c != '\n' ) { putchar( c ); } putchar( '\n' ); return 0; } ``` That is you need to use a loop that will iterate until the Enter key is pressed.
I am getting the following compilation error: prog.c:13:5: error: called object is not a function or function pointer a=250(n-1)+192; ``` #include <stdio.h> int main(){ long long n,a; int t; scanf("%d",&t); while(t--){ scanf("%lld",&n); a=250(n-1)+192; printf("%lld\n",a); } } ```
In C, you always have to write a*character for multiplication, as this: ``` a=250*(n-1)+192; ```
My teacher told me that the intermediate code is generic for all systems but a component of the compiler then make it different according the system/environment the code is run on. Can someone please explain it.
Normally a compiler is divided into two parts: A frontend that does the parsing, and which generates intermediate code. Then a backend which takes the intermediate code and generate the assembly or machine code. The frontend can be generic, but the backend is built for a specifictarget. So the compiler doesn't have to "identify" the host, only know the target. Note that host and target may be different systems, which is used forcross compilation.
Hi im working on a simple bash coding i don't know how to accomplish this and this might be easy for you guys please help. I have a simple program on file.sh ``` #!/bin/bash ./program ``` This ./program is a compiled version of C program which i complied using GCC im trying to use at in bash script to execute this program for few seconds and then terminate that after x interval time and restart again. I hope you got my point? Example: Run file.sh for 10 sec and I'll display the result from ./program C program and then after 10 sec it will restart again.
The answer is, if I understand correctly, a combination ofsleepandtimout: ``` while :; do timout 10s ./program # display some results sleep 10 done ```
When I runmake, I get a file with no file type. Is there a way to create a.exefile that I can just click on in Windows to run? I installed in my home directory: ``` sudo apt-get install mingw-w64 ``` but when I run from ~/workspace/pset2/vigenere: ``` i686-w64-mingw32-gcc -o vigenere.exe vigenere.c ``` I get: ``` vigenere.c:1:18: fatal error: cs50.h: No such file or directory #include <cs50.h> ``` Using clang: ``` clang -ggdb3 -O0 -std=c99 -Wall -Werror $1.c -lcs50 -lm -o $1 ``` how do I find the location of-lcs50and add it to my path?
There is an error that will not produce an executable. The file#include <cs50.h>which you have included is not in the system include directories. You probably meant#include "cs50.h", which will search the current directory. When you have fixed all the errors, just type./vigenere.exe. The.exeis typically not included in UNIX.
Sayt = 8.376600; If I calculatetvby: ``` tv->tv_sec = (long) floor (time); tv->tv_usec = (long) ((time - tv->tv_sec) * 1000000); ``` Thentv->tv_sec == 8andtv->tv_usec == 376599. printf("%f %ld.%06ld\n", time, tv->tv_sec, tv->tv_usec);prints8.376600 8.376599. Is there any simple way I can make the two outputs identical ?
In your code, you round the value down whereasprintfrounds it to the nearest microsecond. Here is an alternative version: ``` #include <math.h> #include <time.h> void set_timespec(struct timespec *tv, double time) { long long usec = round(time * 1000000); tv->tv_sec = usec / 1000000; tv->tv_usec = usec % 1000000; } ```
The textbook i'm reading explains that pointers are variables which hold the starting address of another variable, and that they are defined with a type of data to point to. Why can you assign a pointer to be the address of a variable then? or rather not be an address if omitting the "&" should it not always hold the address if that's how pointers are defined?
ptris the actual pointer, while*ptris whatever it is pointing at, so*ptr=&vardoes not really make any sense, unless it's a pointer to a pointer. It's eitherptr=&varor*ptr=var If you really want to assign a variable to a pointer, it is possible with casting. This compiles, but I cannot see any good reason to do something like this at all: ``` #include <stdio.h> main() { int var=4; int *ptr; ptr = (int *)var; printf("%d\n", *ptr); } ``` The behavior is undefined. When I ran it, it segfaulted.
When I runmake, I get a file with no file type. Is there a way to create a.exefile that I can just click on in Windows to run? I installed in my home directory: ``` sudo apt-get install mingw-w64 ``` but when I run from ~/workspace/pset2/vigenere: ``` i686-w64-mingw32-gcc -o vigenere.exe vigenere.c ``` I get: ``` vigenere.c:1:18: fatal error: cs50.h: No such file or directory #include <cs50.h> ``` Using clang: ``` clang -ggdb3 -O0 -std=c99 -Wall -Werror $1.c -lcs50 -lm -o $1 ``` how do I find the location of-lcs50and add it to my path?
There is an error that will not produce an executable. The file#include <cs50.h>which you have included is not in the system include directories. You probably meant#include "cs50.h", which will search the current directory. When you have fixed all the errors, just type./vigenere.exe. The.exeis typically not included in UNIX.
Sayt = 8.376600; If I calculatetvby: ``` tv->tv_sec = (long) floor (time); tv->tv_usec = (long) ((time - tv->tv_sec) * 1000000); ``` Thentv->tv_sec == 8andtv->tv_usec == 376599. printf("%f %ld.%06ld\n", time, tv->tv_sec, tv->tv_usec);prints8.376600 8.376599. Is there any simple way I can make the two outputs identical ?
In your code, you round the value down whereasprintfrounds it to the nearest microsecond. Here is an alternative version: ``` #include <math.h> #include <time.h> void set_timespec(struct timespec *tv, double time) { long long usec = round(time * 1000000); tv->tv_sec = usec / 1000000; tv->tv_usec = usec % 1000000; } ```
The textbook i'm reading explains that pointers are variables which hold the starting address of another variable, and that they are defined with a type of data to point to. Why can you assign a pointer to be the address of a variable then? or rather not be an address if omitting the "&" should it not always hold the address if that's how pointers are defined?
ptris the actual pointer, while*ptris whatever it is pointing at, so*ptr=&vardoes not really make any sense, unless it's a pointer to a pointer. It's eitherptr=&varor*ptr=var If you really want to assign a variable to a pointer, it is possible with casting. This compiles, but I cannot see any good reason to do something like this at all: ``` #include <stdio.h> main() { int var=4; int *ptr; ptr = (int *)var; printf("%d\n", *ptr); } ``` The behavior is undefined. When I ran it, it segfaulted.
In Allegro, I can set the Window to be resizeable by running ``` al_set_new_display_flags(ALLEGRO_RESIZABLE); ``` before ``` display = al_create_display(800, 600); ``` however, if I resize the window, how will I know how big the window is that I resize?
useal_get_window_constraints(ALLEGRO_DISPLAY *display, int *min_w, int *min_h, int *max_w, int *max_h). Source
This question already has answers here:Extracting bytes in C(3 answers)Closed6 years ago. I have a hexadecimal value 0x40BF00FF and i want to get this value 0xFF (last two number) from it and other numbers are ignore. how can we write code in C language
Solution Use bit masking with 0x000000FF: ``` int result = 0x000000FF & 0x40BF00FF; ``` full code example ``` int input = 0x40BF00FF; //input example int output = 0x000000FF & input; printf("%04x", output); //prints result ``` Result ``` 00ff ```
``` #include <stdio.h> //Compiler version gcc 6.3.0 void print(int a[5],int n){ n--; if(a[n]%2==0) print(a,n); printf("%d",a[n]); } int main(void){ int a[] = {1,2,3,4,5}; print(a,5); return 0; } ``` How would you print only even numbers in that array ..passing the last element obviously that code doesn't work so how to go about it?
You have to callprinteven if the number is odd, or recursion stops. Also onlyprintfwhen the value is even, and stop whennindex is negative or you have access violation. Fixed: ``` void print(int a[],int n) { n--; if (n>=0) { print(a,n); if(a[n]%2==0) { printf("%d ",a[n]); } } } ``` prints:2 4
I have a double free that I'm trying to hunt down. It got introduced in an edge case long ago, far enough back that I can't easily bisect to find what introduced it. So the next best way to hunt it down would be to debug it. I tried to find any documentation indicating whether Valgrind'sgdbserver could be configured to break on any violation. This would be desirable so I could understand the context of the second free. (Hopefully the invalid free is the second one).
Valgrind activates by default its embedded gdbserver. This allows a GDB to connect to it at any moment. If you want Valgrind gdbserver to stop and wait for a connection from GDB when an error is detected, you can use the option--vgdb-error=<number> By specifying--vgdb-error=1, valgrind will stop at the first error detected, and all the following errors. Seehttp://www.valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.gdbserverfor more details
i notice in a function this will not work: ``` char a[10]; sprintf(a, "test"); return a; ``` but this works: ``` char *a; a = malloc(10); sprintf(a, "test"); return a; ``` QUESTION: if i do not have to "return a;"..is it better to use "char a[10];" ? if so. why ?
mallocis a function call into the standard library. Depending on current heap fragmentation and heap organisation of the compiler, this may be an expensive operation (even the call into the library alone may consume more CPU cycles than a stack allocation). char a[10]is an increment of the stack frame (rather: works out to a simple subtraction of 10 from the current stack pointer). Stack allocation is definitively faster on most non-exotic architectures.
I'm very new to gdb. I wrote a very simple hello world program ``` #include <stdio.h> int main() { printf("Hello world\n"); return 0; } ``` I compiled it with-gto add debugging symbols ``` gcc -g -o hello hello.c ``` I'm not sure what to do next since I'm not familiar with gdb. I'd like to be able to use gdb to inspect assembly code. That's what I was told on IRC.
First, start the program to stop exactly at the beginning ofmainfunction. ``` (gdb) start ``` Switch to assembly layout to see assembly instructions interactively in a separate window. ``` (gdb) layout asm ``` Usestepiornexticommands to step through the program. You will see current instruction pointer in assembly window moving when you walk over the assembly instructions in your program.
there is an error when trying to executing the fork() call. warning: implicit declaration of function ‘fork’ [-Wimplicit-function-declaration fork(); here is my code ``` #include <stdio.h> int main() { int a, b; b = fork(); printf("hello"); if (b == 0) { printf("child"); } else { printf("parent"); } } ```
Try ``` #include <stdio.h> #include <unistd.h> int main() { int a; pid_t b; b = fork(); printf("hello"); if (b == 0) { printf("child"); } else { printf("parent"); } } ```
Why does this print1,1,2,3,4,5instead of1,2,3,4,5? ``` #include <stdio.h> #include <stdlib.h> void print(int a[5], int n) { if(n > 0) { print(a, --n); } printf(" %d", a[n]); } int main() { int n, a[] = {1,2,3,4,5}; n = sizeof(a) / sizeof(a[0]); print(a, n); return 0; } ``` And how would you code it to print 1,2,3,4,5 using recursion in that manner ie traversing from the last?
The problem with your code is that you decrementnafter the comparison in theifconditionn > 0. Whenprint(a, 1)is called, the comparisonn > 0is true. Thennis decremented and, the recursive call is done andprint(a, 0)evaluated. That fails the comparison and printsa[0]once. Then back in the calling function,a[0]is printed another time, since the localnafter decrementing is also equal0. One way to fix it is to decrementnbefore doing the comparison with zero.
The log.txt file consist of some data. The program looks for ":" and when it find it prints "Done". The program compiles successfully but never prints "Done". ``` char *atrbt ; FILE *fp; int i = 0; if (fp = fopen("log.txt", "r+")) { while (fscanf(fp, "%c", &atrbt) != EOF) { printf("%c", atrbt); if(atrbt[i] == ':') { <------------ Issue printf("Done"); } ++i; } } ```
You are mixing between char and char pointers. One of the possible correct ways could be (code is untested): ``` char atrbt; FILE *fp; if (fp = fopen("log.txt", "r+")) { while ((atrbt = getc(fp)) != EOF) { printf("%c", atrbt); if(atrbt == ':') { printf("Done"); } } } ```
I have multiple C files 1.c 2.c and 3.c and their correspondent headers 1.h 2.h 3.h. these files use the samestatic char*variable so I want to define this variable in one header file. Is there any solution? like : #define nameVariable valueVariable NB : None of the c files include another header (i.e 1.c dont include 2.h and 3.h etc..).All of the 3 files include a 4.h file.All of the 3 files have the same Makefile.
If the variable in question is a constant string that will never change, you can get away with using a#definefor this. In 4.h: ``` #define MY_STATIC_STRING "my_string" ``` This will perform a text substitution in each source file anyplace you useMY_STATIC_STRING.
In the following program,Why compiler does not gives any error or warning? ``` cc -Wall -pedantic my_program.c ``` code here: ``` #include <stdio.h> void f() { return; // return statement in void function } int main() { f(); return 0; } ``` I have compiled the program inGCCcompiler onLinuxplatform.
Of course you can usereturn;in avoidfunction. How else would you return early from such a function? In your case the statement is redundant as it's reached on all control paths, but a compiler will certainly not issue a diagnostic in that instance. (Note that youmustreturnexplicitly from a non-voidfunction, with the exception ofmain(), where a compiler must generatereturn 0;if missing.
I opened a socket with ``` sockfd = socket(AF_INET, SOCK_DGRAM, 0); ``` then send packet with ``` bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, server->h_length); serveraddr.sin_port = htons(portno); sendto(sockfd, buf, strlen(buf), 0, &serveraddr, serverlen); ``` In what stage the source port of the socket is assigned ? insocket()or insendto()? Does the source port keep unchanged in all calls ofsendto()function ?
sendto() perform an implicit bind if you do not call bind() explicitly.
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed6 years ago. i tried coping a string to a pointer using strcpy. it causes a segmentation fault.any reason for that. ``` #include <stdio.h> #include <string.h> int main() { char *str=NULL; strcpy(str,"C-DAC"); printf("%s\n",str); return 1; } ```
WHere does your string point to? Nowhere! That's why you have segmentation fault. You have to either allocate variable on stack as array or define it as pointer and later allocate memory usingmalloc. When usingmalloc, don't forget to include "stdlib.h" Either do this: ``` char str[6]; strcpy(str,"C-DAC"); ``` or ``` char *str=malloc(sizeof(*str) * 6); strcpy(str,"C-DAC"); ```