question
stringlengths
25
894
answer
stringlengths
4
863
I have a question like this: Which of the following is the correct datatype for the variable like this: ``` a = 23.5 a) float b) double c) long double d) None ``` According to me, it should be double. Because, if we ``` float a = 23.5 ``` Then, actually, we are initializing a float variable by a double constant....
It depends on what type you need forato be in your program logic, not what type of value it's initialized. Yes,float a = 23.5;, there is a conversion from thedoubleliteral23.5to thefloatvariablea, but it's fine. For instance, to initialize adoublevariable to42.0, people usually use ``` double a = 42; ``` in which42...
Let us consider an array (say,int a[25];). Later with the help of some loop I start storing the user input in this array. At some point of time if user choose to delete the value he just entered from the array. How can I do that for the user of my program. I can make that 0, but 0 is also a value he could enter; so...
You can't delete an element from an array. In C arrays are stored as a contiguous block of memory, so you can't just remove an element. You can use any of the following options: Use some unused value like-1to mark the element as deleted.Use separate array to keep track of deleted elements.Use linked list to store you...
``` test ecx,ecx jns 00400000 ``` is this assembly code equivalent to this c code? ``` int ECX; if((ECX>>31)==1){..} ``` if not how can I make it equivalent? Thanks for your help.
Based the Wikipedia entry for thetest instruction, the test will set the sign flag of the flags register based on the most significant bit of the registerecx. Therefore, the jump is taken iff theMSBis not set as you have seen. Your complementCcode is almost equivalent, but depending on whether>>does a logical or arit...
How should this be parsed in C language? ``` 1000 ``` (if octal012* 10 ^ 2) or ``` 1200 ``` (if entire number as decimal)?
A constant with an exponent is always floating-point. There are no octal floating-point constants in C. (There are hexadecimal floating-point constants, but this isn't one of them). So012e2is an unnecessarily confusing way to write1200.0. (I can think of no good reason to write it this way, unless the intent is to ...
So, this is a output based question: The code is: ``` #include <stdio.h> int main() { char ch; if ((ch=printf( ""))) printf("It matters\n"); else printf("It doesnt matter\n"); return 0; } ``` Why the output is It doesnt matter? What exactly is being tested in the if statement? Secondly, in ...
printf()returns the number of characters written. When called with a an empty format string (""), that value will of course be 0, which will be considered "false" by theif, and thus theelsebranch is taken. And no, you certainly can'tswitch()on strings in C.
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed9 years ago. I was experimenting some stuff with pointers in my school today when i found that the following code would output ``` 1 2 3 4 5 6 7 8 9 ``` Here is the code: ``` int foo[10]; int i; for (i = 0; i...
This is becausei[foo]is interpreted by your compiler as*(i + foo)which is the same thanfoo[i] ( *(foo +i) ). So your are printing thefoo[i]'s Note that*(foo + i)does point to the correct address because of the pointer arithmetic system. When you add a number A to a pointer, your are actually addingA*sizeof(*your_point...
I have a lot of global variables whose name is very long, e.g: ``` var1.var2.var3.var4.myGlobalVar1[N] ``` And I must use this variables in my function. My question is what is the best way to manipulate this variable? is it necessary to do a copy into a local variable to increase the readability?
if you only want to increase the readability, you can use ``` #define SHORTER_NAME var1.var2.var3.var4.myGlobalVar1[N] ``` if it is an array you can use ``` #define SHORTER_NAME var1.var2.var3.var4.myGlobalVar1 ``` to access each value withSHORTER_NAME[index]
This question already has answers here:void main() { if(sizeof(int) > -1) printf("true"); else printf("false"); ; [duplicate](3 answers)Closed9 years ago. Please have a look at the following code: ``` #include<stdio.h> int main() { if(sizeof(int)>-1) { printf("Condition evaluates to true !"); } ...
You need to cast the return ofsizeofto int in order for the evaluation to be valid: ``` if((int)(sizeof(int)) > -1) ``` Look at the return type ofsizeof
My code looks like this: ``` char source[] = "the wrong son"; char output[80]; int i, j = 0; for ( i = 0; source[i]; i++ ) if ( i < 4 || i >= 10 ) output[j++] = source[i]; output[j] = '\0'; ``` Why can't I replace a string with other string like this: ``` source = output; ``` Instead of doing it a l...
In Cstringis not considered as primitive data type.hence,your statement won't fit! Had,strings been independent and primitive data-types,you would have easily done it.But,this is restricted and against the C language specifications. You'll have to go through the first way! Alternatively,you can also go forstrcpy()me...
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 ``` FILE *fptr1; char str[10]; fptr1=fopen("D:\\New Folder\\test.txt","rb") //Now I want to replace text.t...
There is no such way that you can directly edit whatfptr1contains. ``` FILE *fptr1; char str[10]; //char fileName[50] = "test.txt"; char path[500] = strcat("D:\\New Folder\\","test.txt"); fptr1=fopen(path,"rb"); ```
I have two different independent files opened in vim editor with buffersb1pointing toabc.candb2pointing toxyz.c. Each of them are in different folders and are having different Makefiles. Is it possible to executemakecommand in both the buffers for their respective files? Currently If I openabc.cfrom its respective ...
One way to do this is to:set autochdir(or one one of the other options:http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file) so that:makewill run in the same directory as the source file.
In Linux kernel 2.4.18, the network layer representation of the socket which is the sock struct has fields such assaddr,sport,daddr,dport, which represent the source and destination IP address (port). However, in kernel 2.6.18 these fields have been removed. I am trying to modify a module based on 2.4.18 kernel, does ...
I think you need to cast your struct sock to a struct inet_sock... ``` struct inet_sock *inet; inet = inet_sk(sock); inet->daddr, inet->dport, etc. ```
This question already has answers here:How can I convert an integer to a hexadecimal string in C?(7 answers)Closed9 years ago. I tried to convert dec to hex. For example convert 255 to hex. opa = 255.ToString("X"); gives me error: error: invalid suffix "ToString" on floating constant I spent lots of time to conver...
You're asking about the wrong language. C does not support the dot operator on integers. To do this in C, you need to print it to a string like so. ``` char numstr[10]; sprintf(numstr, "%X", 255) ```
For having a standalone binary purpose I want to mount a payload in the RAM declaring its content int by int with something like this ``` int *payloadptr = malloc(10*sizeof(int)); payloadptr[0] = 0x11223344; payloadptr[1] = 0x55667788; ``` This data setter script is generated automatically, I chose to do it int by i...
The byte 'mix' as you say is caused by your CPU endianness. I assume you have an Intel-based CPU which architecture is Little Endian. I suggest you read about endianness herehttp://en.wikipedia.org/wiki/Endianness. A little endian architecture will cause int to be stored from the LSB to the MSB which will then invert ...
I have been going through some RTOS example code (a slightly old version of Keil RTX, if anyone's interested) and I came across some syntax I didn't understand: ``` void job1 (void) __task; void job2 (void) __task; ``` This was giving errors (error: #130: expected a "{"), so changed the example code to this: ``` v...
It's not C, it a Keil compiler extension to C. _taskkeyword tells the compilernot to add the function entry and exit code. Read your compiler documentation to get more information.
This question already has an answer here:What does the following for loop syntax mean in C?(1 answer)Closed9 years ago. For example, ``` for (;;) { //do something } ``` How is this different from ``` { //do something } ```
It's an infinite loop. Pretty much the same as writing ``` while (true) { // do something } ```
I have to enterchars in C. Input is of the form: ``` 'f' 'g' 'd' 'b' '2' '3' ``` Each line has a pair of two characters, and my task is to store them in two different arrays. One array will store {'f','d','2'} and the other will store {'g','b','3'}. My code is this: ``` for(i=0;i<n;i++){ scanf(" %c",&arr1...
Your code looks fine except you need space before%cin secondscanftoo: ``` for(i=0;i<n;i++){ scanf(" %c",&arr1[i]); scanf(" %c",&arr2[i]); } ``` A space before%cinscanfcan skip any number ofwhite-spaces. In absence of it, secondscanfreads the white-spaces and store that inarr2. ==>Live Demo.
Well, I'm getting this error and couldn't identify when i'm trying acess the fields. In my bnum.c, i have the declaration of my struct: ``` #include "bnum.h" struct num { char *vet; int tam; }; ``` And in my bnum.h, I have: ``` typedef struct num *b_num; ``` And in the main file I have: ``` ...
The main file does not have access to the structure definition, hence the error. You should move the definition ``` struct num { char *vet; int tam; }; ``` from .c to .h.
I haven't practiced C in a while but is there a way to shorten this statement: ``` if(!(argv[i] == '+' || argv[i] == '-' || argv[i] == '/' || argv[i] == '*')){ } ``` Is it a proper syntax to do something like this: ``` argv[i] == '+’,’-’,’*’,’%’ ; ```
No, your suggestion is not valid syntax. There is no "magic" way. What I'd do is one or more of Shorten the left-hand side, by doing e.g.const char op = argv[i];then just havingopin theif.Usestrchr(), your expression then becomesif(strchr("+-/*", argv[i]) == NULL(this is like Python'sif argv[i] in "+-/9":).Refactor ...
I'm working on a larger project, and a lot of the .cpp files are including files that are in different directories, but there are no references of accessing other directories in the code. Thanks for the help.
No. Usually you give the compiler (or, more specifically, the preprocessor) a bunch of include directories, to tell it where to look for header files. This is typically done from the Makefile (or from the project settings when building inside an IDE). Exactly how the option looks is of course up to each compiler. Wi...
According tothispage a valid hex-sequence is\xfollowed by one digit only. How does\x61can work? rather, I expected the output be\x6decoded and the1value itself into string like"\x61"but it output the\x61decoded. What am I missing?
You're missing the second expansion. The full definition is: ``` hexadecimal-escape-sequence: "\x" hexadecimal-digit hexadecimal-escape-sequence hexadecimal-digit ``` So the minimal escape sequence is "\x" followed by a single digit, but you can extend the escape sequence by adding as many digits as you li...
This question already has answers here:void main() { if(sizeof(int) > -1) printf("true"); else printf("false"); ; [duplicate](3 answers)Closed9 years ago. Please have a look at the following code: ``` #include<stdio.h> int main() { if(sizeof(int)>-1) { printf("Condition evaluates to true !"); } ...
You need to cast the return ofsizeofto int in order for the evaluation to be valid: ``` if((int)(sizeof(int)) > -1) ``` Look at the return type ofsizeof
My code looks like this: ``` char source[] = "the wrong son"; char output[80]; int i, j = 0; for ( i = 0; source[i]; i++ ) if ( i < 4 || i >= 10 ) output[j++] = source[i]; output[j] = '\0'; ``` Why can't I replace a string with other string like this: ``` source = output; ``` Instead of doing it a l...
In Cstringis not considered as primitive data type.hence,your statement won't fit! Had,strings been independent and primitive data-types,you would have easily done it.But,this is restricted and against the C language specifications. You'll have to go through the first way! Alternatively,you can also go forstrcpy()me...
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 ``` FILE *fptr1; char str[10]; fptr1=fopen("D:\\New Folder\\test.txt","rb") //Now I want to replace text.t...
There is no such way that you can directly edit whatfptr1contains. ``` FILE *fptr1; char str[10]; //char fileName[50] = "test.txt"; char path[500] = strcat("D:\\New Folder\\","test.txt"); fptr1=fopen(path,"rb"); ```
I have two different independent files opened in vim editor with buffersb1pointing toabc.candb2pointing toxyz.c. Each of them are in different folders and are having different Makefiles. Is it possible to executemakecommand in both the buffers for their respective files? Currently If I openabc.cfrom its respective ...
One way to do this is to:set autochdir(or one one of the other options:http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file) so that:makewill run in the same directory as the source file.
In Linux kernel 2.4.18, the network layer representation of the socket which is the sock struct has fields such assaddr,sport,daddr,dport, which represent the source and destination IP address (port). However, in kernel 2.6.18 these fields have been removed. I am trying to modify a module based on 2.4.18 kernel, does ...
I think you need to cast your struct sock to a struct inet_sock... ``` struct inet_sock *inet; inet = inet_sk(sock); inet->daddr, inet->dport, etc. ```
This question already has answers here:How can I convert an integer to a hexadecimal string in C?(7 answers)Closed9 years ago. I tried to convert dec to hex. For example convert 255 to hex. opa = 255.ToString("X"); gives me error: error: invalid suffix "ToString" on floating constant I spent lots of time to conver...
You're asking about the wrong language. C does not support the dot operator on integers. To do this in C, you need to print it to a string like so. ``` char numstr[10]; sprintf(numstr, "%X", 255) ```
For having a standalone binary purpose I want to mount a payload in the RAM declaring its content int by int with something like this ``` int *payloadptr = malloc(10*sizeof(int)); payloadptr[0] = 0x11223344; payloadptr[1] = 0x55667788; ``` This data setter script is generated automatically, I chose to do it int by i...
The byte 'mix' as you say is caused by your CPU endianness. I assume you have an Intel-based CPU which architecture is Little Endian. I suggest you read about endianness herehttp://en.wikipedia.org/wiki/Endianness. A little endian architecture will cause int to be stored from the LSB to the MSB which will then invert ...
I have been going through some RTOS example code (a slightly old version of Keil RTX, if anyone's interested) and I came across some syntax I didn't understand: ``` void job1 (void) __task; void job2 (void) __task; ``` This was giving errors (error: #130: expected a "{"), so changed the example code to this: ``` v...
It's not C, it a Keil compiler extension to C. _taskkeyword tells the compilernot to add the function entry and exit code. Read your compiler documentation to get more information.
This question already has an answer here:What does the following for loop syntax mean in C?(1 answer)Closed9 years ago. For example, ``` for (;;) { //do something } ``` How is this different from ``` { //do something } ```
It's an infinite loop. Pretty much the same as writing ``` while (true) { // do something } ```
I've already installed CMake, but I haven't undertood how to use The visualizer Toolkit!I have done a .dat file with C and I want to make a .vtk file.
A .vtk structured grid looks like this : ``` # vtk DataFile Version 2.0 Really cool data ASCII DATASET STRUCTURED_GRID DIMENSIONS 2 2 1 POINTS 4 float 0 0 0 0 0 2 0 1 0 0 1 1 POINT_DATA 4 SCALARS volume_scalars char 1 LOOKUP_TABLE default 1 2 3 4 ``` Using the toolkit is not absolutely mandatory to write such a file...
How can I codetest al,alin c language? I've triedif((n & 0xFF) & 0){}but this is not correct. Thanks.
I'm guessing that you're checking the zero flag next, i.e.jzor similar. In that case you'd want ``` if ((n & 0xFFFF) != 0) { ``` Note that AX is 16-bit not 8 bit (as e.g. AL and AH are) so you want 0xFFFF not 0xFF (if you even need this restriction)& 0can only ever give= 0and so false.
Say I have a python script that opens a file to write: The python modules also call C modules that change the directory with ``` chdir() ``` Will the python script still have the file open and be able to write?
Files are tracked by file handles, and once open for a particular file, stays open to that file until closed.
I want to call an address that is determined by other configuration result. And that call is in an inline assembly. Currently, it's like this and is manually modified: ``` asm volatile ("call 0xc0200c20\n\t"); ``` My question is can I write it like this? ``` #define CALL_ADDR 0xC0200c20 asm volatile ("call CALL_A...
Just ordinary string concatenation should do the trick, with two wrapper macros to create a stringified version of the value: ``` #define QUAUX(X) #X #define QU(X) QUAUX(X) asm volatile ("call " QU(CALL_ADDR) "\n\t"); ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed9 years ago.Improve this question Can you explain to me what does this statementx^=ydo in C ?I already know that the...
It's a shortcut operation, just like ``` x += 1; // same as x = x + 1 x ^= y; // same as x = x ^ y ```
I've already installed CMake, but I haven't undertood how to use The visualizer Toolkit!I have done a .dat file with C and I want to make a .vtk file.
A .vtk structured grid looks like this : ``` # vtk DataFile Version 2.0 Really cool data ASCII DATASET STRUCTURED_GRID DIMENSIONS 2 2 1 POINTS 4 float 0 0 0 0 0 2 0 1 0 0 1 1 POINT_DATA 4 SCALARS volume_scalars char 1 LOOKUP_TABLE default 1 2 3 4 ``` Using the toolkit is not absolutely mandatory to write such a file...
I am having a bit of trouble understanding the difference between these two.. are both of these a pointer to a pointer?? and also, what are the appropriate cases in which each of them would be ideal to use??
``` struct node *hash1[MAXSIZE]; struct node **hash2 = hash1; ``` The first creates an array of MAXSIZE elements, but each element is a pointer to astruct node. The second creates a single variable, a pointer to a pointer, which is initialized with the address of the zeroth pointer in thehash1. You might use the se...
This question already has answers here:Constants and compiler optimization in C++(12 answers)Closed9 years ago. Do modern compilers optimize a piece of code likeif(CONSTANT) { ... }, whereCONSTANTis a literal, template argument,constvariable orconstexprvariable? Do they remove the wholeif(0) { ... }expression or "thr...
This is not guaranteed but most compilers of good quality will do it. C99 Rationale says in 6.4.9: if (0) { /* code to be excluded */ }Many modern compilers will generate no code for this if statement. For example withgcc(in C) an assembly dump shows that dead code with eitherif (0) .. elseorif (1) .. elseis optim...
Since i'm new in the programming world ,i'm facing little problem while writting program for this pattern .I tried many times but the result is not what i wanted ? The pattern is : ``` 1 23 456 78910 ``` What i have written is :- ``` #include<stdio.h> #include<conio.h> void main() { int num = 1 , j ...
``` #include <stdio.h> int main() { printf("1\n23\n456\n78910\n"); return 0; } ``` produces the output you desire
I would normally declare and initialize an array of integers like so: ``` int a[3] = { 1, 2, 3}; // declares an array of 3 integers ``` But today it occurred to me to wrap the list in parentheses as well, like so: ``` int a[3] = ( { 1, 2, 3} ); // gives compile time error ``` Which produced the following compiler ...
It's simply not valid syntax. Here are the relevant sections of the grammar from the C99 standard: [6.7] init-declarator: declarator declarator = initializer [6.7.8] initializer: assignment-expression { initializer-list } { initializer-list , }
I am trying to add nodes to a tree with this function. I have use a array of character pointers for the input data. To insert I am incrementing the pointer each time. ``` node addToTree(node root , char *words[]) { int count=0; while( *(words+2)) { printf("\n VALLED %d",count++); root=addNode(root,*words); ...
You're iterating through the pointers inwordsand checking for a zero pointer, but you didn't add a sentinel at the end of the array. Try this: ``` char *words[] = {"3", "8", "1", NULL}; ... while (*words) ``` Presumably,words + 2worked because there happened to be something in memory at that location that equated to...
This question already has an answer here:Why is "\?" an escape sequence in C/C++?(1 answer)Closed9 years ago. I was readingthisand found the escape\?. What does means exactly this escape? the literal?inside a string(I still can't see a reason) or is this a BNF grammar rule which I don't know about?
It specifies a literal question mark. seehttp://en.wikipedia.org/wiki/Digraphs_and_trigraphs The backslash is used as a marker character to tell the compiler/interpreter that the next character has some special meaning. What that next character means is up to the implementation. For example C-style languages use\nto ...
I am trying to find a way to track an arbitrary point in x,y,z after applying transformations. Something like this ``` glTranslated(0,2,4); glScaled(3,4,5); glTranslated(2,4,5); glRotated(24,0,1,0); point = Point(3,4,2) printf ("the point is now in %f,%f and %f",point.x,point.y,point.z); ``` I am using C wit...
If you don't want to replicate how OpenGL builds and combines your matrices, the easiest approach is probably to get the current matrix: ``` GLfloat mat[16]; glGetFloatv(GL_MODELVIEW_MATRIX, mat); ``` Then you can multiply this matrix with the points you want to transform. Remember that OpenGL stores matrices in col...
I know that using ``` gcc -dM -E - < /dev/null ``` can get the predifined macros ofgcc, but what does the ``` - < /dev/null ``` mean in this command? Per my understanding, there should be a option behind-. I have tried to search ongcc manual, but can't find answers.
On its own,-means "read from standard input instead of the filename that would otherwise be provided on this command-line". This is a common Unix convention. The< /dev/nullredirects standard input from/dev/null, which is of length 0. Thus GCC will read from standard input and immediately reach the end of the input,...
Suppose we write a program in C and print the address of one of the variables declared in the program, is the address that gets printed on the screen the virtual address or the physical address of the variable? If it is the virtual address, why is it that it still has the same range as a bit range of physical memory?...
The address is going to be avirtual addressinvirtual memory, because the application hasno knowledge of physical memory. That is hidden by the kernel and the MMU. I am not sure what you mean by the same "bit range". If you have a 32-bit address space it will range across the entire 32-bit space regardless of what amo...
I am having a bit of trouble understanding the difference between these two.. are both of these a pointer to a pointer?? and also, what are the appropriate cases in which each of them would be ideal to use??
``` struct node *hash1[MAXSIZE]; struct node **hash2 = hash1; ``` The first creates an array of MAXSIZE elements, but each element is a pointer to astruct node. The second creates a single variable, a pointer to a pointer, which is initialized with the address of the zeroth pointer in thehash1. You might use the se...
This question already has answers here:Constants and compiler optimization in C++(12 answers)Closed9 years ago. Do modern compilers optimize a piece of code likeif(CONSTANT) { ... }, whereCONSTANTis a literal, template argument,constvariable orconstexprvariable? Do they remove the wholeif(0) { ... }expression or "thr...
This is not guaranteed but most compilers of good quality will do it. C99 Rationale says in 6.4.9: if (0) { /* code to be excluded */ }Many modern compilers will generate no code for this if statement. For example withgcc(in C) an assembly dump shows that dead code with eitherif (0) .. elseorif (1) .. elseis optim...
Since i'm new in the programming world ,i'm facing little problem while writting program for this pattern .I tried many times but the result is not what i wanted ? The pattern is : ``` 1 23 456 78910 ``` What i have written is :- ``` #include<stdio.h> #include<conio.h> void main() { int num = 1 , j ...
``` #include <stdio.h> int main() { printf("1\n23\n456\n78910\n"); return 0; } ``` produces the output you desire
I would normally declare and initialize an array of integers like so: ``` int a[3] = { 1, 2, 3}; // declares an array of 3 integers ``` But today it occurred to me to wrap the list in parentheses as well, like so: ``` int a[3] = ( { 1, 2, 3} ); // gives compile time error ``` Which produced the following compiler ...
It's simply not valid syntax. Here are the relevant sections of the grammar from the C99 standard: [6.7] init-declarator: declarator declarator = initializer [6.7.8] initializer: assignment-expression { initializer-list } { initializer-list , }
I am trying to add nodes to a tree with this function. I have use a array of character pointers for the input data. To insert I am incrementing the pointer each time. ``` node addToTree(node root , char *words[]) { int count=0; while( *(words+2)) { printf("\n VALLED %d",count++); root=addNode(root,*words); ...
You're iterating through the pointers inwordsand checking for a zero pointer, but you didn't add a sentinel at the end of the array. Try this: ``` char *words[] = {"3", "8", "1", NULL}; ... while (*words) ``` Presumably,words + 2worked because there happened to be something in memory at that location that equated to...
Given aSecKeyRefloaded usingSecItemImportfrom an RSA private key is there a way to obtain or create aSecKeyReffor only the public key components? In OpenSSL this could be done by copying the modulus and public exponent to a new struct, butSecKeyRefis opaque and I've been unable to find a function that performs this op...
As of macOS 10.12, iOS/tvOS 10, and watchOS 3 the functionSecKeyCopyPublicKeynow exists to do this.
I've got two structures, one of which is nested into the other (Date into Video). I've got other functions that insert data into arrayVideo[0].id/title/producer just fine. However once I try to input something for arrayVideo[0].releasedate.Year/month/day it just crashes the program. No warnings during build or anythin...
Should be ``` scanf("%u", &(arrayVideo[0].releaseDate.Year)); ``` You're giving it the value, not the pointer.
Hello I am writing a program and dynamic loadable modules. Those modules are loaded using 'dlopen'. How do I use a program function in the module? Are function pointers the right way? Thank you
Yes you need function pointers and have to calldlsym()to get them
Ok,so I wrote this program and compiled it. It's everything ok, but when I run it in windows 7 it get's me an error c0000005. I have no idea why. Overview of my program I want this program to give me the sum of this numbers depends of an given "n" : 1-1x3+1x3x5-...+-1x3x5x...x(2*n-1). Please help me,I am a begginer...
You need to passaddresstoscanf: ``` scanf("%d", &n); ``` Also, yourforloop is invalid. Conditioni-(2*n-1)never changes becauseiandnnever change.
I wanted to ask the author, caf , fromUnderstanding functions and pointers in C I realized I can't ask the question on that same page. I'm still confused with using & to pass the value of pointer into a function. I always thought &q is just passing the address of q, how is it going to translate the value of q into i...
There is no "translation". Your function ``` int sqp(int *x); ``` takes one argument,x, whose type isint *, i.e. "pointer to integer". So, to call it you need to pass it a pointer to an integer, i.e. the address of an integer. The&prefix operator is used to compute the address of its argument, thus you can do: `...
This question already has answers here:pow() seems to be out by one here(4 answers)Closed9 years ago. Consider the following code: ``` #include <math.h> #include <stdio.h> int main() { printf("%f\n", pow(43,10)); } ``` This outputs: 21611482313284248.000000 Seehttp://codepad.org/eSa4ASF2for playground. But if...
In IEEE-754,double(binary-64) can represent all integers exactly up to9007199254740992(that is 2 power 53). After that not all integer numbers can be represented exactly in adouble. Your number21611482313284249is greater than9007199254740992and cannot be represented exactly in adouble.
Hello I am writing a program and dynamic loadable modules. Those modules are loaded using 'dlopen'. How do I use a program function in the module? Are function pointers the right way? Thank you
Yes you need function pointers and have to calldlsym()to get them
Ok,so I wrote this program and compiled it. It's everything ok, but when I run it in windows 7 it get's me an error c0000005. I have no idea why. Overview of my program I want this program to give me the sum of this numbers depends of an given "n" : 1-1x3+1x3x5-...+-1x3x5x...x(2*n-1). Please help me,I am a begginer...
You need to passaddresstoscanf: ``` scanf("%d", &n); ``` Also, yourforloop is invalid. Conditioni-(2*n-1)never changes becauseiandnnever change.
I wanted to ask the author, caf , fromUnderstanding functions and pointers in C I realized I can't ask the question on that same page. I'm still confused with using & to pass the value of pointer into a function. I always thought &q is just passing the address of q, how is it going to translate the value of q into i...
There is no "translation". Your function ``` int sqp(int *x); ``` takes one argument,x, whose type isint *, i.e. "pointer to integer". So, to call it you need to pass it a pointer to an integer, i.e. the address of an integer. The&prefix operator is used to compute the address of its argument, thus you can do: `...
This question already has answers here:pow() seems to be out by one here(4 answers)Closed9 years ago. Consider the following code: ``` #include <math.h> #include <stdio.h> int main() { printf("%f\n", pow(43,10)); } ``` This outputs: 21611482313284248.000000 Seehttp://codepad.org/eSa4ASF2for playground. But if...
In IEEE-754,double(binary-64) can represent all integers exactly up to9007199254740992(that is 2 power 53). After that not all integer numbers can be represented exactly in adouble. Your number21611482313284249is greater than9007199254740992and cannot be represented exactly in adouble.
``` char foo[] = "something"; char *p = foo; ``` Is there a way to change the value pointed and increment the pointer to the next element using only one ;? I mean, make the effect of these 2 lines below in a single statement? ``` *p = 'S'; p++; ```
I think you want ``` *p++ = 'S'; // as good as --> *(p++) = 'S'; ``` Sample run.
For a shared library project written in C, if I rewrite part of the code in C++, but exactly the same APIs is kept, will I have any ABI compatibility issues?
If you keep the same API (function names and parameter types) you should be good to go. What youwillneed to do is wrap your header files with this(copy & pasted fromhere): ``` #ifdef __cplusplus extern "C" { #endif // all of your legacy C code here #ifdef __cplusplus } #endif ``` This makes sure that the C++ comp...
What is the differences between, ``` #define myvariable 1.25 ``` and, ``` #define myvariable (double)1.25 ``` while declaring a preprocessor directives in C.
The difference is that the preprocessor will, when it seesmyvariable, substitute in(double)1.25rather than1.25. This will have no effect on your code (possibly bizarre edge cases notwithstanding) since1.25isalreadya double literal, as perC11 6.4.4.2 Floating constants /4: An unsuffixed floating constant has typedoub...
I have a struct that declared as follow: ``` struct a { struct b { int d; } c; }; ``` How to declare a variable ofboutsidea? In C++ I can usea::b x;. But, in C it required to specifiesstructkeyword before struct name.
C has a flat layout; when you declare a struct within another struct, the former is just being put into the global namespace. So, in your example, it is juststruct b.
I stumbled uponthisarticle about clang (I have used gcc), so I followed the instructions to compile a .c file but gave me this error: ``` clang -o File.c test ld: can't link with a main executable file 'test' for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) ``` ...
You followed the instructions wrong. You want: ``` clang -o test File.c ``` Your command is telling clang to name itsoutputFile.c, usingtestas input. As to your follow up questions: Is it gone? Yes, almost certainly. Is there any chance to get my file back? Do you keep backups?
I am new to C and am trying to figure out pointers. I tried this simple(according to me) code and keep getting a segmentation fault in GCC ``` #include<stdio.h> int main() { char c[50] = "abc"; char h[50]; char *ptr; printf("abc"); ptr = c; printf("Address stored in ptr: %p" , ptr); pri...
Change this statement ``` printf("Value of ptr: %s" , *ptr); ``` to either ``` printf("Value of ptr: %c" , *ptr); ``` or ``` printf("Value of ptr: %s" , ptr); ``` depending on what you want to see. Or use them both that to see the difference.:)
So far, I have the followingcinoptions: ``` cino= cino+=:0 cino+=g0 cino+=p0 cino+=(0 cino+={0 cino+=l1 cino+=t0 cino+=u2 ``` I would expect that the{0option would indent as: ``` case 1: { foo = 1; break; } ``` but instead it indents as: ``` case 1: { foo = 1; return; } ``` Is the...
cino+={-1s instead of cino+={0 works. Basically, the default is0swhich places it indented in.-1splaces the braces as desired.
``` #include<omp.h> #include<stdio.h> #include<stdlib.h> void main(int argc, int *argv[]){ #pragma omp parallel num_threads(3) { int tid = omp_get_thread_num(); printf("Hello world from thread = %d \n",tid); if(tid == 0){ int nthreads = omp_get_num_threads(); printf("N...
You need to compile your program with-fopenmp. ``` g++ a.cc -fopenmp ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 years ago.Improve this question The Question goes th...
As an idea. It is enough to check whether the result of the addition is less than 10 and greater than -10 if the numbers are signed.:)
I am new to C and am trying to figure out pointers. I tried this simple(according to me) code and keep getting a segmentation fault in GCC ``` #include<stdio.h> int main() { char c[50] = "abc"; char h[50]; char *ptr; printf("abc"); ptr = c; printf("Address stored in ptr: %p" , ptr); pri...
Change this statement ``` printf("Value of ptr: %s" , *ptr); ``` to either ``` printf("Value of ptr: %c" , *ptr); ``` or ``` printf("Value of ptr: %s" , ptr); ``` depending on what you want to see. Or use them both that to see the difference.:)
So far, I have the followingcinoptions: ``` cino= cino+=:0 cino+=g0 cino+=p0 cino+=(0 cino+={0 cino+=l1 cino+=t0 cino+=u2 ``` I would expect that the{0option would indent as: ``` case 1: { foo = 1; break; } ``` but instead it indents as: ``` case 1: { foo = 1; return; } ``` Is the...
cino+={-1s instead of cino+={0 works. Basically, the default is0swhich places it indented in.-1splaces the braces as desired.
``` #include<omp.h> #include<stdio.h> #include<stdlib.h> void main(int argc, int *argv[]){ #pragma omp parallel num_threads(3) { int tid = omp_get_thread_num(); printf("Hello world from thread = %d \n",tid); if(tid == 0){ int nthreads = omp_get_num_threads(); printf("N...
You need to compile your program with-fopenmp. ``` g++ a.cc -fopenmp ```
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 years ago.Improve this question The Question goes th...
As an idea. It is enough to check whether the result of the addition is less than 10 and greater than -10 if the numbers are signed.:)
IsStra "pointer" or a "pointer to pointer" inStr[3][5]? I usually declarechar **Strto make a simulated 2D array, but how to send the address ofStr[3][5]to another function, and how to set the parameter of that function in order to modify values inStr[3][5]? As far as I know, the compiler treats a 2D array as an ordi...
An array of T when used in most expressions will decay to a pointer of type "pointer to T" and have the value equal to the address of the first element of the array. IfStris declared as: ``` char Str[3][5]; ``` ThenStrwill decay tochar (*)[5], and have the value of&Str[0]. If passing to a function, you can declare ...
I get the following error when I try to deploy the KDMF Driver template to a provisioned Windows 7 host: error: Network debugging is not available for Windows versions 6.1 or earlier. I've tried updating the host by installing the latest WDK and the Windows SDK. I'm at a loss for what to do.
For a Windows 7 VM, you will need to do kernel debugging through serial. If you are using HyperV, you can simply configure a virtual COM port that goes through a named pipe. In Visual Studio, you can then configure your kernel debugger settings for serial debugging over a named pipe. Even outside of Visual Studio, th...
``` unsigned char endian[2] = {1, 0}; short x; x = *(short *) endian; ``` I don't understand the value held in x. If I have a little-endian system, x is 1. But if I have a big-endian system, x is 256. Why is the value 256 rather than 128 ? Thanks for your help.
Because the bytes01 00, in big-endian, are the value0x0100, which equals1 << 8 == 2**8 == 256(Recall there are 8 bits in a byte).
If i have an enum in a header file aheader.h as ``` enum Fruits { Apple, Orange, Guava }; ``` Can i use it in another header bheader.h as ``` #include <aheader.h> ... #define FRUIT1 Fruits.Apple ``` Is this usage correct, for whatever purpose I intend to use it for. What would be the scope changes if any?
Enum constants aren't qualified by their parent type in C, so that'd be simply: ``` #define FRUIT1 Apple ``` For this reason, it is often considered good style to prefixing the enum constants yourself to avoid name collisions. ``` enum Fruits { FRUIT_APPLE, FRUIT_ORANGE, FRUIT_GUAVA }; ```
I'm a web developer, trying to learn more about C programming. My C training is purely academic, so i thought i'd start with reading some source code on Github. My project of choice washttps://github.com/cesanta/mongoose- Mongoose Web Server, as i used it on several occasions. Browsing through the source (mongoose.c)...
There is always an entry point to anyprogram, but softwarelibrariesgenerally do not have entry points. In terms of whether the entry point is always calledmain, you can look atthis question. mongoose.cis the source code for alibrary, so there is nomainfunction. Themainfunctions are all in the clients of that library...
This question already has answers here:reusing pthread_t variable for currently running threads(3 answers)Closed9 years ago. Is it conforming for the thread-ID argument of thepthread_create()function to be on the stack if the thread is detached? For example ``` void func() { pthread_t thread; pthread_create(...
Based onthis answerto a related question, I would say it is safe even if you do not usepthread_detach. Since you will not be trying tojoinit in the future, there's no reason you need to keep it around.
I want to make a kind of Python wrapper for wkhtmltopdf, build from C/C++ sources. For this i've expected to use ctypes but wkhtmltopdf uses various structures who contain specific types like QPrinter and many others. Does anybody knows how to use non-standard ctypes fields with Python and the ctypes module ? I'm a...
I'd recommend that you use a wrapper likepy-wkhtmltoxinstead of trying to use the C API forlibwkhtmltoxvia ctypes.
IsStra "pointer" or a "pointer to pointer" inStr[3][5]? I usually declarechar **Strto make a simulated 2D array, but how to send the address ofStr[3][5]to another function, and how to set the parameter of that function in order to modify values inStr[3][5]? As far as I know, the compiler treats a 2D array as an ordi...
An array of T when used in most expressions will decay to a pointer of type "pointer to T" and have the value equal to the address of the first element of the array. IfStris declared as: ``` char Str[3][5]; ``` ThenStrwill decay tochar (*)[5], and have the value of&Str[0]. If passing to a function, you can declare ...
I get the following error when I try to deploy the KDMF Driver template to a provisioned Windows 7 host: error: Network debugging is not available for Windows versions 6.1 or earlier. I've tried updating the host by installing the latest WDK and the Windows SDK. I'm at a loss for what to do.
For a Windows 7 VM, you will need to do kernel debugging through serial. If you are using HyperV, you can simply configure a virtual COM port that goes through a named pipe. In Visual Studio, you can then configure your kernel debugger settings for serial debugging over a named pipe. Even outside of Visual Studio, th...
``` unsigned char endian[2] = {1, 0}; short x; x = *(short *) endian; ``` I don't understand the value held in x. If I have a little-endian system, x is 1. But if I have a big-endian system, x is 256. Why is the value 256 rather than 128 ? Thanks for your help.
Because the bytes01 00, in big-endian, are the value0x0100, which equals1 << 8 == 2**8 == 256(Recall there are 8 bits in a byte).
If i have an enum in a header file aheader.h as ``` enum Fruits { Apple, Orange, Guava }; ``` Can i use it in another header bheader.h as ``` #include <aheader.h> ... #define FRUIT1 Fruits.Apple ``` Is this usage correct, for whatever purpose I intend to use it for. What would be the scope changes if any?
Enum constants aren't qualified by their parent type in C, so that'd be simply: ``` #define FRUIT1 Apple ``` For this reason, it is often considered good style to prefixing the enum constants yourself to avoid name collisions. ``` enum Fruits { FRUIT_APPLE, FRUIT_ORANGE, FRUIT_GUAVA }; ```
I'm a web developer, trying to learn more about C programming. My C training is purely academic, so i thought i'd start with reading some source code on Github. My project of choice washttps://github.com/cesanta/mongoose- Mongoose Web Server, as i used it on several occasions. Browsing through the source (mongoose.c)...
There is always an entry point to anyprogram, but softwarelibrariesgenerally do not have entry points. In terms of whether the entry point is always calledmain, you can look atthis question. mongoose.cis the source code for alibrary, so there is nomainfunction. Themainfunctions are all in the clients of that library...
This question already has answers here:reusing pthread_t variable for currently running threads(3 answers)Closed9 years ago. Is it conforming for the thread-ID argument of thepthread_create()function to be on the stack if the thread is detached? For example ``` void func() { pthread_t thread; pthread_create(...
Based onthis answerto a related question, I would say it is safe even if you do not usepthread_detach. Since you will not be trying tojoinit in the future, there's no reason you need to keep it around.
I want to make a kind of Python wrapper for wkhtmltopdf, build from C/C++ sources. For this i've expected to use ctypes but wkhtmltopdf uses various structures who contain specific types like QPrinter and many others. Does anybody knows how to use non-standard ctypes fields with Python and the ctypes module ? I'm a...
I'd recommend that you use a wrapper likepy-wkhtmltoxinstead of trying to use the C API forlibwkhtmltoxvia ctypes.
I have a one-dimensional array of string literals of different lengths like so: ``` char *map[] = { "ABC", "ABCDEF", ... }; ``` I would like to change a certain character in the array withmap[y][x]='X';, which does not (and should not) work according toWikipedia. I also read that declaring it aschar map[][]would fix...
``` #include <stdio.h> #define CNV(x) (char []){ x } int main(void){ char *map[] = { CNV("ABC"), CNV("ABCDEF"), //... }; map[1][2]='c'; printf("%s\n", map[1]);//ABcDEF return 0; } ```
This question already has answers here:A question about union in C - store as one type and read as another - is it implementation defined?(6 answers)Closed9 years ago. ``` #include<stdio.h> int main() { union a { int i; char ch[2]; }; union a z = {512}; printf("%d %d",z.ch[0],z.c...
I am not sure why you expect the compiler to generate garbage for you, when you have just told it to initialize toito512. The least two significant bytes of 512 are0and2. Implementation-specific behavior is not the same as garbage.
I have a one-dimensional array of string literals of different lengths like so: ``` char *map[] = { "ABC", "ABCDEF", ... }; ``` I would like to change a certain character in the array withmap[y][x]='X';, which does not (and should not) work according toWikipedia. I also read that declaring it aschar map[][]would fix...
``` #include <stdio.h> #define CNV(x) (char []){ x } int main(void){ char *map[] = { CNV("ABC"), CNV("ABCDEF"), //... }; map[1][2]='c'; printf("%s\n", map[1]);//ABcDEF return 0; } ```
This question already has answers here:A question about union in C - store as one type and read as another - is it implementation defined?(6 answers)Closed9 years ago. ``` #include<stdio.h> int main() { union a { int i; char ch[2]; }; union a z = {512}; printf("%d %d",z.ch[0],z.c...
I am not sure why you expect the compiler to generate garbage for you, when you have just told it to initialize toito512. The least two significant bytes of 512 are0and2. Implementation-specific behavior is not the same as garbage.
``` #include <stdio.h> int main(int argc, const char *argv[]) { const char *s[] = {"a", "b", "c", NULL}; const char **p = s; while (*p != NULL) { printf("string = %s\n", *p); (*p)++; } return 0; } ``` I want to traverse the string array and print the string util come up the NULL s...
``` (*p)++; ``` Should just be: ``` p++; ``` Here's what you are doing: ``` p --> * --> "a" | ^ incrementing this checking this for null ``` You're incrementing the wrong pointer.
I am currently trying to allocate separate chunks of memory usingmallocin order not to allocate a huge amount of contiguous block of memory at one go but by allocating separate memory allocations. Having said that, in order to keep track of the allocated memory I am trying to keep each pointer in a dynamic array to h...
Let malloc and friends handle this for you. That's what they are designed to do, build on that instead of wasting effort redoing what experts provide as part of your programming environment.
I have a pre-built static library (.a) and the source code for it. How do I attach the source so so I can step through it while debugging in Eclipse with gdb?
You can't step through the source code if your library has not been compiled with the debug option (gcc -g, assuming you are using gcc). The easiest thing would be to compile the library yourself in Eclipse, in debug mode, then link your program against the newly-compiled library.
Converting this code to javascript: ``` for( i = 0; i < 256; i++ ) m[i] = (unsigned char) i; ``` How do I convert theunsigned charpart? ``` for (i = 0; i < 256; i++) { m[i] = (?)i } ```
You don't have to do anything at all to the value to get the corresponding result: ``` for (i = 0; i < 256; i++) { m[i] = i; } ``` Anunsigned charin C is an 8 bit integer data type that can hold the values 0 to 255. As no value in the loop goes outside that range the cast doesn't change any of the values, it only ...
``` #include <stdio.h> int main(int argc, const char *argv[]) { const char *s[] = {"a", "b", "c", NULL}; const char **p = s; while (*p != NULL) { printf("string = %s\n", *p); (*p)++; } return 0; } ``` I want to traverse the string array and print the string util come up the NULL s...
``` (*p)++; ``` Should just be: ``` p++; ``` Here's what you are doing: ``` p --> * --> "a" | ^ incrementing this checking this for null ``` You're incrementing the wrong pointer.
I am currently trying to allocate separate chunks of memory usingmallocin order not to allocate a huge amount of contiguous block of memory at one go but by allocating separate memory allocations. Having said that, in order to keep track of the allocated memory I am trying to keep each pointer in a dynamic array to h...
Let malloc and friends handle this for you. That's what they are designed to do, build on that instead of wasting effort redoing what experts provide as part of your programming environment.
I have a pre-built static library (.a) and the source code for it. How do I attach the source so so I can step through it while debugging in Eclipse with gdb?
You can't step through the source code if your library has not been compiled with the debug option (gcc -g, assuming you are using gcc). The easiest thing would be to compile the library yourself in Eclipse, in debug mode, then link your program against the newly-compiled library.
Converting this code to javascript: ``` for( i = 0; i < 256; i++ ) m[i] = (unsigned char) i; ``` How do I convert theunsigned charpart? ``` for (i = 0; i < 256; i++) { m[i] = (?)i } ```
You don't have to do anything at all to the value to get the corresponding result: ``` for (i = 0; i < 256; i++) { m[i] = i; } ``` Anunsigned charin C is an 8 bit integer data type that can hold the values 0 to 255. As no value in the loop goes outside that range the cast doesn't change any of the values, it only ...
The following piece of code compiles and runs withgcc version 4.7.2 (Debian 4.7.2-5): ``` #include <stdio.h> int main() { const volatile x = 3; volatile const y = 4; return 0; } ``` Should I assume that the order of const and volatile is irrelevant? I tried reading up here :encpp refand it doesn't say ...
Yes, the order is irrelevant. In C++, the relevant specification is in 7.1p1,decl-specifieranddecl-specifier-seq, which basically explain that there is a sequence of relevant keywords, and 7.1.6, which listsconstandvolatileas two these keywords. Note that the production is weird enough that these are valid as well, th...