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 = mal... |
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 []=... |
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());
re... |
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 wit... |
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... |
"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;
cha... |
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 incre... |
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') Suc... |
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... |
"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;
cha... |
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 incre... |
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') Suc... |
```
#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... |
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 undefin... |
```
#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 me... |
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... |
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... |
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: " pa... |
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... |
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();
... |
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 ... |
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(... |
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 cal... |
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... |
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" ... |
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 ... |
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... |
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)... |
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 representatio... |
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:
```
#in... |
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
+--- ... |
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 mean... |
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 // Bi... |
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 re... |
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);
prin... |
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 in... |
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>
#inc... |
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("Elem... |
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... |
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 nod... |
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("%... |
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 whic... |
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 t... |
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>
#inc... |
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("Elem... |
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... |
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 nod... |
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("%... |
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 whic... |
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 t... |
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 i... |
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 da... |
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 l... |
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 ... |
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) {
...
}
```
... |
```
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", (vo... |
```
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", (vo... |
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 cha... |
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
```
... |
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... |
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 as... |
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 creat... |
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... |
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()
{
... |
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");... |
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 produc... |
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(" a... |
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 followin... |
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 varia... |
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 ... |
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... |
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 ... |
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 mea... |
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 wil... |
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 creat... |
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... |
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()
{
... |
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");... |
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 produc... |
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(" a... |
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 followin... |
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 varia... |
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 ... |
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... |
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 ... |
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 mea... |
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 wil... |
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 t... |
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... |
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:
``... |
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 i... |
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 iden... |
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 ... |
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 ... |
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 someth... |
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:
``... |
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 i... |
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 iden... |
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 ... |
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 ... |
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 someth... |
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 ... |
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]);
}
}
... |
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 t... |
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 d... |
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 ... |
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 ... |
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... |
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
... |
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 ... |
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 printe... |
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("%... |
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 inclu... |
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 onLinu... |
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... |
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(so... |
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()
{... |
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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.