question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I've stumbled upon a following problem, could anyone please help?
I'm trying to use bitwise operations, and I'm expecting this to print the value of 2^50. The output, however, is 0. The maximum I can get it to print is 2^31, which is supposed to be the maximum of normal int, right? So am I doing something terribly wro... |
You have to make your constant an unsigned long long type, which guarantees at least 64 bits in size:
```
uint64_t x=(1LLU<<50);
```
|
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.Closed8 years ago.Improve this question
My question is very simple and trivial, but I haven't found an explicit answer.
if there... |
The concept of "significance" only makes sense when the unit being talked about (e.g. bit or byte) takes part inrepresenting a valuemade up of more than one such unit. As in indiv's comment, an array of 2charobjects has no inherent meaning as a single value. If you choose to use it as such, it's up to you how you inte... |
```
struct TCB_t *del = RunQ;
del->next = NULL;
```
In the line of code above any changes that are made to del are also made to RunQ. In the first line all the values of RunQ are also given to del. I figured after this line any changes to del would not effect RunQ. However after the second line, RunQ->next is Null... |
```
struct TCB_t del = *RunQ;
del.next = NULL;
```
or
```
struct TCB_t newRunQ = *RunQ;
struct TCB_t *del = &newRunQ;
del->next = NULL;
```
|
I am reading a file, and want to store the line number on a particular condition.
I know thatfgetsused to read the line, is there any way to store/get the line number where the cursor located.
|
There is no cursor in the context of a standard file stream. There is a file pointer, but not a cursor. The cursor is a concept of the console / terminal driver. Even with file pointers, you don't typically use them in line-mode, they are for random access / binary type access. You can seek to the beginning and end of... |
I am implementing a program to run in user space as often as possible. So I am trying to call functions which enter and leave kernel space as less as possible. For example, I use some DMA API which read/write but bypass the kernel.
I don't know how to tell a function needs to enter kernel space or not. For example, I... |
Have you run your program through strace? That will let you know where you are making system calls that will enter kernel space
|
With the code:
```
#define MACRO(A,B) foo(A); bar(B)
if(true) {
MACRO(A,B);
}
```
Astyle will remove the brackets around the macro call
```
if(true)
MACRO(A,B);
```
Fortunately I found a solution. If I place the;inside the macro, Astyle will understand it.
```
#define MACRO(A,B) foo(A); bar(B);
if(true)... |
It's a bad style.
If you absolutely must have multiple statements in macro, wrap them indo whileloop (note the lack of semicolon at the end):
```
#define MACRO(A,B) do { foo(A); bar(B); } while(0)
```
|
I'm currently learning the C language and I'm having trouble in thedoublemultiplication topic.
I need to to print the original value and then the2*valueof thedouble.
```
double num = 34.39;
printf("Original value = %d, 2x original value = %d", num, num*2);
```
How do I make it so that the 2x value will be really ... |
Your multiplication is not the problem.
Yourprintfformat string is.%dis not for floating-point values, but for integers, so you're seeing nonsense resulting from your broken contract with the compiler.
```
double num = 34.39;
printf("Original value = %lf, 2x original value = %lf", num, num*2);
```
|
When I search using keywords of 'fgets' and 'newline', there are many posts regarding how to remove the trailing newline character (and such removal appears to be a burden). Yet it seems there is few explaination on how that newline is necessary for fgets to include. Also in C++, the 'std::getline' and 'std::istream:g... |
Here is satisfying (IMHO) explanation:http://www.cplusplus.com/reference/cstdio/fgets/
Especially:
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
|
I'm trying to usescanfin a function.In the first use, code is working fine, but in the second,scanfdoesn't work.Variable's value doesn't change, but I need to type something.Here is a part of my code :
```
char *choix;
choix=(char *)calloc(20,sizeof(char));
printf("Saisissez le nom du fichier que vous voulez charger ... |
Stop usingscanf()for stuff like this, it's a bit hard to use.
Instead, usefgets()to read a whole line from the user, then parse that line if you need to. You can then remove the home-grown input flushing code.
|
Given the following code:
```
#include <stdio.h>
#ifndef STR
#define STR "HELLO"
#endif
int main() {
printf(STR "WORLD \n");
return 0;
}
```
which says: ifSTRwas not defined, then define it to be"HELLO",
so the output will be
```
HELLO WORLD
```
How can I modify the value ofSTRwhen compiling usinggcc... |
Try in the form of:
```
-DSTR=\"MyString\"
```
|
With the code:
```
#define MACRO(A,B) foo(A); bar(B)
if(true) {
MACRO(A,B);
}
```
Astyle will remove the brackets around the macro call
```
if(true)
MACRO(A,B);
```
Fortunately I found a solution. If I place the;inside the macro, Astyle will understand it.
```
#define MACRO(A,B) foo(A); bar(B);
if(true)... |
It's a bad style.
If you absolutely must have multiple statements in macro, wrap them indo whileloop (note the lack of semicolon at the end):
```
#define MACRO(A,B) do { foo(A); bar(B); } while(0)
```
|
I'm currently learning the C language and I'm having trouble in thedoublemultiplication topic.
I need to to print the original value and then the2*valueof thedouble.
```
double num = 34.39;
printf("Original value = %d, 2x original value = %d", num, num*2);
```
How do I make it so that the 2x value will be really ... |
Your multiplication is not the problem.
Yourprintfformat string is.%dis not for floating-point values, but for integers, so you're seeing nonsense resulting from your broken contract with the compiler.
```
double num = 34.39;
printf("Original value = %lf, 2x original value = %lf", num, num*2);
```
|
When I search using keywords of 'fgets' and 'newline', there are many posts regarding how to remove the trailing newline character (and such removal appears to be a burden). Yet it seems there is few explaination on how that newline is necessary for fgets to include. Also in C++, the 'std::getline' and 'std::istream:g... |
Here is satisfying (IMHO) explanation:http://www.cplusplus.com/reference/cstdio/fgets/
Especially:
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
|
I'm trying to usescanfin a function.In the first use, code is working fine, but in the second,scanfdoesn't work.Variable's value doesn't change, but I need to type something.Here is a part of my code :
```
char *choix;
choix=(char *)calloc(20,sizeof(char));
printf("Saisissez le nom du fichier que vous voulez charger ... |
Stop usingscanf()for stuff like this, it's a bit hard to use.
Instead, usefgets()to read a whole line from the user, then parse that line if you need to. You can then remove the home-grown input flushing code.
|
Given the following code:
```
#include <stdio.h>
#ifndef STR
#define STR "HELLO"
#endif
int main() {
printf(STR "WORLD \n");
return 0;
}
```
which says: ifSTRwas not defined, then define it to be"HELLO",
so the output will be
```
HELLO WORLD
```
How can I modify the value ofSTRwhen compiling usinggcc... |
Try in the form of:
```
-DSTR=\"MyString\"
```
|
Is there a clever way to share common actions between scripts in Loadrunner?
Let me explain. Our company will have to create 50 different scripts with different scenarios. Most of them requires logging on to our website, and logging out. It's kind of annoying to have to update 50 scripts, when the log-in requests are... |
Use a C header file, such as myfunctions.h
You can either include this as a separate file in your script, copy it to all of the load generators loadrunner\include directory (default search scope) or provide it in a network location which is accessible to all load generators
|
I want to save the address of a variable in a clean way, so NO Compiler errors or warnings.I've got something like this:
```
unsigned int a = 5;
unsigned int address = (unsigned int)&a;
```
But I get some compiler-warnings. If I write
```
unsigned int address = &a;
```
its also the wrong way. So what is the clean ... |
You can use pointers in c, which should be something like
```
int *address = &a;
```
|
I am trying to copy argv to char array,been through some solutions online but ending up in getting Segmentation Fault. Following is the code i used:
```
void main (int argc,const char *argv[])
{
char *arr;
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
```
Please help to identify what I... |
It seems that argv[1] is equal to NULL or even does not exist (The C Standard allows that argc may be equal to 0).
Add the following check
```
char *arr;
if ( argc > 1 )
{
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
else
{
// print some error message
}
```
|
Suppose I want to generate a very long, repetitive string, such as
```
"foo bar bar bar bar ... bar"
```
wherebaroccurs 1,000 times in the final result. What would be the easiest way to do this without having memory leaks?
|
The first thing that came to my mind is:
```
char *string = malloc(4004);
int i;
strcpy(string, "foo");
for(i = 0; i < 1000; i++)
strcat(string, " bar");
```
|
I am wondering if there are any algorithms to perform a floating-point division that would be accelerated if one has access to a floating point square root unit in hardware?
If so, what are those algorithms?
|
Division by square root is actually the way division operation is usually implemented in hardware. To be more precise the square root unit almost universally internally computes reciprocal square root (1/sqrt(X)), because with it one can easily perform both division and square root operations:sqrt(x) = x*(1/sqrt(x))an... |
If I have:
```
struct my_container {
int x;
struct some_struct *ss;
}
```
If I have the pointer ss through which I can access the members inside some_struct, I should be able to access my_container by doing the following right ?
This is what I am doing:
```
struct my_container *my_c;
my_c = container_of(&s... |
If you only have a pointer tosome_struct(i.e. if youjusthavestruct some_struct *ss;), you cannot use thecontainer_ofmacro in this way, as&sswill just evaluate to the address of some variable,notthe address ofmy_container. To use it properly, you'll need a pointer to a pointer tosome_struct(i.e.struct some_struct **pss... |
When I compile my Arduino sketch(language C), I get the error:
```
sketch_oct30b:2: error: ‘e’ was not declared in this scope
sketch_oct30b:2: error: ‘z’ was not declared in this scope
```
This is the piece of code,char zis in the first line of the whole code.
```
char z[4] = "z_0";
int e = 0;
char delta(e, z) {}
... |
The error means that in this function definition
```
char delta(e, z) {}
```
names e and z are not declared,
Either you have to specify a parameter list as for example
```
char delta( int e, char z[]) {}
```
or anidentifier list
```
char delta(e, z) int e; char * z; {}
```
|
This is an excerpt from my code. It reads a file and puts the first line into acharand then puts part of that first line into an int. The first line of the file is "10 20". The file does get closed later on. The output when I print temp is 10 20, but when I print rct it is 49 and cct is 32. I am completely new to c an... |
You're trying to convert a string to an integer, which you can't do by assignment. What you're actually doing is printing the character code for the first and third characters in the string (49 is ASCII for'1', 32 ASCII for' '). Instead, you should usefscanfto do the parsing for you.
|
I have some code that draws a cube. I've managed to rotate the cube using glRotatef but I need to be able to rotate the cube using only matrix multiplication. I know what matrices to use but I'm not sure how to apply them to the vertices of the cube. Is there a way to pass a vector to glVertex3f? Or a way to pass an a... |
I agree completely with Drew's answer. However, I figured I'd point you in the direction of a nicely-written tutorial series that shows these concepts in action:
http://en.wikibooks.org/wiki/OpenGL_Programming
Start with the first 3 tutorials to learn shader basics, and then the 4th and 5th tutorials dive into rota... |
When using the open() function in C, I get a fd (file descriptor). I was wondering if it's the same thing as its process id, because as I know, fd is an integer.
|
No it is not.PID is process identifier, and file descriptor is file handler identifier.
Specifically from Wikipedia about File Descriptors:
(...) file descriptor (FD) is an abstract indicator for accessing a file. The term is generally used in POSIX operating systems.In POSIX, a file descriptor is an integer, specif... |
This question already has answers here:Why is sizeof considered an operator?(10 answers)Closed8 years ago.
I saw some code which used sizeof directly and wondered if it is standard C. To my surprise, it was working just fine. Here is an example:
```
#include <stdio.h>
#include <string.h>
int main()
{
char buff[... |
"When sizeof's operand is a type, it has to be enclosed in parentheses. But when sizeof's operand is a variable, this is not required."--Expert C Programming: Deep C secrets. And from c11 standard:
```
sizeof unary-expression
sizeof ( type-name )
```
|
```
Rf_Rx_Buff[0]; //first 2 bits of serial number
Rf_Rx_Buff[1]; //second 2 bits
Rf_Rx_Buff[2]; //third
Rf_Rx_Buff[3]; //fourth
```
I want to hardcode the serial number of the device.
```
Rf_Rx_Buff[0]=0x30;
Rf_Rx_Buff[1]=0x67;
Rf_Rx_Buff[2]=0x43;
Rf_Rx_Buff[3]=0x57;
```
I am getting an error saying invalid di... |
In C, you have to declare the type of the variable before you use it. And since you are using an array, you have to do it like this:
```
char Rf_Rx_Buff[4]; //declare an array of char with size 4
Rf_Rx_Buff[0]=0x30;
Rf_Rx_Buff[1]=0x67;
Rf_Rx_Buff[2]=0x43;
Rf_Rx_Buff[3]=0x57;
```
|
The following program fragment
```
int k=-7;
printf("%d",0<!k);
```
will print 0 according to the answer.
Can anyone explain me why ?
|
So here's what you're printing:
```
0 < !(-7)
```
First, !(-7) will give 0, because -7 is a "truthy" integer, i.e. it is non-zero, and!negates it, so the whole thing is "false" i.e. 0.
Then you have:
```
0 < 0
```
Which is of course false, i.e. 0 in C. You print that as an integer, so of course you see0.
|
I have to interpret some c-code as a kind of homework and I don't really understand this macro:
```
#define rdtscll(val)__asm__ __volatile__("rdtsc":"=A"(val))
```
I know it's some kind of static function namedrdtscllwhich receives one parameterval. But what about the rest?
What are__asm__and__volatile__and why tho... |
In this case__asm__and__volatile__are compiler extensions for embedding assembly statements into a C file. The two leading underscores are to prevent clashes with identifiers in user code, and the trailing are pure choice.__volatile__is just an "anti-optimization" directive.
rdtscis an x86 instruction for reading the... |
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.Closed8 years ago.Improve this question
I have an array like this:
```
char data[512];
```
for clearing my array use:
```
memset(&data[0], 0, si... |
datais an array of 512charvariable (1 byte), so thesizeof(data)is 512. This is correct. Read more about data types.
|
In C, strcmp() function returns 0 if two strings are equal.
When I give a code like this,
```
char str[10] = "hello";
if(strcmp(str,strrev(str))==0)
{
printf("1");
}
else
printf("0");
```
This should print a 1 if its a palindromic string or it should print 0 if it is not a palindrome.
But it prints 1 even when the g... |
What isstrrev()? That's not a standard C function.
My assumption would be that it doesn't work like you think it does, i.e. it doesn't create and return a new heap copy of the string. Of course,ifyou expect that, then there's a bug that you don't retain the returned pointer so you canfree()it when you're done.
Basic... |
When I use--std=c99GCC defines__STRICT_ANSI__and when it is on, the BSD and System V features don't kick in. It implies__USE_MISCand__USE_POSIXare left undefined.
```
-- stdio.h --
...
#if defined __USE_POSIX || defined __USE_MISC
extern int getc_unlocked (FILE *__stream);
extern int getchar_unlocked (void);
#endif /... |
Use-std=gnu99instead of-std=c99and it will work the way you want.
|
G'day!
Usually if I was using malloc, I'd check for failure via:
```
int *A;
A=(int *)malloc(NUM_ELEMENTS*sizeof(int));
if (!A) {
printf("mem failure, exiting \n");
exit(EXIT_FAILURE);
}
```
Can I do the same thing for calloc, even though everything is assigned to 0? My gut feel is yes, because we'd be che... |
Yes, you can error checkcallocjust likemalloc. However, sincecallocis fairly rock-solid failure wise, you usually don't need to do so, as explained herehow can i know if calloc fails to initialize.
|
I came across this in an assessment and I need to find the bug and explain why.
```
int process(int, int*, int*);
int example10(int in)
{
int *buffer1 = (int*)malloc(1000 * sizeof(int));
if (!buffer1)
return -1;
int *buffer2 = (int*)malloc(2000 * sizeof(int));
if (!buffer2)
return ... |
You are freeingbuffer1andbuffer2only when bothifcondition got passed. What if firstifcondition got passed and secondifcondition got failed. There will be memory leak in that case. Therefore free thebuffer1in secondifstatement.
|
I need to initialize a typedef struct pointer
in header file,
```
typedef struct {
DWORD RxBuf[4];
DWORD Tr0c;
} t, *p_t;
```
In the cpp file,
```
static p_t p1
= {
{0x00,0x00,0x00,0x00},
0
};
```
|
Just a guess, I believe you want to do:
```
static t tNull
= {
{0x00,0x00,0x00,0x00},
0
};
static p_t p1 = &tNull;
```
|
I am aware of utilities like GNUgettextfor making the software multilingual.
You give it a string id and it will return the translated string.
But I also need this for images in Qt.For example, if I am displaying an image inen_USlocale, I want to display a different version of the image if sayja_JPorfr_FRlocale is se... |
Yes theresource systemallows you to specify the language each resource is associated with thelangattribute in the.qrcfile.
|
I have a gtk window that contains a notebook. I want to get the children of the same. I am using following statementGList *children;
notebook = GTK_WIDGET (gtk_builder_get_object (self->gui, "list_notebook"));
children = gtk_container_get_childern (GTK_CONTAINER (notebook));
I am getting the following error while c... |
gtk_container_children()has been deprecated for averylong time and is not part of the GTK+ 3 API. Whatever component is using that macro needs to be updated to usegtk_container_get_children().
|
if source file is source.cpp then compiler output should have source.i source.s
source.o in my directory not only .o file.
where
preprocessed = source.iassembly = source.sobject = source.o
i know first two files are being created but later on they got deleted only .o file is
shown so that linker can link object fi... |
According to the gcc man pages
-save-temps
-save-temps=cwd
Store the usual "temporary" intermediate files permanently; place them in the current directory and name them based on the source file. Thus, compiling foo.c with -c -save-temps would produce files foo.i and foo.s, as well as foo.o. This cr... |
I have doubt regarding the following piece of code :
```
int main()
{
int array1 = {1,2,3,4,5}; //error in c++ , warning in c
int array2[] = {1,2,3,4,5};
int array3[5] = {1,2,3,4,5};
}
```
This piece of code gives a error on line 3 inc++but not inc?
I knowarray1is actually anintandarray2andarray3are arr... |
It is not valid C. See C11 6.7.9:
No initializer shall attempt to provide a value for an object not
contained within the entity being initialized.
I would guess that you are using gcc. Then if you want your program to behave as strict standard C, compile it as such:
```
gcc -std=c11 -pedantic-errors
```
gives
e... |
```
typedef int WORD;
short WORD x =2;
```
Compiler throws an error. I have searched in the internet and books. I read that typedef cannot be used with type modidfers [unsigned, signed, long, short.]
And i found that it can be used in the following way.
```
typedef short int WORD;
WORD x =2;
```
Whytypedefcannot ... |
In Deep C, i read that typedef cannot be used with type modidfers [unsigned, signed, long, short.]
Why typedef cannot be used with type modifiers?
That's nonsense.
Compiler throws an error.
Because typedef is not text replacement. You can only use one type per declaration. Soshort WORD xmakes as little sense asdo... |
In Unix I can calltimes()to get not only the running time of the current process, but also that of the whole process group.
In Windows, I can callGetProcessTimes()to get the time of the current process. However, the documentation seems to indicate that this doesn't return the running time of the whole process group.
... |
As Harry said, this can't be done, at least not directly, because Windows does not track the parent/child relationship between processes like Unix does.
However, you can work around this by creating shared memory for processes, and have them both update that location as they go along. Here is where you can find mored... |
I came across this in an assessment and I need to find the bug and explain why.
```
int process(int, int*, int*);
int example10(int in)
{
int *buffer1 = (int*)malloc(1000 * sizeof(int));
if (!buffer1)
return -1;
int *buffer2 = (int*)malloc(2000 * sizeof(int));
if (!buffer2)
return ... |
You are freeingbuffer1andbuffer2only when bothifcondition got passed. What if firstifcondition got passed and secondifcondition got failed. There will be memory leak in that case. Therefore free thebuffer1in secondifstatement.
|
I need to initialize a typedef struct pointer
in header file,
```
typedef struct {
DWORD RxBuf[4];
DWORD Tr0c;
} t, *p_t;
```
In the cpp file,
```
static p_t p1
= {
{0x00,0x00,0x00,0x00},
0
};
```
|
Just a guess, I believe you want to do:
```
static t tNull
= {
{0x00,0x00,0x00,0x00},
0
};
static p_t p1 = &tNull;
```
|
I am aware of utilities like GNUgettextfor making the software multilingual.
You give it a string id and it will return the translated string.
But I also need this for images in Qt.For example, if I am displaying an image inen_USlocale, I want to display a different version of the image if sayja_JPorfr_FRlocale is se... |
Yes theresource systemallows you to specify the language each resource is associated with thelangattribute in the.qrcfile.
|
I have a gtk window that contains a notebook. I want to get the children of the same. I am using following statementGList *children;
notebook = GTK_WIDGET (gtk_builder_get_object (self->gui, "list_notebook"));
children = gtk_container_get_childern (GTK_CONTAINER (notebook));
I am getting the following error while c... |
gtk_container_children()has been deprecated for averylong time and is not part of the GTK+ 3 API. Whatever component is using that macro needs to be updated to usegtk_container_get_children().
|
if source file is source.cpp then compiler output should have source.i source.s
source.o in my directory not only .o file.
where
preprocessed = source.iassembly = source.sobject = source.o
i know first two files are being created but later on they got deleted only .o file is
shown so that linker can link object fi... |
According to the gcc man pages
-save-temps
-save-temps=cwd
Store the usual "temporary" intermediate files permanently; place them in the current directory and name them based on the source file. Thus, compiling foo.c with -c -save-temps would produce files foo.i and foo.s, as well as foo.o. This cr... |
I have doubt regarding the following piece of code :
```
int main()
{
int array1 = {1,2,3,4,5}; //error in c++ , warning in c
int array2[] = {1,2,3,4,5};
int array3[5] = {1,2,3,4,5};
}
```
This piece of code gives a error on line 3 inc++but not inc?
I knowarray1is actually anintandarray2andarray3are arr... |
It is not valid C. See C11 6.7.9:
No initializer shall attempt to provide a value for an object not
contained within the entity being initialized.
I would guess that you are using gcc. Then if you want your program to behave as strict standard C, compile it as such:
```
gcc -std=c11 -pedantic-errors
```
gives
e... |
```
typedef int WORD;
short WORD x =2;
```
Compiler throws an error. I have searched in the internet and books. I read that typedef cannot be used with type modidfers [unsigned, signed, long, short.]
And i found that it can be used in the following way.
```
typedef short int WORD;
WORD x =2;
```
Whytypedefcannot ... |
In Deep C, i read that typedef cannot be used with type modidfers [unsigned, signed, long, short.]
Why typedef cannot be used with type modifiers?
That's nonsense.
Compiler throws an error.
Because typedef is not text replacement. You can only use one type per declaration. Soshort WORD xmakes as little sense asdo... |
I am using the command line to get input of 3floatsseparated by spaces. e.g."1.234 5.678 9.012".
I am currently using:
```
float xyz[3] = {0};
scanf("%f", xyz);
print(%f %f %f, xyz[0], xyz[1], xyz[2]);
```
However the output is "1.234000 0.000000 0.000000".
Expected output is "1.234000 5.678000 9.012000"
EDIT: I ... |
Maybe this
```
#include <stdio.h>
int main(int argc, char** argv)
{
float vals[3];
printf("input 3 float values: ");
int res = scanf("%f %f %f", &vals[0], &vals[1], &vals[2]);
if(res == 3)
{
printf("read 3 floats %f %f %f\n", vals[0], vals[1], vals[2]);
} else
{
printf(... |
I am trying to learn pointer manipulation in C, and I am not understanding how part of the code isn't working.
```
#include <stdio.h>
int main() {
int *alpha[17];
*(alpha+4)= 35;
*(alpha+5)= 35;
*(alpha+12)= 50;
printf("%d", *(alpha+4));
*(alpha+8)=*(alpha+5) + *(alpha+12);
return 0;
}
```
Why is t... |
int *alpha[17];creates array of pointers.
If you want array of int, useint alpha[17];
Your assignations are succesful because of implicit cast from int to pointer. (I hope you are getting warnings)
Adding two pointers is not only non-sensical, but also not allowed inC.This postcovers why adding two pointers is forb... |
I'm trying to understand pointers more and am having trouble with this example.
```
typedef struct{
int areaCode;
int streetNumber;
}Address;
Address *addr;
addr->areaCode = 10000;
printf("%d\n", addr->areaCode);
```
I get a segmentation fault and can't seem to understand why.
addr is a pointer to a Add... |
```
Address *addr;
```
You only declared a pointeraddr, but it points to somewhere unknown. You didn't allocate memory space for it.
To fix it, change into
```
Address *addr = malloc(sizeof(Address));
```
|
I don't understand why I can do this:
```
#include "stdio.h"
#include "string.h"
char a[1][100];
void main(void) {
strcpy(a[0], "test1");
strcpy(a[1], "test2");
strcpy(a[6], "test3");
printf("%s", a[0]);
printf("%s", a[1]);
printf("%s", a[6]);
}
```
Will return:
```
test1test2test3
```
... |
Yes it is out of bounds but what are you expecting to happen?
Thestrcpy(a[6], "test3");will overwrite a portion of the stack. Will it cause a problem? Probably. will it be immediately obvious? Probably not.
|
This question already has answers here:Java logical operator short-circuiting(10 answers)Closed8 years ago.
For instance if I have an if statement as follows:
```
if(returnsFalse() && timeConsumingFunction()){
//do whatever
}
```
Will the program run the time consuming function or will it realise that the if ev... |
No if you use && it will not continue on if the first statement is false.(Java) If you use & it will evaluate all expressions.
|
I was wondering how can I create a text file like this:
For example if I have:
```
FILE *f;
int id=1;
f = fopen("file\%d.txt", "a");
```
In the end of file I would like to add the number of the id. I tried several things but nothing worked.
|
You fail to show what you actually tried.
The typical solution is to usesprintf():
```
char fnbuf[1024];
int a = 1;
sprintf(fnbuf, "file%d.txt", a);
f = fopen(fnbuf, "a");
```
Note that this is pretty safe, but in a real program with more complexity it's a good idea to usesnprintf(), and of course to check the retu... |
I have a function that runs every second automatically,
inside the function i have a counter "i" that increments by 1 so every 1sec. i dont want to run stuff every second but at every x seconds e.g. every 10 seconds.
so i presume the best approach is to detect the increments of i, when it increases by 13?
or a timer... |
I think you are looking for modulo operation (http://en.wikipedia.org/wiki/Modulo_operation):
```
void func(void){
static int i = 0;
int x = 13
if (i % x == 0)
{
do something
}
i++;
}
```
|
I'm kind of new to C and started looking through Learn C (http://www.learn-c.org/). In the function section the exercise asks the user to print outx is bigifx> 10. My issue is that the official answer is
```
int print_big(int number){
if(number > 10){
printf("%d is big\n",number);
}
}
```
Why is the ... |
Ideally, the function should return void, as the function is not returning anything for the caller.
```
void print_big(int number){
if(number > 10){
printf("%d is big\n",number);
}
```
|
```
char statement[1052]="test", *a=inet_ntoa(iphdr->ip_src);
char c[20]="1";
strcpy(c,a);
char *b=inet_ntoa(iphdr->ip_dst);
snprintf(statement, 1052, "INSERT INTO tblname(ip1,ip2) VALUES ('%s','%s')",c,b);
printf("%s\n,statement);
```
This works correctly , but when I try to remove the second and third line, the val... |
Fromhttp://linux.die.net/man/3/inet_ntoa
The inet_ntoa() function converts the Internet host address in, given
in network byte order, to a string in IPv4 dotted-decimal notation.
The string is returned in astatically allocated buffer, which
subsequent calls will overwrite.
The second call toinet_ntoais overwri... |
What is quicker in C: operator!=or>?
I am asking because what if we have a large amount of loops and we have to use one of the above conditions (while(x!=-1)orwhile(x>0)).
Also what about other languages.
|
On most modern processors it will not make any difference.
This is usually compiled as a comparison instruction, which sets certain flags followed by a jump which branches on the combination of some of the flags. There is generally no timing difference between the relational operators.
Some optimizations might omit ... |
I want to generate 60 files, program0.txt,.., program59.txt.
How can I do this?
My attempt:
```
FILE *fp[60];
for(i=0;i<60;i++){
fp[i]=fopen("program.txt","w");
fprintf(fp[i],"zeros=[");
}
```
|
Use followingfilename[]toformfilenames
```
char filename[15] ;
int i;
for( i =0; i<60; ++i )
{
sprintf(filename, "program%02d.txt",i);
//printf("%s\n", filename );
/*
fp[i] = fopen( filename ,"w");
....
fclose( fp[i] );
*/
}
```
|
Sorry for this easy question but I couldn't find the answer, if I got a while loop that looks like this. Does it calculate before or after the comparison?
```
a = 0;
while(a++ < 5)
{
....
```
When it first runs the loop will it look at it as "1 < 5" or "0 < 5". Thanks
|
Comparison is doneBEFOREthe increment, but the body of the loop sees the valueAFTERicrementation. So in the first run you'll compare 0 < 5, but in the loop a will have the value of 1.
|
I'm trying to understand pointers more and am having trouble with this example.
```
typedef struct{
int areaCode;
int streetNumber;
}Address;
Address *addr;
addr->areaCode = 10000;
printf("%d\n", addr->areaCode);
```
I get a segmentation fault and can't seem to understand why.
addr is a pointer to a Add... |
```
Address *addr;
```
You only declared a pointeraddr, but it points to somewhere unknown. You didn't allocate memory space for it.
To fix it, change into
```
Address *addr = malloc(sizeof(Address));
```
|
I don't understand why I can do this:
```
#include "stdio.h"
#include "string.h"
char a[1][100];
void main(void) {
strcpy(a[0], "test1");
strcpy(a[1], "test2");
strcpy(a[6], "test3");
printf("%s", a[0]);
printf("%s", a[1]);
printf("%s", a[6]);
}
```
Will return:
```
test1test2test3
```
... |
Yes it is out of bounds but what are you expecting to happen?
Thestrcpy(a[6], "test3");will overwrite a portion of the stack. Will it cause a problem? Probably. will it be immediately obvious? Probably not.
|
This question already has answers here:Java logical operator short-circuiting(10 answers)Closed8 years ago.
For instance if I have an if statement as follows:
```
if(returnsFalse() && timeConsumingFunction()){
//do whatever
}
```
Will the program run the time consuming function or will it realise that the if ev... |
No if you use && it will not continue on if the first statement is false.(Java) If you use & it will evaluate all expressions.
|
I was wondering how can I create a text file like this:
For example if I have:
```
FILE *f;
int id=1;
f = fopen("file\%d.txt", "a");
```
In the end of file I would like to add the number of the id. I tried several things but nothing worked.
|
You fail to show what you actually tried.
The typical solution is to usesprintf():
```
char fnbuf[1024];
int a = 1;
sprintf(fnbuf, "file%d.txt", a);
f = fopen(fnbuf, "a");
```
Note that this is pretty safe, but in a real program with more complexity it's a good idea to usesnprintf(), and of course to check the retu... |
If the code is
```
scanf("%s\n",message)
```
vs
```
gets(message)
```
what's the difference?It seems that both of them get input to message.
|
The basic difference [in reference to your particular scenario],
scanf()ends taking input upon encountering awhitespace,newlineorEOFgets()considers a whitespace as a part of the input string and ends the input upon encounteringnewlineorEOF.
However, to avoidbuffer overflowerrors and to avoid security risks, its safe... |
I have few weeks searching how to create a UML class diagram for a project.
The system will manage users and roles of users for access and maintain active session after login.
What type of relation can I implementate between the classes?Are this class correct?Will I need other classes?
Thanks in Advance!
|
I'll take a shot at this. Session object has a composition association with User. (Can't have a user without a session, can't have a session without a user.) User has a composition association with Roles. (Can't have a user without roles, etc.) Session constructor creates user object, user constructor creates one... |
Now, when I print each element in my block array, each one has the same address. For example:
```
ints: 20 bytes stored at 0xbffa84fc
doubles: 80 bytes stored at 0xbffa84fc
chars: 8 bytes stored at 0xbffa84fc
Students: 1008 bytes stored at 0xbffa84fc
```
|
```
blk->addr = &blk;
```
The address of the allocated memory actually isblkitself. But here, you are using&blk, i.e, the address ofblk.
|
I use aUSB GPIO device. When it was connected to PC, it created a file that was named "/dev/ttyACM0". I want to send data using termios.I run
```
int fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
```
in C code, but it didn't work.What should it be?
UPDATE
After USB device was connected to PC, I rundmesg... |
For "permission denied" error, you should run$ sudo ./exe. I did, it worked fine!
|
Let's say I have the following code:
```
typedef struct {
int numBars;
BarType *bars;
} fooType;
foo = (fooType *) malloc(sizeof(fooType));
foo->bars = (BarType *) malloc(sizeof(barType));
```
Will calling free(foo) also free the bars or do I need to do this:
```
free(foo->bars);
free(foo);
```
Intuitively, I... |
For everymallocyou need onefree. Nothing is done "automatically" for you.
Note that, contrary to your claim, you donotactually have to allocate any memory forbars, just as you don't have to allocate memory fornumBars. However, youareallocating memory for*bars.
A single star can make a big difference in C...
|
I am parsing a text-file. While parsing, I want to skip certain characters (space, line-break, comma, period). In PHP, one may check the existence of a variable in an array within_array(char, array), but things are obviously different given we are working with pointers.
I am currently writing it like this (excuse the... |
Another choice would be to usestrchrto check if a given character is in a given string:
```
if (strchr(" \n.,", c)
continue;
```
|
This question already has answers here:Position of least significant bit that is set(23 answers)Closed8 years ago.
Is there any builtin function in C that returns me the first bit equals to zero in a 32-bit integer?
I know I can check all 32-bit using a for-loop:
```
value <--- parameter (uint32_t)
for (int i=0; i<... |
Unfortunately there's no standardized C function to do this, but many C compilers offer one of their own. When you use GCC it's the_builtin_ctzfunction. When you use Microsoft Visual C it's the_BitScanForwardfunction.
If you want to write programs that compile on multiple different compilers then you end up using a... |
Can someone explain the code below? How is it reversing the order of the chars in the string?
```
void reverse_string(char *str)
{
/* skip null */
if (str == 0)
{
return;
}
/* skip empty string */
if (*str == 0)
{
return;
}
/* get range */
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for... |
It swaps the first character and the last character. Then it swaps the second character with the next to last. And so on until it's done.
|
I have been working with function pointers and structs for a personal project. When I compiled and ran my code I got an "aborted (core dumped)" error when I tried to free a pointer.
I have the following code (excluding imports):
```
typedef int (*intFunction)(int,int);
typedef struct {
int value;
intFunct... |
You only need tofreewhat you dynamically allocated (for example by usingcalloc,mallocor any function from that family).
You never allocated memory, so you do not need to free it. And passing a random pointer to thefreefunction will make it misbehave.
|
I am parsing a text-file. While parsing, I want to skip certain characters (space, line-break, comma, period). In PHP, one may check the existence of a variable in an array within_array(char, array), but things are obviously different given we are working with pointers.
I am currently writing it like this (excuse the... |
Another choice would be to usestrchrto check if a given character is in a given string:
```
if (strchr(" \n.,", c)
continue;
```
|
This question already has answers here:Position of least significant bit that is set(23 answers)Closed8 years ago.
Is there any builtin function in C that returns me the first bit equals to zero in a 32-bit integer?
I know I can check all 32-bit using a for-loop:
```
value <--- parameter (uint32_t)
for (int i=0; i<... |
Unfortunately there's no standardized C function to do this, but many C compilers offer one of their own. When you use GCC it's the_builtin_ctzfunction. When you use Microsoft Visual C it's the_BitScanForwardfunction.
If you want to write programs that compile on multiple different compilers then you end up using a... |
Can someone explain the code below? How is it reversing the order of the chars in the string?
```
void reverse_string(char *str)
{
/* skip null */
if (str == 0)
{
return;
}
/* skip empty string */
if (*str == 0)
{
return;
}
/* get range */
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for... |
It swaps the first character and the last character. Then it swaps the second character with the next to last. And so on until it's done.
|
I have been working with function pointers and structs for a personal project. When I compiled and ran my code I got an "aborted (core dumped)" error when I tried to free a pointer.
I have the following code (excluding imports):
```
typedef int (*intFunction)(int,int);
typedef struct {
int value;
intFunct... |
You only need tofreewhat you dynamically allocated (for example by usingcalloc,mallocor any function from that family).
You never allocated memory, so you do not need to free it. And passing a random pointer to thefreefunction will make it misbehave.
|
There is a pseudocode that I want to implement in C. But I am in doubt on how to implement a part of it. The psuedocode is:
```
for every pair of states qi, and qj, i<j, do
D[i,j] := 0
S[i,j] := notzero
end for
```
iandj, inqiandqjare subscripts.
how do I representD[i,J]orS[i,j]. which data structure to use... |
You can use something like
```
int length= 10;
int i =0, j= 0;
int res1[10][10] = {0, }; //index is based on "length" value
int res2[10][10] = {0, }; //index is based on "length" value
```
and then
```
for (i =0; i < length; i++)
{
for (j =0; j < length; j++)
{
res1[i][j] = 0;
res2[i][j] = 1... |
I have a data structure that supports following operations:
An item can be inserted in constant time. For that item the data structure assigns a unique positive integer.
(Clarification: assigned integer is not a function of inserted item, and user has no choice on the assigned integer. It is chosen solely by the dat... |
It's an array with a "free list."
|
This question already has answers here:Function pointer: physical or virtual address(2 answers)Closed8 years ago.
When I am using a pointer in C for a PC program, does it point to the physical or virtual address of the variable ?
```
int x = 10;
int* ptr = &x;
```
|
It depends.
If you're writing a application that will run on top of a operating system, that is, in user mode and the operating system uses virtual memory, it will point to a virtual address (or rather, it will point to a physical address but not the same physical address that will in fact be used).
If you're using ... |
Why does the following code upon running exits abruptly without printing any output???
```
FILE *file;
file=fopen("filename","r");
char *line;
while (fgets(line,1000,file)!=NULL) {
int i=0;
int l=sizeof(line);
printf("%d\n",l);
}
```
|
```
char *line;
```
this is a char pointer, not pointing to any memory..
```
fgets(line,1000,file)!=NULL
```
and here you are trying to store the string that you read fromfilein it, without allocating memory to it
to correct that, before you do thefgets()do amalloc()to allocate memory
```
line = malloc(1000);
```... |
In C how can I create a 1 byte datatype?
I wish to create an improved boolean type in C. Someone told me to use char type but I don't know how.
I made an enum with both {true, false} but now I need a datatype with 1byte long (could be 1 bit long). I don't think a struct could be useful so I have to access its fields ... |
There's already a one-byte datatype in C. It'schar(orunsigned char). You can just define a bool as a char (with typedef or #define), true as the value 1 and false as the value 0, both of types bool.
You could also use bools from <stdbool.h>, however they are not guaranteed to take 1 byte.
|
Is using fscanf when opening a file in binary mode bad? I can't seem to find anything reasonable on the Internet. I am trying to open and read a PPM file and I've foundthis, but I am not sure if using fscanf is okay? And using netpbm is not okay, yeah.
Reading this with fread seems like a pain.
|
Thescanfandfscanffunctions are for reading characters, e.g., "1234", and converting them from a string to an integer. But integers are not stored as stings in a binary file. The actual bytes of the integer itself are stored. These need to be read directly into an integer withfread.
|
So far, I can print in one column quite nicely :
```
for (i = 0 ; i < *lengthOfFile ; i++)
{
fprintf(myFile, "%d\n", thisArray[i]);
}
```
Easy enough. However, how would I go about printing in columns of ten if say I have 20 or 100 or 10000 or more numbers?
Anything would help very much, thank you!
|
You can print "%d\t" instead of "%d\n", and move the "\n" into its own print statement that only occurs when (i % 10) == 0.
|
This question already has answers here:What is the effect of extern "C" in C++?(18 answers)Closed8 years ago.
Is this legal to do? I want to export a C function, but internally that function will use a C++ class.
```
extern "C" BOOL /*BOOL==int*/ Func()
{
return someclass::getinstance()->Func(); // this is just ... |
This is perfectly legitimate. The purpose of extern "C" is to prevent Func() from getting its name mangled (decorated with type information) so that a C module can link to it using its plain name. C++ mangles names so that functions with the same name but different parameter lists can be resolved (function overloadi... |
I wrote some code and works perfectly using g++ compiler, but when I use gcc, it throws an errorUnknow type name 'Image' in void load_image(FILE*, Image*);
Here's a part of my header file:
```
struct Image {
struct FileHeader file_header;
struct InfoHeader info_header;
struct RGBQuads rgbquads;
struc... |
It seems that you are compiling the program as a C program. If so then you have to write
```
void load_image(FILE*, struct Image*);
```
Another approach is to use typedef for the structure. For example
```
typedef struct Image {
struct FileHeader file_header;
struct InfoHeader info_header;
struct RGBQua... |
I would like to know the difference between structure and union for one member data type if there is any.
|
In C: None. The famous "space-saving joke"#define struct unionis almost not a joke.
In C++98: Unions can only havePOD members, non-union classes can have arbitrary members.
In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-u... |
This
```
char str[20];
scanf("%19[^\n]s",str);
getchar(); // To remove the `\n`
printf(str);
```
and
```
char str[20];
scanf("%19[^\n]",str);
getchar(); // To remove the `\n`
printf(str);
```
produce the same results. I know that[^\n]scans until it encounters a\n. But what I could not understand is tha... |
Since you have written"%19[^\n]"you don't need the%swhich indicates it is a string.
It is already specified by the amount of characters (19) you want to read.
The statement:
```
scanf("%19[^\n]s",str);
```
expects a string and then expects anscharacter.
To answer your question: Which one should I use?
Neither on... |
I'm now trying to print a parallelogram only with while loop. I wrote some code but It's printing square instead of parallelogram. I'm used to do these things with for loops but doing it with while is unusual for me.
```
while (x < k)
{
while (y < k)
{
printf(" * ");
y++;
}
x++;
printf(" \n "... |
What you want to do is print N tabulations according to your number of line.
Try this:
```
while (x < k)
{
while (y < k)
{
printf(" * ");
y++;
}
x++;
printf(" \n");
y = 0;
while (y < x)
{
printf("\t");
y++;
}
y = 0;
}
```
|
Are these three equivalent:
```
char* p= NULL;
char* q = "";
char r[] = {'\0'};
```
I suspect the first one is different from the rest, but I'm not entirely sure.
|
I'm answering for C++ even though the OP hasalsotagged the question as C. These are two different languages. It's not a good idea to conflate them.
This declaration:
```
char* q = "";
```
used a deprecated conversion in C++03, and becameinvalidin C++11. We're now at C++14.
These two declarations:
```
char* p= N... |
```
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
c = 0;
line = 0;
word = 0;
printf("Please enter text:\n");
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
... |
```
if(ch =='\'' || ch == ' ' || ch == '\n')
{
word++;
}
```
|
I have usedthis code examplesuccessfully. Running this code returns to stdout:
```
{"sessionToken": <some string>,"loginStatus":"SUCCESS"}
```
I need to have the sessionToken string for the following requests I need to made, thus including cookie in http headers won't work for me.
I could redirect stdout to a pipe ... |
I would suggest you setup a write callback for libcurl and receive the response directly into a memory buffer instead and then you parse that to extract what you need after the request has completed.
Thegetinmemory libcurl examplesshows one way to receive data directly into a memory buffer.
|
I wrote some code and works perfectly using g++ compiler, but when I use gcc, it throws an errorUnknow type name 'Image' in void load_image(FILE*, Image*);
Here's a part of my header file:
```
struct Image {
struct FileHeader file_header;
struct InfoHeader info_header;
struct RGBQuads rgbquads;
struc... |
It seems that you are compiling the program as a C program. If so then you have to write
```
void load_image(FILE*, struct Image*);
```
Another approach is to use typedef for the structure. For example
```
typedef struct Image {
struct FileHeader file_header;
struct InfoHeader info_header;
struct RGBQua... |
I would like to know the difference between structure and union for one member data type if there is any.
|
In C: None. The famous "space-saving joke"#define struct unionis almost not a joke.
In C++98: Unions can only havePOD members, non-union classes can have arbitrary members.
In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-u... |
This
```
char str[20];
scanf("%19[^\n]s",str);
getchar(); // To remove the `\n`
printf(str);
```
and
```
char str[20];
scanf("%19[^\n]",str);
getchar(); // To remove the `\n`
printf(str);
```
produce the same results. I know that[^\n]scans until it encounters a\n. But what I could not understand is tha... |
Since you have written"%19[^\n]"you don't need the%swhich indicates it is a string.
It is already specified by the amount of characters (19) you want to read.
The statement:
```
scanf("%19[^\n]s",str);
```
expects a string and then expects anscharacter.
To answer your question: Which one should I use?
Neither on... |
I'm now trying to print a parallelogram only with while loop. I wrote some code but It's printing square instead of parallelogram. I'm used to do these things with for loops but doing it with while is unusual for me.
```
while (x < k)
{
while (y < k)
{
printf(" * ");
y++;
}
x++;
printf(" \n "... |
What you want to do is print N tabulations according to your number of line.
Try this:
```
while (x < k)
{
while (y < k)
{
printf(" * ");
y++;
}
x++;
printf(" \n");
y = 0;
while (y < x)
{
printf("\t");
y++;
}
y = 0;
}
```
|
Are these three equivalent:
```
char* p= NULL;
char* q = "";
char r[] = {'\0'};
```
I suspect the first one is different from the rest, but I'm not entirely sure.
|
I'm answering for C++ even though the OP hasalsotagged the question as C. These are two different languages. It's not a good idea to conflate them.
This declaration:
```
char* q = "";
```
used a deprecated conversion in C++03, and becameinvalidin C++11. We're now at C++14.
These two declarations:
```
char* p= N... |
```
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
c = 0;
line = 0;
word = 0;
printf("Please enter text:\n");
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
... |
```
if(ch =='\'' || ch == ' ' || ch == '\n')
{
word++;
}
```
|
I have usedthis code examplesuccessfully. Running this code returns to stdout:
```
{"sessionToken": <some string>,"loginStatus":"SUCCESS"}
```
I need to have the sessionToken string for the following requests I need to made, thus including cookie in http headers won't work for me.
I could redirect stdout to a pipe ... |
I would suggest you setup a write callback for libcurl and receive the response directly into a memory buffer instead and then you parse that to extract what you need after the request has completed.
Thegetinmemory libcurl examplesshows one way to receive data directly into a memory buffer.
|
How can I get a makefile of my C program that will build/compile my program and generates an
executable.This executive should be able to run my c program???
|
Save the makefile asmakefileorMakefile:
```
.PHONY: all
all : progname
progname: all-objects
```
.PHONYto mark the targetallas not a file-targetallis the first and thus default-target, depends onprogname(Just somake allworks)prognamedepends on all the object-files, and will thus link them together.The object-files a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.