question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I executed following piece of code:
```
int a[] = {5,1,15,20,25};
int i,j,m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
```
and I got output as follow :-
```
3 2 15
```
The part which I don't understand is how I got value ofias3
It should be2right?
Or is it related with C compiler's right to l... |
Them = a[i++]line incrementedifor a second time, from 2 to 3.
|
I roughly read
http://linux.die.net/man/2/forkandhttp://linux.die.net/man/3/fork
got confused.
can anybody briefly explain to me difference between fork(3) and fork(2)
thank you
|
fork(2) is the kernel call and fork(3) is the posix library call
|
I'm trying to read each character from a file and print it to the screen using getc and putc alone. Here's my code,
```
FILE *fp = fopen("new.txt","r+");
rewind(fp);
while( feof(fp) == 0 )
{
putc( getc(fp) , stdout);
}
```
When ever I execute this, it runs into an infinite loop. I can't understand how this hap... |
Looping whilefeofreturns zero is almostnevercorrect.
Instead you might want to read from the inputandcheck that the input function didn't fail in one expression:
```
int ch;
while ((ch = getc(fp)) != EOF)
putc(ch, stdout);
```
This reads a character usinggetc, checks that the reading was successful by comparing... |
If I run the following:
```
int tokenIdx=ERROR; //ERROR=8
tokens[tokenIdx] = 57; //tokens is of type int[]
int totalTokens = 100;
int percent = (int)((100.0 * tokens[tokenIdx])/(float)totalTokens);
printf("%d%\n",percent);
int percent2 = (int)(100.0*(tokens[tokenIdx]/(1.0*totalTokens)));
printf("%d%\n",percent2);
``... |
Because 5700.0 and 100.0 can both be represented exactly as floating point numbers, and their ratio is exactly 57.0. On the other hand, 57.0/100.0 cannot be represented exactly as a floating pointer number, and multiplying it by 100.0 will not produced exactly 57.0. If it produces slightly less than 57.0 (as seems to ... |
In how many ways a variable can be multiplied by 8 in a c program ? I know
```
1. a*8
2. a<<8 ?
```
Are there any more alternative ways ?Its a technical aptitude test question.
|
a<<8is not the same asa * 8.
a<<1is equivalent toa*2.a<<2is equivalent toa*4.a<<3is equivalent toa*8.a<<8is equivalent toa*256.
If you really want other ways, some pedantic stuff:
```
a+a+a+a + a+a+a+a
a<<1 + a<<1 + a<<1 + a<<1
a<<2 * 2
2*(a<<1 + a<<1)
2*(a<<1)*2
a*2*2*2
a*(2<<2)
a*(4<<1)
```
|
Doint const *aandconst int *amean that "a is a integer pointer to a constant value" and "a is a pointer to a constant address", respectively , or is it viceversa?
This was asked to me in an interview. After reading a lot about the same I am still very much confused regarding it.
|
When theconsthops over the type keyword (int), the meaning doesn't change.
The meaning changes when theconsthops over the*.
```
const int *a; /* The int is const */
int const *b; /* The int is const */
int *const c; /* The pointer is const */
```
|
So I have this function where we calculate the distance between two points in a 2D array.
double distance( int p1[], int p2[] );is the header of our distance formula. My question about this is: What exactly am I sending into the function? I think that I'm sending in an array to the function, so the function call woul... |
```
double distance( int p1[], int p2[] );
```
is equivalent to
```
double distance( int *p1, int *p2 );
```
It means that your function is expecting a pointer toint. You need to pass address of the (first) element of your arrays as argument to this function.
|
I want to know, if I can change the SIFT descriptors dimension , if so how can I do it. I know currently the dimension is 128, can we make is 128*4 or 124/4 something like this?
Update: I tried to change the SIFT_DESCR_WIDTH to 2, from 4 in opencv / modules / nonfree / src / sift.cpp , but it doesn't change the dime... |
You cannot change SIFT dimensions in OpenCV without changing the OpenCV source. So you have to change sources and recompile whole OpenCV or nonfree module.
Change that constant value, then do cmake & make for OpenCV.
P.S. Actually, it wouldn`t change a lot for you - checkoriginal SIFT paper, figure 8.
|
If I want to write a C statement equivalent to ARM assembly instructions:
```
mov r0, #2
```
Do I write it as a function? (i.e.):
```
myfunc1
mov r0, #2
bx lr
```
Or do I write it this way:
```
asm("mov r0, #2)
```
|
Writing assembly inline for C depends on compiler extensions. How exactly you do it will be specific to the compiler you use.
For gcc, theconstruct to use is
```
asm ( assembler template
: output operands /* optional */
: input operands /* optional */
: list o... |
I need to retrieve the path of a parent process, by just looking at the child process.
The parent process is DEAD, meaning the parent process created the child process, and then the parent process exited.
So I am another process, who has the handle to the child process, and I need to know who created this process(th... |
Once a process has exited, and all handles to it have been closed, the system forgets everything about it. There is no way to retrieve this information in the scenario described.
|
I am trying to understand the compilation process of a C program. The pre-processed program was given to the compiler (to create obj file). The compiler will check for compilation errors. But somewhere I read that code segment, data segment will be created by the compiler and places the corresponding entries in to tho... |
As you mentioned, the text and data segments (and technically the BSS) are generated by the compiler. The text contains program code, the data contains global and static data. Those are all part of your binary image on disk.
The stack and the heap are not created by the compiler, but rather allocated at runtime -- th... |
This question already has answers here:Division in C++ not working as expected(6 answers)Closed9 years ago.
Helo, I'm new to programming and run into an issue, I have an integer, for example 158, and I divide it by 100 that i get is 1, but I want 1.58 instead
It is probably known issue, but sorry, I'm noob, for now ... |
Just cast this to float number
```
int i = 158;
float f = (float)i / 100; //less precision
double d = (double)i / 100; //more precision
//other way
int i = 158;
float f = i / 100.0; //less precision
double d = i / 100.0; //more precision
```
What you are doing is dividing integer from integer, in this case resul... |
What's the error in this program?
```
int checkok(onesquare_board[5][5], int x, int y) {
if (board [x][y]. color != 0) {
printf("sorry, another piece here \n");
return 0; /*if this is true, then validmove will take the value 0*/
}
else {
return 1; /*if this... |
Multiple syntax errors:
```
int checkok(onesquare_board[5][5], int x, int y) {
^^^^^^^^^^^^^^^--- no type given for array
if (board [x][y]. color != 0) {
^^^^^^---different variable name used
```
|
I'm trying to read each character from a file and print it to the screen using getc and putc alone. Here's my code,
```
FILE *fp = fopen("new.txt","r+");
rewind(fp);
while( feof(fp) == 0 )
{
putc( getc(fp) , stdout);
}
```
When ever I execute this, it runs into an infinite loop. I can't understand how this hap... |
Looping whilefeofreturns zero is almostnevercorrect.
Instead you might want to read from the inputandcheck that the input function didn't fail in one expression:
```
int ch;
while ((ch = getc(fp)) != EOF)
putc(ch, stdout);
```
This reads a character usinggetc, checks that the reading was successful by comparing... |
If I run the following:
```
int tokenIdx=ERROR; //ERROR=8
tokens[tokenIdx] = 57; //tokens is of type int[]
int totalTokens = 100;
int percent = (int)((100.0 * tokens[tokenIdx])/(float)totalTokens);
printf("%d%\n",percent);
int percent2 = (int)(100.0*(tokens[tokenIdx]/(1.0*totalTokens)));
printf("%d%\n",percent2);
``... |
Because 5700.0 and 100.0 can both be represented exactly as floating point numbers, and their ratio is exactly 57.0. On the other hand, 57.0/100.0 cannot be represented exactly as a floating pointer number, and multiplying it by 100.0 will not produced exactly 57.0. If it produces slightly less than 57.0 (as seems to ... |
In how many ways a variable can be multiplied by 8 in a c program ? I know
```
1. a*8
2. a<<8 ?
```
Are there any more alternative ways ?Its a technical aptitude test question.
|
a<<8is not the same asa * 8.
a<<1is equivalent toa*2.a<<2is equivalent toa*4.a<<3is equivalent toa*8.a<<8is equivalent toa*256.
If you really want other ways, some pedantic stuff:
```
a+a+a+a + a+a+a+a
a<<1 + a<<1 + a<<1 + a<<1
a<<2 * 2
2*(a<<1 + a<<1)
2*(a<<1)*2
a*2*2*2
a*(2<<2)
a*(4<<1)
```
|
Doint const *aandconst int *amean that "a is a integer pointer to a constant value" and "a is a pointer to a constant address", respectively , or is it viceversa?
This was asked to me in an interview. After reading a lot about the same I am still very much confused regarding it.
|
When theconsthops over the type keyword (int), the meaning doesn't change.
The meaning changes when theconsthops over the*.
```
const int *a; /* The int is const */
int const *b; /* The int is const */
int *const c; /* The pointer is const */
```
|
So I have this function where we calculate the distance between two points in a 2D array.
double distance( int p1[], int p2[] );is the header of our distance formula. My question about this is: What exactly am I sending into the function? I think that I'm sending in an array to the function, so the function call woul... |
```
double distance( int p1[], int p2[] );
```
is equivalent to
```
double distance( int *p1, int *p2 );
```
It means that your function is expecting a pointer toint. You need to pass address of the (first) element of your arrays as argument to this function.
|
I was already told to use glib but I'm not allowed to upgrade glib.
So I can't use this code:
```
GMainLoop* loop = g_main_loop_new (NULL, FALSE);
g_timeout_add_seconds (5, mainLoop, &data);
g_timeout_add_seconds (15*60, editTree, &data);
g_main_loop_run (loop);
```
Is there any alternative how can I call 2 function... |
g_timeout_add_secondswas added in glib-2.14, butg_timeout_addandg_timeout_add_fullhave been around since at least 2.0. They take milliseconds instead of seconds, so just multiply by 1000 and you should be fine.
|
If I have a macro like
```
#define MYMACRO(x) printf ("%any\n", x);
```
is there any%anyformatter which can print anything, context-dependently?
Non-standard or GNU C specific are OK.
|
Update: Rewritten to focus more on the macro aspect.
If you limit yourself to a single argument, it's doable inC11usinggenerics. The linked-to page has an example, the gist of which is to use generics to map the type of the argument to the proper formatting string.
I don't want to "re-print" the entire blog post, bu... |
I have two functions,
```
//virDomain is some struct
int virDomainCreate(virDomain*);
int virDomainDestroy(virDomain*);
```
How do I assign these two functions to a variable?
I tried,
```
int (*func)(virDomain*) = NULL;
func = virDomainCreate(virDomain*); // not working
func = &virDomainDestroy(virDomain*); //not ... |
You can just assign the pointer to the function like:
```
func = &virDomainCreate;
```
Or you can just use the short format:
```
func = virDomainCreate;
```
|
For this assignment I want my program to output the requested output. My issue lies in the formatting.Link to the problem in question:
The output of the program:
For whatever reason my x value is not increasing by a factor of ten and as far as the spacing is concerned I am not sure what I am doing wrong.
```
#incl... |
The spacing is because only outer loop is executing which contains printf
|
I have a C library compiled in different versions. I'm creating a symbolic link, for my python program, to the particular version of the library I want. Is there a way of getting the version of the library that's being loaded into python?
Here's how I'm loading the C library
```
import os
import ctypes as C
path ... |
You could resolve the symbolic link (see readlink) or if the library provides a version variable/function, use that after it has loaded.
|
OK, so I downloaded Codeblocks and I already have a cygwin terminal on my computer that I regularly use to compile and run C programs, but when I try to build a program in CodeBlocks, it gives me an error:
The compiler's setup (GNU GCC Compiler) is invalid, so Code::Blocks cannot find/run the compiler.
I don't know ... |
I faced the same problem. I have fixed out by going toSetting->Compiler->Global Compiler Settings->Toolchain Execuatables (tab). There, click onProgram Filesand then renameC compilertogcc.exeandC++ compilertog++.exe.
|
When reading aboutconst_castI came across sentences like the following:
Only the following conversions can be done with const_cast. In particular, only const_cast may be used to cast away (remove) constness or volatility.1) Two possiblymultilevel pointersto the same type may be converted between each other, regardles... |
Is it just a pointer to a pointer, or pointer to a pointer to a pointer, e.g.int **orint ***?
It is exactly this, yes.
|
This question already has answers here:Please explain the comma operator in this program(3 answers)What does the comma operator , do?(8 answers)Closed9 years ago.
For the following code:
```
int main(void) {
int x = 1000, y = 5000;
printf ("%d\n", x, y);
printf ("%d\n", (x, y));
return 0;
}
```
Outp... |
its aboutoperator precedence.in case of (x,y) first statement inside () is evaluated so the last value y is taken as result from (). without () all comma operators have equal precedence so evaluation takes from left to right so x value is taken for printf()
|
For example, to call MessageBox all I need is to include windows.h, so I assume some header file does the actual LoadLibrary.
How does this work?
|
The Windows header file that declaresMessageBoxdeclares it but does not define it. In other words, the header file merely declares that there is a function with a particular prototype that is defined somewhere else.
The definition is provided by an import library. ForMessageBox, that import library isuser32.lib. That... |
In my book, it has been written that*p[3] declares p as an array of 3 pointers. I got it. But for (*p)[3] it has been written that(*p)[3] declares p as a pointer to an array of three elements. What does it mean? There is no example for(*p)[3]. Can anybody give me an example of it??
|
```
int a[3] = {1,2,3};
int (*p)[3];
p=&a;
printf("%d %d %d",(*p)[0],(*p)[1],(*p)[2]);
```
At first you will have to understand the difference betweena and &a.Valueof botha and &awill besame. But There is huge difference in the meaning of them. Herearepresent thefirst elementof anarrayi.e.&a[0]and&arepresent the ... |
I'm writing a linker for Windows PE format object files, and I've got to the stage where it can link together object files produced by the Microsoft compiler, but when I try to link with libcmt.lib I get a lot of duplicate symbols.
For example,coslis defined by three different objects in the library. All three refer ... |
As referenced in the comments, the OP is not processing the COMDAT section properly.http://download.microsoft.com/download/e/b/a/eba1050f-a31d-436b-9281-92cdfeae4b45/pecoff.doc
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q... |
you have to create a keyboard hook. seeSetWindowsHookEx
|
Running the following code will print outorld. What is happening here? What exactly does&(p[*(i + j)])do?
```
#include <stdio.h>
char p[] = "HelloWorld";
int i[] = {2,1,3,5,6}, j = 4;
int main()
{
printf(&(p[*(i + j)]));
return 0;
}
```
|
```
char p[] = "HelloWorld";
int i[] = {2,1,3,5,6}, j = 4;
```
&(p[*(i + j)])is evaluated as below:
hereiis thebase addressofarray i. Thusi+4will be theaddressof thefifth elementin thearray i.*(i+j)will be equal to6.P[6]will beoafterW.&(p[*(i + j)])would beequalto&p[6]. Thus inprintfyou are passing theaddress of oan... |
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.Closed9 years ago.Improve this question
i written small code like addition for two numbers in python.
```
addition.py
def add(a,b):
c=a+b... |
Readingthe Python manual,
```
#include <Python.h>
int main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("import addition\naddition.add(42, 42)\n");
Py_Finalize();
return 0;
}
```
might do what you want.
|
I read from many question here in SO and some other articles regarding free() function in c that frees the memory of unused variables. In my case, I have the following code block.
```
char *injectStrAt(char *str, char *strToIn, int pos)
{
char *strC = malloc(strlen(str) + strlen(strToIn) + 1);
strncpy(strC, ... |
strCis the return value of this function, so you don't callfree(strC)inside the function itself. You need to free it outside the function, the time when this string is not used anymore.
|
Extending the questionWhat happens if the first part of an if-structure is false?
for C programming
```
if((NULL!=b)&&(query(&b)))
```
In the above code will the part "query(&b)" is executed if b=Null?
And is the behavior consistent across compilers?
|
No, logical operators in C will short-circuit.
If you attempt to evaluatea && bwhenais false,bis not evaluated.
But keep in mind that you're not checkingbwith that original statement, rather you're checkinga. Also note that it's safe to take the address of a variable that's NULL, you just can't dereference it.
I su... |
This question already has answers here:Is there a printf converter to print in binary format?(58 answers)Closed9 years ago.
I have a pointer returned from malloc. Which points to first byte of allocated size. For EX:
```
void* p=malloc(34);
```
How to print the binary values contained in those 34 bytes. ?
|
You probably want this :
```
int i ;
void* p=malloc(34);
for (i = 0; i < 34; i++)
{
unsigned char c = ((char*)p)[i] ;
printf ("%02x ", c) ;
}
```
It doesn't print in binary (010011011) but in hexadecimal, but that's probably what you want.
But as stated in the comments you will get garbage values.
|
Just started to learn the nested loop logic in C Programming, and i don't know how to achieve in C Programming, the length and row should follow the input number, and use '-' to separate data
```
Enter number: 2
-1-3
----
Enter number: 7
-1-3-5-7-9-1-3
--------------
-1-3-5-7-9-1-3
--------------
-1-3-5-7-9-1-3
----... |
```
#include <stdio.h>
int main(){
int i,j,n;
printf("Enter number: ");
scanf("%d", &n);
for(i=0;i<n;++i){
for(j=0;j<2*n;++j){
if(i%2==0 && j%2==1)
printf("%d", j % 10);
else
printf("-");
}
printf("\n");
}
return ... |
I want to conditionally use either printf() or a statement:
```
#define USE_PRINTF
#ifdef USE_PRINTF
#define macrofn(str) printf(str)
#else
#define macrofn(str) some_statement
#ifndef USE_PRINTF
```
But I'm getting the following error:
```
incompatible implicit declaration of built-in function 'printf'
```
What a... |
You don't necessarily have to include the<stdio.h>before the macro definition. What you really need is#endiffor the#ifyou have started. For example, the following programme will work all fine:
```
#define USE
#ifdef USE
#define asd printf("asd")
#else
#define asd puts("kek")
#endif
#include<stdio.h>
int main( ) {
... |
Can I use the "IN" operator in C?
For instance, in searching an array, can I say:
```
if(a in array[i])
{
printf("%d \n", array[i]);
}
```
In Python, we may say this.
|
There's no built-in C syntax that does this. You can write a function that does. Ie, ifarray[i]is an array ofints:
```
int in(int n, int* arr, int len) {
int i;
for (i = 0; i < len; ++i) {
if (arr[i] == n) {
return 1;
}
}
return 0;
}
```
In some contexts such a function might already exist in t... |
When not providing new data buffer to playback device, it repeats previously given data buffer.
How to overcome this?
triedsnd_pcm_dropandsnd_pcm_prepare. but didn't helped.
in sw params i have used,snd_pcm_sw_params_set_start_threshold()- to start playback when available frames are >= threshold value. and same assn... |
Thanks to this fantastic post.
Fixed my issue.
http://www.spinics.net/linux/fedora/alsa-user/msg09906.html
|
Is there a way to find out if a file write occurred in c. I'm supposed to return a 0 if I wrote to the file and -1 if nothing was written.
|
If you're usingfwrite(), for example, the return code is the number of items written.
Similarly,fprintf()returns the number of characters written.
So you can examine the return code to figure out if anything was written, something like:
```
if (fprintf (fh, "val=%d\n", value) == 0)
return -1;
return 0;
```
or:... |
I am having problems with using a camera in OpenGL/freeGLUT. Here is my code:
http://pastebin.com/VCi3Bjq5
(For some reason, when I paste the code into the code feature on this site, it gives extremely weird output.)
As far as I can tell this should rotate the camera when arrow keys are pressed - but it does nothi... |
The display function is only called once. You need to either set an idle function with glutIdleFunc() or tell GLUT that the display function must be called again with glutPostRedisplay().
|
I am trying to solve this problem and I need your help.
I have this code...
```
while(a != EOF){
scanf("%f",&a);
...
}
```
...and I want to terminate this loop by pressing CTRL+D. It works but I need to press it two times. I tried to use this
```
while(getchar() != EOF){
scanf("%f",&a);
...
}
```
but the ... |
You can check for EOF directly in scanf:
```
while (scanf("%f",&a) != EOF) {
...
}
```
For more information, read the docs on scanf (an exampleof them).
|
I'm trying to associate numbers between two arrays, and one of the arrays contains 500 numbers. Some of the numbers contain 2 decimal places, while others contain 3. How do i read off the numbers as is.
I triedprintf("%.3f",floatvar);but it only displayed correctly when the number DID have 3 decimal places. It howeve... |
Did you tryprintf("%g",floatvar);?. Anyway,printf("%.3f",floatvar)should add a trailing 0 for numbers with 2 decimals though.
|
I'm just starting with socket programming in UNIX and I was reading the man pages for the socket system call. I'm a bit confused about the AF_LOCAL argument and when it is used. The manual just says local communication. Wouldn't an AF_INET format also work for local communication?
|
AF_LOCALuses UNIX domain sockets which are local to the filesystem and can be used for internal communications.AF_INETis an IP socket.AF_LOCALwill not incur some performance penalties related to sending data over IP. See thisold but very nice discussionof the topic.
|
I have a quite large C application consisting of several shared libraries. One of the core libraries has a function
```
void common_function(const char * arg) { ... }
```
Which is called by all the other libraries. During testing I would like to use a different test implementation of thecommon_function.
My plan has... |
ReadDrepper's paper: How To Write Shared Librariesand wikipage ondynamic linker.
You probably want to play theLD_PRELOADtrick(assuming all your libraries are shared, not static).
|
I searched on theopen standards website, particularly theC working group homepagebut only found information about C11.
They seem to have regular meetings and discuss different features and extensions, but they never actually mention a future C standard nor roadmap. It is hard to tell whether they are working on a new... |
I sent an email to the guy on the WG 14 contact section but I didn't expect to get an answer anytime soon, however, I did.
This is what he replied to me:
the Committee has not discussed starting work on a new revision of the
Standard. WG 14 will be meeting in Parma Italy the first part of
April, and so far ther... |
I am working I C with two structures: Car and List
```
#define MAX_LEN 10
#define NUM 7
typedef struct{
char nr[NUM];
char model[MAX_LEN];
char categ[];
}Car;
#define LEN 100
typedef struct{
Car elem[LEN];
int n;
}List;
```
I want to add elements of typecarinto theList. I have tried
```
vo... |
```
void add(List* l, Car c){
strcpy(l->elem[l->n].nr,c.nr);
strcpy(l->elem[l->n].model,c.model);
strcpy(l->elem[l->n].categ,c.categ);
l->n= l->n + 1;
}
```
|
How can I compare a character withchar*character in c ?
Below is my case.
```
char *str = "this is testing"
for (i=0; i<strlen(str); i++)
{
if (strcmp(str[i], 't') == 0)
printf("%c\n", str[i]);
}
```
|
To just compare one character, you don't needstrcmp-- you can do it yourself.
```
if (str[i] == 't') {
```
For that matter, you don't needstrleneither -- since C strings are null-terminated, you can just iterate until you see the NUL value, thus doing one pass through the string rather than two (the first being with... |
I have a quite large C application consisting of several shared libraries. One of the core libraries has a function
```
void common_function(const char * arg) { ... }
```
Which is called by all the other libraries. During testing I would like to use a different test implementation of thecommon_function.
My plan has... |
ReadDrepper's paper: How To Write Shared Librariesand wikipage ondynamic linker.
You probably want to play theLD_PRELOADtrick(assuming all your libraries are shared, not static).
|
I searched on theopen standards website, particularly theC working group homepagebut only found information about C11.
They seem to have regular meetings and discuss different features and extensions, but they never actually mention a future C standard nor roadmap. It is hard to tell whether they are working on a new... |
I sent an email to the guy on the WG 14 contact section but I didn't expect to get an answer anytime soon, however, I did.
This is what he replied to me:
the Committee has not discussed starting work on a new revision of the
Standard. WG 14 will be meeting in Parma Italy the first part of
April, and so far ther... |
I am working I C with two structures: Car and List
```
#define MAX_LEN 10
#define NUM 7
typedef struct{
char nr[NUM];
char model[MAX_LEN];
char categ[];
}Car;
#define LEN 100
typedef struct{
Car elem[LEN];
int n;
}List;
```
I want to add elements of typecarinto theList. I have tried
```
vo... |
```
void add(List* l, Car c){
strcpy(l->elem[l->n].nr,c.nr);
strcpy(l->elem[l->n].model,c.model);
strcpy(l->elem[l->n].categ,c.categ);
l->n= l->n + 1;
}
```
|
How can I compare a character withchar*character in c ?
Below is my case.
```
char *str = "this is testing"
for (i=0; i<strlen(str); i++)
{
if (strcmp(str[i], 't') == 0)
printf("%c\n", str[i]);
}
```
|
To just compare one character, you don't needstrcmp-- you can do it yourself.
```
if (str[i] == 't') {
```
For that matter, you don't needstrleneither -- since C strings are null-terminated, you can just iterate until you see the NUL value, thus doing one pass through the string rather than two (the first being with... |
I have a quite large C application consisting of several shared libraries. One of the core libraries has a function
```
void common_function(const char * arg) { ... }
```
Which is called by all the other libraries. During testing I would like to use a different test implementation of thecommon_function.
My plan has... |
ReadDrepper's paper: How To Write Shared Librariesand wikipage ondynamic linker.
You probably want to play theLD_PRELOADtrick(assuming all your libraries are shared, not static).
|
I searched on theopen standards website, particularly theC working group homepagebut only found information about C11.
They seem to have regular meetings and discuss different features and extensions, but they never actually mention a future C standard nor roadmap. It is hard to tell whether they are working on a new... |
I sent an email to the guy on the WG 14 contact section but I didn't expect to get an answer anytime soon, however, I did.
This is what he replied to me:
the Committee has not discussed starting work on a new revision of the
Standard. WG 14 will be meeting in Parma Italy the first part of
April, and so far ther... |
I am working I C with two structures: Car and List
```
#define MAX_LEN 10
#define NUM 7
typedef struct{
char nr[NUM];
char model[MAX_LEN];
char categ[];
}Car;
#define LEN 100
typedef struct{
Car elem[LEN];
int n;
}List;
```
I want to add elements of typecarinto theList. I have tried
```
vo... |
```
void add(List* l, Car c){
strcpy(l->elem[l->n].nr,c.nr);
strcpy(l->elem[l->n].model,c.model);
strcpy(l->elem[l->n].categ,c.categ);
l->n= l->n + 1;
}
```
|
How can I compare a character withchar*character in c ?
Below is my case.
```
char *str = "this is testing"
for (i=0; i<strlen(str); i++)
{
if (strcmp(str[i], 't') == 0)
printf("%c\n", str[i]);
}
```
|
To just compare one character, you don't needstrcmp-- you can do it yourself.
```
if (str[i] == 't') {
```
For that matter, you don't needstrleneither -- since C strings are null-terminated, you can just iterate until you see the NUL value, thus doing one pass through the string rather than two (the first being with... |
Im having problems with the following code:
```
int main(void)
{
char *pointer;
int num, i;
printf_s("Enter number of elements: ");
scanf_s("%d", &num);
pointer = (char*) malloc(sizeof(char) * num);
for (i = 0; i < num; i++, pointer++)
scanf_s(" %c", pointer);
pointer -= num;
for (i = 0; i < num; i++)
printf_s("%... |
Change:
```
scanf_s(" %c");
```
To:
```
scanf_s("%c");
```
And while you're at it (although not directly related to the problem at hand), get rid of themalloc:
```
int main(void)
{
char c;
scanf_s("%c", &c);
printf_s("%c", c);
return 0;
}
```
|
Here's my code:
1. User types in two names, with a space in between. This means that two strings need to be read. I.e. input:
John Doe.
The strings are then checked in a char-array. (works fine).The while loop goes on until the user types "stop" - only "stop".
How can I make it to stop directly if "stop" is ente... |
I suggest you usefgetsto get the input, check for the"stop"string, and then usesscanfto parse the input.
|
This question already has answers here:What does the comma operator , do?(8 answers)C comma operator(4 answers)Closed9 years ago.
Compiled using GCC on a Fedora 20 Desktop, the following code outputs 10.
```
int x=10;
int y=5;
printf("%d",(y,x));
```
|
In C,(y,x)means evaluatingxandyand returning onlyx. EG. From wikipedia:
the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
|
I'm new to programming and I want to know how to check if the user input is within my condition. For example, the program only accepts inputs which are below 25.
Here is my code. But it isn't working. :(
```
for(i=1; i<=5; i++);
{
if(act[i]<25)
{
scanf("%d", &act[i]);
}
}
```
|
This code is not working because you are trying to evaluate the if conditionif(act[i]<25)beforeact[i]is actually received from the user.
What you need is this:
```
for(i=1;i<=5;i++)
{
again:
scanf("%d",&act[i]);
if(!(act[i]<25))
{
printf("Invalid input! Enter again..\n");
goto again:
... |
```
int main(){
int rem, N, dig, i;
printf("Enter a number: ");
scanf("%d", &N);
while (N > 0){
N /= 10;
dig += 1;
}
int D[dig] = {0};
```
So I'm writing a program where a person enters a number (ex. 276433) and I must count the number of times a number appears (but that's not what I need help with), Sinc... |
you have to write
```
int D[dig];
```
without
```
={0}
```
and it will work;
This is the only way to allocate an array with a variable integer without malloc !
|
```
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
```
I came across this on codegolf
Please explain the usage of?and:and why is there no statement following the while loop? As in why is there a;after the parenthesis.
|
There is a boolean operation going on inside the parentheses of the while loop:
```
while (boolean);
```
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. ... |
As we know, the C can open the /dev file node by the Linux system API. Like this:
```
int fd = open("/dev/hello", O_RDONLY|O_NONBLOCK);
```
So , is there any way to do this using JAVA without JNI ?
Thanks.
|
Yes, since on Unix "everything is a file". You just open/dev/hellolike you open your file/home/jerikc/some.txt...
Perhaps your question is how to passO_NONBLOCKtoopen(2)syscall in Java....
|
currently I'm using this command to compile my .c files in Mint
```
gcc -std=gnu99 -Wall -Werror filename.c -o filename [-lm]
```
How do I make these parameters default, perhaps include them in themake filename.ccommand? Thanks :)
|
You need to write makefile like
```
CC = gcc
EXEC = filename
OBJS = filename.o \
FLAGS = -std=gnu99 -Wall -Werror
LDLIBS = -lm
all: $(EXEC)
$(EXEC): $(OBJS)
$(CC) $(FLAGS) -o $@ $(OBJS) $(LDLIBS)
clean:
-rm -f $(EXEC) *.o
```
Then run make to compile your file
|
I have this 64 byte character arraybuf.
I am trying to dereference the value at byte[4] as an little-endian integer. But what I get out is not equivalent to the bytes when I look character by character.
See below for the behavior that is confusing me:
```
(gdb) p &buf + 4
$106 = (char (*)[64]) 0xbffff8c8
// These ... |
Remember that pointer arithmetic takes the size of the data type into account. Since the size ofbufis 64 bytes,&buf + 4is a pointer to memory 4*64=256 bytes after&buf.
To get a pointer tobuf[4]use&buf[4].
|
I am using Mac OS X 10.8 with Xcode. I have installed thejanssonlibrary, with the following commands:
```
./configure
make
make check
sudo make install
```
Everything went fine and the library installed correctly. I have created a smple.cfile with a text editor and tried to include the<jansson.h>file. I builded ever... |
I resolved the issue, by going underBuild phases, and searching forHEADER_SEARCH_PATH. Then I changed the search path label with/usr/local/include, where the library was installed.
|
How do I change the following code so that it also goes through files instead of just stdin?
For example the program would work if I do./detag blahwhere blah is a text file?
Do I use an if statement and try tocatit?
```
int main() {
int in_tag = 0;
char c;
while ((c = getchar()) != EOF) {
if (c == ... |
A simple way is to change how you invoke it, and use redirection e.g.
```
$ ./detag < blah
```
will feed the contents of blah into your program viastdin, and consequently you don't need to change any code.
Otherwise you'll have to definemain()usingargv and argv. If you want it to processmultiplefiles then this woul... |
Hi I have a simple MakeFile that contains this in it:
```
clean:
rm -f ex1
```
but when i run commandmake clean, i get the following error:
```
make: *** No rule to make target `clean'. Stop.
```
I am not sure what I am doing wrong, its only 2 lines and the 2nd line is started with a TAB not Spaces. anybody h... |
MakeFileshould be namedMakefile. Remove the capital F.
|
I am creating a video player using SDL and I am using C-programming language. In my main function, I create a “for loop” and display the video. After the last video frame is displayed I keep my display window up. When I try to close the window with top-right “X” button, it does not close the window, as there is no cal... |
Just put that into your main loop for Event Handling, if you don't handle QuitEvent, your window will not be closeable by pressing on the X.
```
SDL_Event evt;
while(SDL_PollEvent(&evt))
{
switch(evt->type)
{
case SDL_QUIT:
//your quit procedure
break;
}
}
```
|
I have a bitmap stocked as a unsigned char array, containing only 1 and 0; like this:
```
0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1
```
I wish to stock this in a compact way, so I wrote a function to convert this into hexadecimals. I'll stock this like:
```
0f33
```
My question now: with which function can I convert these c... |
Try this for C++:
```
int number;
std::stringsteam ss;
ss << std::hex << *characterPointer;
ss >> number;
```
For C:
```
char hexstr[2] = {*characterPointer, '\0'};
int number = (int)strtol(hexstr, NULL, 16);
```
|
i have a C console application that write a text to a file:
```
FILE *f;
f = fopen("out", "w");
fprintf(f, "%s","My Text");
rewind(f);
fclose(f);
```
when i run it from explorer it works fine, but when i run it using another application the file does not create and the text not saved
even with the administrator... |
Youroutfile is a relative path and it may be set e.g. to your third-party application directory. Or maybe it changes its current directory to something else and it results your app savingoutthere? If you're not sure, you can always try to pass absolute path to youroutfile.
|
How to get address of a pointer inc/c++?
Eg: I have below code.
```
int a =10;
int *p = &a;
```
So how do I get address of pointerp?
Now I want to print address of p, what should I do?
print("%s",???) what I pass to ???.
|
To get the address of p do:
```
int **pp = &p;
```
and you can go on:
```
int ***ppp = &pp;
int ****pppp = &ppp;
...
```
or, only in C++11, you can do:
```
auto pp = std::addressof(p);
```
To print the address in C, most compilers support%p, so you can simply do:
```
printf("addr: %p", pp);
```
otherwise you n... |
At the momemt, i'm learning the C and the basics of the language, but I have a problem with my code. When I multiply two numbers, I cant get the decimals, even I float the numbers I enter.
My code:
```
int main()
{
double result_met, km;
result_met = km = 0.0f;
/*Display text*/
printf("Enter values... |
The format specifiers are incorrect - it should be%lf-%dis forint.
```
scanf_s("%lf", &km);
/*Formular for a simple km conversion*/
result_met = km * 1000.0f;
/*Result print*/
printf("Meter:%lf", result_met);
```
Format string specifications
|
i wanted to make a program for wget which asks you from which URL you want do download and then download, but i don't know how to add the string "wget" and the url and put it in the system() command. I know there are several possibilities to add strings, but nothing worked for me. Could you please help me? (The code s... |
scanf("%s", &url);strip of&ersand as it is not required.urlitself is base address of the array needed for scanf().
Arrays basically decays to pointers, so there is no need to use the&operator on an array to get a pointer. It can be dangerous if you think you have an array but actually have a pointer.
|
my scanf statement is giving seg fault. could you please tell me why?
```
typedef struct message1
{
int call_id1;
int lac;
long int attribute;
int conn_id;
struct message1 *next1;
}M1;
M1 *last=NULL;
main()
{
printf("\nEnter Call Id\t");
scanf("%d",&last->call_id1);
}
```
|
your trying to read into a struct which is not allocated memory
add
M1 *last = malloc(sizeof(struct message1)); // in global space
or
last =malloc(sizeof(struct message1)); // in main function
|
I am using Mac OS X 10.8 with Xcode. I have installed thejanssonlibrary, with the following commands:
```
./configure
make
make check
sudo make install
```
Everything went fine and the library installed correctly. I have created a smple.cfile with a text editor and tried to include the<jansson.h>file. I builded ever... |
I resolved the issue, by going underBuild phases, and searching forHEADER_SEARCH_PATH. Then I changed the search path label with/usr/local/include, where the library was installed.
|
How do I change the following code so that it also goes through files instead of just stdin?
For example the program would work if I do./detag blahwhere blah is a text file?
Do I use an if statement and try tocatit?
```
int main() {
int in_tag = 0;
char c;
while ((c = getchar()) != EOF) {
if (c == ... |
A simple way is to change how you invoke it, and use redirection e.g.
```
$ ./detag < blah
```
will feed the contents of blah into your program viastdin, and consequently you don't need to change any code.
Otherwise you'll have to definemain()usingargv and argv. If you want it to processmultiplefiles then this woul... |
Hi I have a simple MakeFile that contains this in it:
```
clean:
rm -f ex1
```
but when i run commandmake clean, i get the following error:
```
make: *** No rule to make target `clean'. Stop.
```
I am not sure what I am doing wrong, its only 2 lines and the 2nd line is started with a TAB not Spaces. anybody h... |
MakeFileshould be namedMakefile. Remove the capital F.
|
I am creating a video player using SDL and I am using C-programming language. In my main function, I create a “for loop” and display the video. After the last video frame is displayed I keep my display window up. When I try to close the window with top-right “X” button, it does not close the window, as there is no cal... |
Just put that into your main loop for Event Handling, if you don't handle QuitEvent, your window will not be closeable by pressing on the X.
```
SDL_Event evt;
while(SDL_PollEvent(&evt))
{
switch(evt->type)
{
case SDL_QUIT:
//your quit procedure
break;
}
}
```
|
I have a bitmap stocked as a unsigned char array, containing only 1 and 0; like this:
```
0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1
```
I wish to stock this in a compact way, so I wrote a function to convert this into hexadecimals. I'll stock this like:
```
0f33
```
My question now: with which function can I convert these c... |
Try this for C++:
```
int number;
std::stringsteam ss;
ss << std::hex << *characterPointer;
ss >> number;
```
For C:
```
char hexstr[2] = {*characterPointer, '\0'};
int number = (int)strtol(hexstr, NULL, 16);
```
|
i have a C console application that write a text to a file:
```
FILE *f;
f = fopen("out", "w");
fprintf(f, "%s","My Text");
rewind(f);
fclose(f);
```
when i run it from explorer it works fine, but when i run it using another application the file does not create and the text not saved
even with the administrator... |
Youroutfile is a relative path and it may be set e.g. to your third-party application directory. Or maybe it changes its current directory to something else and it results your app savingoutthere? If you're not sure, you can always try to pass absolute path to youroutfile.
|
How to get address of a pointer inc/c++?
Eg: I have below code.
```
int a =10;
int *p = &a;
```
So how do I get address of pointerp?
Now I want to print address of p, what should I do?
print("%s",???) what I pass to ???.
|
To get the address of p do:
```
int **pp = &p;
```
and you can go on:
```
int ***ppp = &pp;
int ****pppp = &ppp;
...
```
or, only in C++11, you can do:
```
auto pp = std::addressof(p);
```
To print the address in C, most compilers support%p, so you can simply do:
```
printf("addr: %p", pp);
```
otherwise you n... |
At the momemt, i'm learning the C and the basics of the language, but I have a problem with my code. When I multiply two numbers, I cant get the decimals, even I float the numbers I enter.
My code:
```
int main()
{
double result_met, km;
result_met = km = 0.0f;
/*Display text*/
printf("Enter values... |
The format specifiers are incorrect - it should be%lf-%dis forint.
```
scanf_s("%lf", &km);
/*Formular for a simple km conversion*/
result_met = km * 1000.0f;
/*Result print*/
printf("Meter:%lf", result_met);
```
Format string specifications
|
i wanted to make a program for wget which asks you from which URL you want do download and then download, but i don't know how to add the string "wget" and the url and put it in the system() command. I know there are several possibilities to add strings, but nothing worked for me. Could you please help me? (The code s... |
scanf("%s", &url);strip of&ersand as it is not required.urlitself is base address of the array needed for scanf().
Arrays basically decays to pointers, so there is no need to use the&operator on an array to get a pointer. It can be dangerous if you think you have an array but actually have a pointer.
|
my scanf statement is giving seg fault. could you please tell me why?
```
typedef struct message1
{
int call_id1;
int lac;
long int attribute;
int conn_id;
struct message1 *next1;
}M1;
M1 *last=NULL;
main()
{
printf("\nEnter Call Id\t");
scanf("%d",&last->call_id1);
}
```
|
your trying to read into a struct which is not allocated memory
add
M1 *last = malloc(sizeof(struct message1)); // in global space
or
last =malloc(sizeof(struct message1)); // in main function
|
This question already has answers here:What is the difference between int* ptr and int *ptr in C? [duplicate](5 answers)Closed9 years ago.
I have seen,
```
int *pnum;
int * pnum;
int* pnum;
```
Are these all the same?
|
Yes, all those three are the same. And in them, that*is notdereferencing operator, it is part of the typeint *, pointer toint.
|
so I built a very basic program according to The C Programming Language book, but when I run it, it keeps asking input after I enter one, the loop should ended when there are no inputs longer right? or Am I wrong? srry for my bad english
```
int main()
{
long nc;
nc = 0;
while ( getchar() != EOF) {
+... |
Your loop is expecting an EOF character to terminate, not just an empty string. *nix consoles typically translate aCtrl-Don an empty line as EOF, in Windows I believe it'sCtrl-Zbut I could be wrong.
|
I'm looking at the openjdk source files and I'm wondering where I could find the .c file which is at the root of the Java Virtual Machine. In other words, where/what is the file which contains themain? Is there such a thing?
EDIT: I think I'm going to feel dumb in a moment. Is it just the filejava.c? Because when you... |
If you have the source there's smarter ways to find main.
One dumb way:
```
grep -R main *.c
```
(A little trickier to set up recursive grep right - I'm more used togit grep).
Someone more fluent in C can propose better ways...
|
```
int b = 0xf ^ 0xc;
printf("value is %04X", b);
```
Output is:
```
value is 0003
```
I know that the decimal value of the xor operation between1111and1100is3although I want integerbto be printed out in hex.
|
0003 is a hexadecimal value; a hexa digit has values between 0..F
|
I am working with huge files. (>>>2gb). the question I have is it safe to use fileno() on the file descriptor if the file is larger than sizeof(int) is?
Here a quick code snippet:
```
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <inttypes.h>
int readstuff(FILE *fp,uint64_t seekpoint, uint64_t seekwid... |
The file descriptor returned byfileno()is anint, regardless of the size of the file that it is used to open.
|
Create partial of a given string using pointers in C.
Lets say I have the following string:
```
char string[] = "hellomynameisbob";
```
and I wanted hello out of it:
interface:
```
char * partial(int i, int j, char *string){
...
}
```
Wherejis where I want my word to start at andiis where I want my word to end a... |
Thepartialfunction is better written with an argument pointing to the buffer where you want the partial string to be copied. Otherwise it will have to dynamically allocate memory and the caller will have to free it, which is confusing.
```
// buf shall have size at least j - i + 2
char* partial(int i, int j, const ch... |
The title is the question: when a thread exits, does its cached memory get flushed to the main memory?
I am wondering because cases are common where the main thread creates some threads, they do some work on independent parts of the array (no data dependencies between each other), the main thread joins all the worker... |
The pthreads specification requires thatpthread_join()is one of the functions that"synchronizes memory with respect to other threads", so in the case of pthreads you are OK - afterpthread_join()has returned, the main thread will see all updates to shared memory made by the joined thread.
|
I have a C program
```
#include<stdio.h>
void f(const int* p)
{
int j;
p = &j;
j = 10;
printf("Inside function *p = %d\n",*p);
*p = 5;
printf("Inside function *p = %d\n",*p);
j = 7;
printf("Inside function *p = %d\n",*p);
}
int main()
{
int i = 20, *q = &i;
f(q);
}
```
Compilation of the progra... |
const int *pmeans that you can't modify the integer thatpis pointing to usingp, as in*p = 5;. The integer it points to may not be aconst int, which is whyj = 10works. This prevents coders from modifying integer being pointed to.
|
This question already has answers here:What is the difference between int* ptr and int *ptr in C? [duplicate](5 answers)Closed9 years ago.
I have seen,
```
int *pnum;
int * pnum;
int* pnum;
```
Are these all the same?
|
Yes, all those three are the same. And in them, that*is notdereferencing operator, it is part of the typeint *, pointer toint.
|
so I built a very basic program according to The C Programming Language book, but when I run it, it keeps asking input after I enter one, the loop should ended when there are no inputs longer right? or Am I wrong? srry for my bad english
```
int main()
{
long nc;
nc = 0;
while ( getchar() != EOF) {
+... |
Your loop is expecting an EOF character to terminate, not just an empty string. *nix consoles typically translate aCtrl-Don an empty line as EOF, in Windows I believe it'sCtrl-Zbut I could be wrong.
|
I'm looking at the openjdk source files and I'm wondering where I could find the .c file which is at the root of the Java Virtual Machine. In other words, where/what is the file which contains themain? Is there such a thing?
EDIT: I think I'm going to feel dumb in a moment. Is it just the filejava.c? Because when you... |
If you have the source there's smarter ways to find main.
One dumb way:
```
grep -R main *.c
```
(A little trickier to set up recursive grep right - I'm more used togit grep).
Someone more fluent in C can propose better ways...
|
For example if I received the following ASCII value: 123456
How would I combine two digits into a byte? So my bytes become like this ...
```
byte1 = 0x12;
byte2 = 0x34;
byte3 = 0x56;
```
Thanks!
|
This is called BCD (binary-coded decimal).
```
char s[] = "123456";
byte1 = (s[0] - '0') * 0x10 + (s[1] - '0');
```
|
I'm just curious, does Objective-C compile into C code or does the Objective-C runtime work like a layer of abstraction above the program? Sorry in advance if I don't know what I'm talking about!
|
A little history lesson:
Both C++ and Objective C originally started out as preprocessors for C. So you typed in your ObjC code, and it would effectively run a search-and-replace over the code and translate the Objective-C commands into straight C code that used a little helper library (the stuff in objc/runtime.h an... |
```
1. struct thread_args
{
2. int thread_id;
3. struct timeval before;
4. struct timeval after;
}
5. void * foobar(void *threadargs)
{
6. struct * mydata;
7. mydata = (struct thread_args *) threadargs;
8. gettimeofday(&mydata->before, NULL);
9. gettimeofday(mydata->before, NULL);
}
...
`... |
foo->bar= value contained by variablebarin struct variablefoo.
&foo->bar= address of variablebarin struct variablefoo.
See thisoperator precedence table.
gettimeofday()requires first argument of typestruct timeval *. Sogettimeofday(mydata->before, NULL);does not compile.
|
I am trying to parse a HTTP request header. I need to pickup the first line:
GET / HTTP/1.1
However, the output for the code below is:
```
Method: (null)
Filename: (null)
Version: (null)
Client hostname: (null)
```
Why?
Code:
```
char *token;
const char delimiter[2] = " ";
token = strtok(NULL, delimiter)... |
The first time you call strtok you need to provide the string you want to split as the first argument. Subsequent calls to strtok need to use NULL as the first argument to get subsequent delimited strings.
Good luck.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.