question
stringlengths
25
894
answer
stringlengths
4
863
``` struct tree{ #ifdef A #define TREE_GET(x,y) &x->y #else #define TREE_GET(x,y) x->y #endif }; ``` I want to know whether macro A was defined . Is there any command I can use in gdb .
In compilation time we pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information. For example,g++ -gdwarf-2 -g3 program.cpp -o program C Preprocessor Macros
Both methods work but which one is the faster/performant in the caseptr == NULL? ``` void voo() { str *ptr = NULL; // try to malloc memory and do something // leaving methode and free the memory if(ptr != NULL) { free(ptr); ptr = NULL; } } ``` Do I need anifquery at all if I leave t...
From C standard, 7.20.3.2/2, ifptrisNULLthenfree(ptr)does nothing. It's therefore pointless for you to check this, from both performance and superfluous code perspectives.
``` int main() { static int fun(){} return 0; } ``` ** If we define a function into another then why this code is giving following error:** Error: invalid storage class for function ‘fun’
This is called "nested function". It's not supported in C. Some compilers, such asgcc, offer it as language extension. You do not need thestatickeyword though.
Im using C langage, I resume my error: ``` char * sys_cmd; sys_cmd="exec ftp -vn << EOF\nopen servername \nuser user_name pswd \nlcd /our_dir \ncd P01/FTP_DIR/IN \numask 006\nput HB504170\ndir HB504170\nclose \nquit\n\nEOF\n"; system(sys_cmd); ``` the system command returns no error inhp-uxplatforms and returns inr...
As far as I remember ftp is an interactive application. So you would have to use "expect" mechanics to automate it. And since you would have to interact with it, the best idea imho would be to invoke a script that performs all ftp actions and then deal with results the way you see fit.
``` #include<stdio.h> #define MAX(a,b) ((a)>(b))?(a):(b) int main() { double a = 100 , b, c, e; int d = -1; b = 336; c = -33.600000000000001; e = a + (MAX(b, abs(c)) * d); printf("max is %f", e); return 0; } ``` Output of this program is 436 whereas logically it should be -236 . Can a...
After the macro substitution,a + (MAX(b, abs(c)) * d)becomes: ``` a + (((b) > (abs(c))) ? (b) : (abs(c)) * d) ``` Note that*has a higher precendence than?:, so the result is not what you expected. The correct macro should be: ``` #define MAX(a,b) (((a)>(b))?(a):(b)) // ^ ^ ``` This i...
I have anunsigned intthat holds a series of bits, and a certain bit location. Now I want to set all bits to 1 from that bit location 'downwards'. How can this be achieved simply without a loop? Example: ``` unsigned int bitloc=2; unsigned int bits=??; //must become 0000 0111 unsigned int bitloc=4; unsign...
How about? ``` unsigned int Mask = 0xffffffff; bits = Mask >> (31 - bitloc); ``` as in your example bitloc is 2: Mask is a binary number of ones then we shift right it 29 time effectively adding 29 zeros from the left leaving only bit zero bit one and bit two as ones. 0xffffffff >> 29 = 0x00000007=000...0111
Why do i get runtime eror when running this code in gcc compiler?? It works fine in turboC. I have been working on this for couple of days with no progress at all. Kindly help. ``` #include<stdio.h> int main() { int T,i=0,num,sum,temp,j; int *N; scanf("%d",&T); while(i++<T) { scanf("%d",N); temp=*N; while((*N)-->0) ...
include the header file ``` # include <stdlib.h> ``` Allocate memory to the pointer before using it. ``` int *N; N = (int *)malloc (sizeof (int)); ``` Free the allocated memory after using it ``` free (N); ```
I have a memory region which contains data that I would like to send over ethernet to the other client. To increase the throughput, currently I am fiddling with sendfile API instead of the classic send/write API. But as far as I understand, the sendfile API requires a file descriptor for input, but what I have is only...
The primary benefit ofsendfile()is that it allows you to avoid the overhead of having to firstread()data from a file descriptor into memory before you cansend()it. If the data you want to send is already in memory,sendfile()is not needed. Using weird workarounds to move the data into a file (likemmap()ing it) will onl...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question When compile and run, which stages can report error "symbol defined multiple times"? Pre...
This is sad... To save you from any more humiliation, I'm gonna just give you the answer. It's the linker.
``` #include<stdio.h> #define MAX(a,b) ((a)>(b))?(a):(b) int main() { double a = 100 , b, c, e; int d = -1; b = 336; c = -33.600000000000001; e = a + (MAX(b, abs(c)) * d); printf("max is %f", e); return 0; } ``` Output of this program is 436 whereas logically it should be -236 . Can a...
After the macro substitution,a + (MAX(b, abs(c)) * d)becomes: ``` a + (((b) > (abs(c))) ? (b) : (abs(c)) * d) ``` Note that*has a higher precendence than?:, so the result is not what you expected. The correct macro should be: ``` #define MAX(a,b) (((a)>(b))?(a):(b)) // ^ ^ ``` This i...
I have anunsigned intthat holds a series of bits, and a certain bit location. Now I want to set all bits to 1 from that bit location 'downwards'. How can this be achieved simply without a loop? Example: ``` unsigned int bitloc=2; unsigned int bits=??; //must become 0000 0111 unsigned int bitloc=4; unsign...
How about? ``` unsigned int Mask = 0xffffffff; bits = Mask >> (31 - bitloc); ``` as in your example bitloc is 2: Mask is a binary number of ones then we shift right it 29 time effectively adding 29 zeros from the left leaving only bit zero bit one and bit two as ones. 0xffffffff >> 29 = 0x00000007=000...0111
Why do i get runtime eror when running this code in gcc compiler?? It works fine in turboC. I have been working on this for couple of days with no progress at all. Kindly help. ``` #include<stdio.h> int main() { int T,i=0,num,sum,temp,j; int *N; scanf("%d",&T); while(i++<T) { scanf("%d",N); temp=*N; while((*N)-->0) ...
include the header file ``` # include <stdlib.h> ``` Allocate memory to the pointer before using it. ``` int *N; N = (int *)malloc (sizeof (int)); ``` Free the allocated memory after using it ``` free (N); ```
I have a memory region which contains data that I would like to send over ethernet to the other client. To increase the throughput, currently I am fiddling with sendfile API instead of the classic send/write API. But as far as I understand, the sendfile API requires a file descriptor for input, but what I have is only...
The primary benefit ofsendfile()is that it allows you to avoid the overhead of having to firstread()data from a file descriptor into memory before you cansend()it. If the data you want to send is already in memory,sendfile()is not needed. Using weird workarounds to move the data into a file (likemmap()ing it) will onl...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question When compile and run, which stages can report error "symbol defined multiple times"? Pre...
This is sad... To save you from any more humiliation, I'm gonna just give you the answer. It's the linker.
I have a memory region which contains data that I would like to send over ethernet to the other client. To increase the throughput, currently I am fiddling with sendfile API instead of the classic send/write API. But as far as I understand, the sendfile API requires a file descriptor for input, but what I have is only...
The primary benefit ofsendfile()is that it allows you to avoid the overhead of having to firstread()data from a file descriptor into memory before you cansend()it. If the data you want to send is already in memory,sendfile()is not needed. Using weird workarounds to move the data into a file (likemmap()ing it) will onl...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question When compile and run, which stages can report error "symbol defined multiple times"? Pre...
This is sad... To save you from any more humiliation, I'm gonna just give you the answer. It's the linker.
``` void skip(char *msg) { puts(msg+6); } char *message="Don't call me"; skip(message); ``` My doubt is why we don't use puts(*(msg+6)) to display text from 7th character onward;according to me (msg+6) refers to memory and *(msg+6) content
*msgis essentially a reference to a single char, not to the string of char's. due to thischar *andchar[]are essentially the same thing and you don't need to dereference character pointer in C because compiler automatically print fully string from given base address upto '\0' not get. you can also referthisfor more inf...
Today as I am trying to solve a simple 2-dimensional math function using C. However the result I got is kinda funny there. Code is here: ``` int main() { int x, y; x = 10 - y; y = x - 2; printf("the x and y would be %d, %d ", x, y); return 0; } ``` So as you can see, the answer would be easily c...
The reason is a basic misunderstanding of an imperative programming language. The C language is not an equation solver. '=' means an assignment, not an equation.
I am little struggling how to make my output to show like this: ``` a aa aaa ``` My current output shows this instead: ``` a aa aaa ``` Below are my code: ``` void displayA(int a){ for(int i = 0; i < a; i++) printf("a"); } int main(void){ displayA(1); printf("\n"); displayA(2); print...
You can useprintf("%*s", <width>, "a");to print any text right aligned by variable no. of spaces. Checkhere live.
This question already has answers here:What is the difference between char s[] and char *s?(14 answers)Closed9 years ago. I am trying to assign a character using pointer but it doesn't do. Will somebody please explain why following program stops working ? ``` #include <string.h> int main(void) { char *s = "modif...
You may not change a string literal that way. https://stackoverflow.com/a/17507772/234307 "A C string literal creates an anonymous array of char. Any attempt to modify that array has undefined behavior." - Keith Thompson
i want to compile a kernel for android from my source. But I want to use a tool or something like that. So I just click a button and get a flashable zip file... Is there a tool? Can I do it with a script? Thank you!
It depends where you have the kernel from and what your target device will be. Usually you need the right toolchain for your kernel and an approprietary linux environment anyway. Compared to this it's not much to just type the command to compile it in the terminal. If you need further information, xda is always a good...
This question already has answers here:Unexpected output when executing left-shift by 32 bits(2 answers)undefined behavior when left operand is negative(3 answers)Closed9 years ago. I'm debugging some code and came across some behavior I cannot explain. I am trying to shift the number -1 to the left 32 times to prod...
It'sundefined behaviorbecause you shift count is bigger than the number of bits for anint, that means that the result can't be predicted.
these are two codes ``` int d; d=0; d=a+b; print d+c+e; code 2: print a+b+c+e; ``` I am trying c programming. I am having some doubts in execution of this code which code executes faster? and use less memory?
Given what you have posted, Example 1 int d; d=0; d=a+b; /* print d+c+e;*/ printf("%i\n", d+c+e); Example 2 /* print a+b+c+e; */ printf("%i\n", a+b+c+e); Which is faster is tricky, if your compiler optimizesdaway inExample 1they are equivalent. On the other hand, if your compiler can't determine thatd=0is discard...
I get a segmentation fault with this code on fprintf: ``` #define _GNU_SOURCE #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <stdint.h> #include <fcntl.h> #include <errno.h> #include <time.h> #include <sys/time.h> #include <unistd.h> int fd; int main(int argc, char **ar...
You have a segfault, becausefdis anint, andfprintfexcept of aFILE*. ``` fd = posix_openpt(O_RDWR | O_NOCTTY); fprintf(fd, "hello\n"); close(fd); ``` Tryfdopenover thatfd: ``` FILE* file = fdopen(fd, "r+"); if (NULL != file) { fprintf(file, "hello\n"); } close(fd); ```
I'm trying to initialize an array of 32-bit integers bu for some reason the debugger (MSVC) throws an exception halfway through the writing process. The array is 1048576 elements longFails on iteration 263152 ``` #define ROM_MAX_SIZE (1024*1024*4) int main(){ size_t rom_size = ROM_MAX_SIZE / sizeof(uint32_t); ...
You should allocate it like this ``` uint32_t *rom = malloc(rom_size * sizeof(uint32_t)); ``` in current situation, your array is four times smaller then you expected.
I have this below code snippet from kernel source for PowerPc ``` #define SPRN_IVOR32 0x210 /* Interrupt Vector Offset Register 32 */ unsigned long ivor[3]; ivor[0] = mfspr(SPRN_IVOR32); #define __stringify_1(x) #x #define __stringify(x) __stringify_1(x) #define mfspr(rn) ({unsigned lon...
Themfsprmacro generates an asm instructionmfsprwhich reads the given special purpose register into a register chosen by the compiler, which then gets assigned torvalhence becomes the return value of the expression. As the comment says,SPRN_IVOR32is theInterrupt Vector Offset Register 32, whose contents are thus fetch...
I have a question about literals in C. ``` int a; //a is an integer that is assigned an integer literal 414 a = 414; float b; //b is a float that is assigned a float literal of 3.14 b = 3.14; struct point { int x,y; }; struct point b; //{5,6} is a compound literal that is assigned to a struture. b = {5,6}; //d...
(struct point){5,6}as a whole is a compound literal. C11 §6.5.2.5Compound literalsA postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal.
Say I have this C function: ``` __declspec(dllexport) const char* GetStr() { static char buff[32] // Fill the buffer with some string here return buff; } ``` And this simple Lua module: ``` local mymodule = {} local ffi = require("ffi") ffi.cdef[[ const char* GetStr(); ]] function mymodule.get_...
Theffi.stringfunction apparently does the conversion you are looking for. ``` function mymodule.get_str() local c_str = ffi.C.GetStr() return ffi.string(c_str) end ``` If you are getting a crash, then make sure that your C string is null terminated and, in your case, has at most 31 characterss (so as to not ...
Hello I was wondering if there was a C framework for windows? Like if someone wanted to run a C program on Windows would they have to download C?
The C programming language does require some runtime support libraries; however, these are included in all major OS distributions (both Windows and UNIX). So, you just need to compile a C program targetting the desired CPU instruction set (e.g. "x86" for Intel chips) and distribute the compiled output. You don't need ...
The C compiler was written in C, that much I know. What language/tools/instructions was/were used to create the initial functionality for the C compiler to become self-hosting? UPDATE: I know what bootstrapping a language is, and it is that research that prompted this question. I cannot find an answer to my question...
There are a multitude of C compilers in the world. Many of them were (and still are) written in C. However the first one was not - it was written in B.
What happens if you callopendir(argv[i])andargv[i]is the name of atextfile, not adirectory?
Fromman opendir: Return ValueTheopendir()andfdopendir()functions return a pointer to the directory stream. On error,NULLis returned, anderrnois set appropriately. In this case,errnowould beENOTDIR: name is not a directory.
I feel quite 'stupid' as asking this question but if anyone can show me the methods to modify the input result appeared on the command window. Example: I want to sort 5 numbers (1, 3, 4, 7, 5) in smallest-to-biggest order and the result on the command window must be: ``` input: 1 3 4 7 5 /* 1 line input */ output: ...
Regarding to your edited question, just replace"%d "with"%d".
I'm given the following snippet of code: ``` int group1[3][3] = {3,4,5,1,9,8}; int group2[3][3] = {{1},{2,3},{4,5}}; int *gPtr1 = group1; int *gPtr2 = group2; ``` The question asks me for the value of: (I'm supposed to answer this on paper, of course, no computer) ``` *(gPtr1 + 3) *(gPtr2 + 3) ``` Normally, I know...
To access the address of group1 pass it to the pointer in this way: ``` int *gPtr1 = &group1[0][0]; ``` Using that it's easy to find the soultions: 1 and 2.
Consider the following lines: ``` int i; printf("%d",i); ``` Will the lexical analyzer go into the string to parse%anddas separate tokens, or will it parse "%d" as one token?
There are two parsers at work here: first, the C compiler, that will parse the C file and basically ignore the content of the string (though modern C compilers will parse the string as well to help catch bad format strings — mismatches between the%conversion specifier and the corresponding argument passed toprintf()to...
In many programming competitions I have seen people write this type offor-loop ``` for(i = 0; i < (1 << 7); i++) ``` Unless I am missing something, that's the same as ``` for(i = 0; i < 128; i++) ``` Why use the(1 << 7)version?Isn't calculating the condition every time an unnecessary overhead?
Yes, they are equivalent in behavior. Then why do people use the (1 << 7) version? I guess, they use it to document it is a power of 2. Calculating the condition every time must be an overhead! I am unable to find the reason behind this! Not really, any normal compiler will replace1 << 7by128and so both loops will...
Suppose I want to perform the following action in C. Is there a way to do this more efficiently with pointers (just out of interest, as I am in the process of learning C). Thanks! ``` int my_array[5]; my_array[0] = my_array[1]; my_array[1] = my_array[2]; my_array[2] = my_array[3]; my_array[3] = my_array[4]; my_array...
usememmove. ``` memmove(&my_array[0], &my_array[1], 5 * sizeof(my_array[0])); my_array[5] = 0; ``` Maybe it's the most efficient way, because in most casememmoveis implemented with special machine code (e.g.rep movsdof x86, or SSE..) (Notice that youcannotusememcpy, because the source and the destination are overla...
This question already has answers here:Getting the size of a malloc only with the returned pointer(6 answers)Closed9 years ago. I'm struggling with realloc... ``` strucType mkBggr (structType x, char ch) { x = realloc(x, 100); printf("%d", sizeof(x)); } ``` I'm thinking this should print out the value 100,...
Realloc returns a pointer, so x is of pointer type. sizeof(x) is returning the size of a pointer, which is 8 bytes in this environment.
I came along a competitive question that asks the output of the following: ``` #include <stdio.h> int main() { int a[] = {0,1,2,3,4}; int i, *ptr; for(ptr = a+4, i=0; i <=4; i++) printf("%d", ptr[-i]); return 0; } ``` I did read this topic:Are negative array indexes allowed in C?However it was un...
First, recall that in C the expressionptr[index]means the same thing as*(ptr+index). Now let's look at your expression again:ptris set toa+4before the loop; then you apply-iindex to it. Therefore, the equivalent pointer arithmetic expression would be as follows: ``` printf("%d", *(a+4-i)); ``` This expression itera...
I was working with thestrcmpfunction in C, then i saw the function as arguments gets: ``` strcmp(_const char *s1, const char *s2)_; ``` And actually i passed normal char array and it worked. Any ideas why this happening?
If you have for example the following code ``` char c = 'A'; char *p = &c; const char *cp = &c; ``` then it means that you can change variablecusing pointerpbut you may not change it using pointercp For example ``` *p = 'B'; // valid assignment *cp = 'B'; // compilation error ``` Thus function declaration ``` i...
I need to write a program in C to read in pcap files and extract the packets and send them out . It's like a traffic replay. I know there's tcpreplay but I didn't see its C library, it seems to be only a command-line application. I know how to do it with pcap_open(), but it's only available in WinPcap, I need to do i...
Use eitherpcap_open_live()or, in newer versions of libpcap,pcap_create()andpcap_activate()- all of which are available in the current version of WinPcap, by the way.
I initialized my array like this:char x[]={'m'}; It worked. But for the following lines i got error:Size of the type is unknown or zero ``` char x[][]={{'m'},{'m'}}; ``` or ``` char x[][]={{'m'}}; ``` I am unable to find the reason of the error.
While defining a 2D array, specifying the column size is mandatory. ``` char x[][1]={{'m'}}; ```
Suppose I want to perform the following action in C. Is there a way to do this more efficiently with pointers (just out of interest, as I am in the process of learning C). Thanks! ``` int my_array[5]; my_array[0] = my_array[1]; my_array[1] = my_array[2]; my_array[2] = my_array[3]; my_array[3] = my_array[4]; my_array...
usememmove. ``` memmove(&my_array[0], &my_array[1], 5 * sizeof(my_array[0])); my_array[5] = 0; ``` Maybe it's the most efficient way, because in most casememmoveis implemented with special machine code (e.g.rep movsdof x86, or SSE..) (Notice that youcannotusememcpy, because the source and the destination are overla...
This question already has answers here:Getting the size of a malloc only with the returned pointer(6 answers)Closed9 years ago. I'm struggling with realloc... ``` strucType mkBggr (structType x, char ch) { x = realloc(x, 100); printf("%d", sizeof(x)); } ``` I'm thinking this should print out the value 100,...
Realloc returns a pointer, so x is of pointer type. sizeof(x) is returning the size of a pointer, which is 8 bytes in this environment.
I came along a competitive question that asks the output of the following: ``` #include <stdio.h> int main() { int a[] = {0,1,2,3,4}; int i, *ptr; for(ptr = a+4, i=0; i <=4; i++) printf("%d", ptr[-i]); return 0; } ``` I did read this topic:Are negative array indexes allowed in C?However it was un...
First, recall that in C the expressionptr[index]means the same thing as*(ptr+index). Now let's look at your expression again:ptris set toa+4before the loop; then you apply-iindex to it. Therefore, the equivalent pointer arithmetic expression would be as follows: ``` printf("%d", *(a+4-i)); ``` This expression itera...
I was working with thestrcmpfunction in C, then i saw the function as arguments gets: ``` strcmp(_const char *s1, const char *s2)_; ``` And actually i passed normal char array and it worked. Any ideas why this happening?
If you have for example the following code ``` char c = 'A'; char *p = &c; const char *cp = &c; ``` then it means that you can change variablecusing pointerpbut you may not change it using pointercp For example ``` *p = 'B'; // valid assignment *cp = 'B'; // compilation error ``` Thus function declaration ``` i...
I need to write a program in C to read in pcap files and extract the packets and send them out . It's like a traffic replay. I know there's tcpreplay but I didn't see its C library, it seems to be only a command-line application. I know how to do it with pcap_open(), but it's only available in WinPcap, I need to do i...
Use eitherpcap_open_live()or, in newer versions of libpcap,pcap_create()andpcap_activate()- all of which are available in the current version of WinPcap, by the way.
I initialized my array like this:char x[]={'m'}; It worked. But for the following lines i got error:Size of the type is unknown or zero ``` char x[][]={{'m'},{'m'}}; ``` or ``` char x[][]={{'m'}}; ``` I am unable to find the reason of the error.
While defining a 2D array, specifying the column size is mandatory. ``` char x[][1]={{'m'}}; ```
This question already has an answer here:Code for printf function in C [duplicate](1 answer)Closed9 years ago. What is the exact use of%inscanfandprintf? And wouldscanfandprintfwork without the%sign? All I could find is that%is the conversion specifier but I want to know how it works actually?
%is simply the symbol used to identify the beginning of a conversion specifier in the format string; why%as opposed to any other symbol is an open question, and probably doesn't have that interesting an answer. Theprintfandscanffunctions search the format string for conversion specifiers to tell them the number and t...
I would like to initialize an array of strings with \0. Is it right to do it like this? ``` char first[1024][1024] = {'\0'}; ```
For a 2d array is better to use: ``` char first[1024][1024] = {{'\0'},{'\0'}}; ``` or better yet (as suggested by @haccks): ``` char first[1024][1024] = {{'\0'}}; ``` in order to avoid warnings.
i have this array: ``` char alph[] ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','.',',',':','?','=','-','(',')','"','\'','/','%','@','!'}; ``` It's possible to change the symbol ' % ' with a word like 'perc' ? Thank...
Given the declaration ofalph, each element is a singlechar, whereas the string"perc"consists of multiple characters. Do note, however, that the character literal'perc'(with single quotes)isvalid C code, but its value is generally not useful; if you were to try to print it out, you'd wind up with garbage instead of the...
``` #include<stdio.h> int recursive(int f,int g){ static int a;; static int b; int c = 100; a = f; b = g; if(c != 105){ a++; b++; c++; recursive(a,b); } printf("\n a : %d b : %d \n",a,b); return 0; } int main(){ int a = 10; int b = 1; ...
You have infinite recursion in there. Becausecisneverequal to105(it's set to100every time you enter the function), the function will simply keep calling itself over and over, until you blow up the stack (exceed its capacity). It boils down to something as simple as: ``` int blowUpStack (int a) { blowUpStack (a);...
i need to put many symbols in one array of char. This is my code, I have problem with the single quote symbol, "'" : ``` int main() { int i, j; int a; char alph[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8'...
You can escape the quote with a backslash, i.e.'\''
This is some code that I wrote but I am confused to how to run it with linux terminal. I tried writing like this: asdasd:~/folder/file>./main.c file.txt but I just keep getting permission denied. Do I need some other program to run this with? I hope I gave enough information to get some kind of feedback (file.txt is ...
You have to compile the program. You do that with ``` gcc main.c -o program ``` Then you start it with: ``` ./program file.txt ```
I see that the bitmask field in theheader_fieldused inproto_register_field_array(const int parent, hf_register_info *hf, const int num_records);is aguint32, therefor I cannot use a 64 bit mask. Is there anyway I can go around? Specifically, I have a 60 bit field so I am trying to create a field with typeFT_UINT64and ...
If the function takes a 32 bit parameter, there is no way you can force it to understand a 64 bit parameter, sorry. Look for if some other function can do what you want.
I want to activate c99 mode in gcc compiler to i read in other post in this forum that-stdshould be equal to-std=c99but i don't know how to set it to this value using command line so please help.
Compile using: ``` gcc -std=c99 -o outputfile sourcefile.c ``` gcc --helplists some options, for a full list of options refer to themanuals. The different options for C dialect can be found the section "Options Controlling C Dialect" in anygccversion's manual (e.g.,here). As you are usingmakeyou can set the command...
I am trying to use Eclipse for C/C++ developers version with MinGW to build my IDE. The first thing I want to try is to import my existing C project. However after I importing the codes I found several problems I cannot handle It cannot resolve the includes, e.g. in a.c I am using macros defined in c.h, but a.c doe...
You can set general include paths and#definesymbols to be used by the indexer in the project propertiesC/C++ General -> Paths and Symbolspages. There's no automatic way I know to import these settings from a makefile AFAIK.
This is some code that I wrote but I am confused to how to run it with linux terminal. I tried writing like this: asdasd:~/folder/file>./main.c file.txt but I just keep getting permission denied. Do I need some other program to run this with? I hope I gave enough information to get some kind of feedback (file.txt is ...
You have to compile the program. You do that with ``` gcc main.c -o program ``` Then you start it with: ``` ./program file.txt ```
I see that the bitmask field in theheader_fieldused inproto_register_field_array(const int parent, hf_register_info *hf, const int num_records);is aguint32, therefor I cannot use a 64 bit mask. Is there anyway I can go around? Specifically, I have a 60 bit field so I am trying to create a field with typeFT_UINT64and ...
If the function takes a 32 bit parameter, there is no way you can force it to understand a 64 bit parameter, sorry. Look for if some other function can do what you want.
I want to activate c99 mode in gcc compiler to i read in other post in this forum that-stdshould be equal to-std=c99but i don't know how to set it to this value using command line so please help.
Compile using: ``` gcc -std=c99 -o outputfile sourcefile.c ``` gcc --helplists some options, for a full list of options refer to themanuals. The different options for C dialect can be found the section "Options Controlling C Dialect" in anygccversion's manual (e.g.,here). As you are usingmakeyou can set the command...
I am trying to use Eclipse for C/C++ developers version with MinGW to build my IDE. The first thing I want to try is to import my existing C project. However after I importing the codes I found several problems I cannot handle It cannot resolve the includes, e.g. in a.c I am using macros defined in c.h, but a.c doe...
You can set general include paths and#definesymbols to be used by the indexer in the project propertiesC/C++ General -> Paths and Symbolspages. There's no automatic way I know to import these settings from a makefile AFAIK.
u8glib picture loop contains a do-while loop in the following format ``` // picture loop u8g.firstPage(); do { draw(); } while( u8g.nextPage() ); ``` The reference manual specifies that "The decision on the number of parts and the number of calls to the draw() procedure is left to the low level driver. So ...
This is not possible, however some drivers have a 2x or 4x postfix, denoting the double or quad RAM buffer usage. Oliver
This question already has answers here:Is x += 1 more efficient than x = x + 1?(6 answers)Incrementing: x++ vs x += 1(5 answers)Why is i=i+1 faster than i++?(5 answers)Closed9 years ago. Is there is any difference between these two statements performance wise ? ``` i++; i = i + 1; ```
Depends on the optimisation.i++can, on most processors, be represented as a single machine language instruction.i = i + 1, on the other hand, could be represented by up to four: loadi, load1, add, store toi; although, even a middling smart compiler should be able to recognise it can rewrite it into the former.
I've been searching on how to create a digital clock on GTK/Glade in C but I couldn't find anywhere :( I guess that I need to use a label right? But what else? How can I pass the computer time, for example, to a label in the window that I've created on glade? Sorry for my bad english but I hope you can understand what...
Why not google it for help? I tried the keywords "gtk clock example" and found the following example: http://www.gtkforums.com/viewtopic.php?t=857
I have a simple program like : ``` #include <stdio.h> int main(void){ *(int*) 1 = 1; return 0; } ``` but why it is giving me Segmentation fault?
This will most likely crash no most systems. The assignment ``` *(int*)1 = 1; ``` tries to assign 1 to the location in memory with address 1. This is very undefined behaviour, and in most of systems the memory protection mechanism raises an error when you try it.
By default, GDB's internal variables will be $1, $2, $3, .... How to restart naming them from $1? ``` (gdb) p v1 $1 = 7 (gdb) p v2 $2 = 8 (gdb) p v3 $3 = 9 (gdb) ??? // what should be put here? $1 = 0 ```
Looking atthe documentation, there's no explicit command to clear the value history. It does mention that thefileandsymbol-filecommands, which can change the symbol table, clear the history. Also, you can useoutputinstead ofprintto avoid putting the printed value in the value history.
can anyone tell me what will happen if I miss double in below lines? ``` time_spent = (double)(end - begin) / CLOCKS_PER_SEC; ``` I was trying to calculate running time of my sorting problem, and forgot to typecast to double. The code ran for almost 90 mins, but the output time printed was "270.000006". Can anyone p...
If the code runs for almost 90 minutes, you will be getting an overflow of clock_t type on 32-bit architecture in under 72 minutes already. I do believe that this is your case.
When i linked the .o files,some problems happened: ``` gcc -L/usr/local/apr/lib -lapr-1 -pthread -laprutil-1 devpkg.o bstrlib.o db.o shell.o commands.o -o devpkg devpkg.o: In function `main': /root/workspace/devpkg/devpkg.c:21: undefined reference to `apr_pool_initialize' /root/workspace/devpkg/devpkg.c:22: undefi...
This is most likely just a simple dependency issue. You might want to try listing all the libraries you link to after the .o files, in the right order based on their dependencies with one another.
``` #include<stdio.h> int main() { int (*p_arr)[10]; int (*ptr)[10]; int arr[10] = {1,2,3,4,5,6,7,8,9,0}; ptr = &arr; p_arr = arr; } ``` When compiling it gives an error ``` warning: assignment from incompatible pointer type [enabled by default] ``` Why is using just the name of array gives this wa...
When you say ``` ptr = &arr; ``` L.H.Sisint(*)[]andR.H.Sisint(*)[]too. Hence no issue. Now let us examine ``` p_arr = arr ``` L.H.Sisint(*)[]andR.H.Sisint[]. Therefore,the warning asassignment from incompatible pointer type
I want to get hardware address of network interface onAIXusingioctl. Like in Linux we get it through: ``` ioctl(sockFd, SIOCGIFADDR, ifr_p); ``` I didn't findSIOCGIFADDRflag in/usr/include/sys/ioctl.honAIXto get hardware address information. Is there any way to get it fromioctl? or any file in system from where I c...
There are plenty of example codes available, seehereorhere. Basically, you'll have to callgetkerninfowith theKINFO_NDDargument and then read the address from thendd_addrfield of thekinfo_nddstruct filled by that call.
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed9 years ago. When I run this following code: ``` #include <stdio.h> #include <conio.h> void main(){ clrscr(); printf("%%"); getch(); } ``` I get % as an output? What might be the reason behind this...
That is whatprintfdoes: it is print formatted (ffor formatted). It uses%as the formatting character. It is the only reserved character and needs to be escaped to represent it self, i.e.%%. See the manual for more information on formatting:printf. P.S.: Never use a string that is not a part of the program as the first...
I want to remove or hide some components from my window (button, combobox, etc). How can I do that?
So, I've found answer on pelles-c forum:http://forum.pellesc.de/index.php?topic=6382.0 ``` ShowWindow(hWnd, SW_HIDE); // where hWnd - is some component ```
``` typedef void (*LoopCallback)(int fd, void * arg); LoopCallback func_ptr = 0; void call_back(int value) { printf("%d", value); } void sys_register_input(LoopCallback call_back) { func_ptr = call_back; } int main() { sys_register_input((LoopCallback)call_back); func_ptr(33, 0); } ``` Found this ...
No, it is not valid. The prototype expected by the caller doesn't match the prototype of the function being called, so undefined behavior may result. The specific result will depend on such factors as the compiler and the calling convention (the called function may merely end up seeing garbage inarg, or the thread sta...
Is it possible? Intel documentation says opcode E8 can be used with a relative displacement value. E8 cd CALL rel32 "Call near, relative, displacement relative to next instruction. 32-bit displacement sign extended to 64-bits in 64-bit mode." Does it mean only 32 bit displacements are allowed? I am quite unclear...
Yes. It means that the opcode is followed by a 32-bit displacement. If you want longer, you can compute it yourself with anleaand an indirect call.
I try use a pointer to a constant integer number in C: ``` void *p = NULL; p = (int *) 1; printf("p=%d\n", *(int *)p); ``` but I got a segment fault..... I cannot figure out how a pointer to a constant number in C w/o declaring a variable.
You are not taking the pointer to a constant but you are converting the constant to a pointer. You should do something like: ``` const int one = 1; const int *p; p = &one; ``` You cannot however do something like: ``` p = &1; ``` since literal constants haven't a memory location.
In my project there is a method which only returns aconst char*, whereas I need achar*string, as the API doesn't acceptconst char*. Any idea how to convert betweenconst char*tochar*?
First of all you should do such things only if it is really necessary - e.g. to use some old-style API withchar*arguments which are not modified. If an API function modifies the string which was const originally, then this is unspecified behaviour, very likely crash. Use cast: ``` (char*)const_char_ptr ```
I am trying to compile and run thiscodeunder ubuntu 14.04. I downloaded and installedlibpngversion 1.6.12. I am able to compile the code usinggcc test.c -lpngbut when I try to run it, I get this error:./a.out: error while loading shared libraries: libpng16.so.16: cannot open shared object file: No such file or directo...
Ok so I found the solutionhere. The trick is to runsudo ldconfigafter you install some shared library.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve...
This is a well-known bug in the Turbo C 3.0 compiler. But note one thing: currently the behaviour of your function is undefined asmainshould always have anintreturn type. Formally, a standards compliant compiler is permitted to do anything with your program! If you adjust your program so it has no undefined construc...
In the following code, when I fetch the value of the firstif's condition, it is 0, thus false. Still, the output prints "float". Is it a consequence of short circuiting ? If so, why doesn't it happen in the "normal" case, when thesizeofoperator is not used with '==' ? ``` #include<stdio.h> int main() { int x=1...
sizeofdoes not execute its operand, and moreover is a compile-time operator, which means that you couldn't branch on non-constant values anyway. sizeof((x == 2) ? f : i)is the size of the type of the result of(x == 2) ? f : i. The conditional operator would promote yourshortto afloatif it were executed, so the wholes...
I have gone through the development path for qVSCD(Quick Visa Smart Debit/Credit), as specified in "Visa Contactless Payment Specification v2.0.2" and have successfully implemented all the steps in C language. However they do not specify how to implement the Reset of Offline Counters and have only mentioned it briefly...
There are 3 different possible ways to reset the counters as mentioned in VCPS 2.0.2 section 8.3. The spec is clearly pointing you to the VIS 1.4 spec on this topic. You will find further details there.
I have 2 char arrays, and they have different sizes. I need to subtract one from the other, but I didn't manage to do it with a loop (because they have different sizes). This is what I've written: ``` for (i = 0; i < text_counter; i++) { for (j = 0; j <= key_counter; j++) { text_out[i] = text_in[i] - (...
Try something like : ``` j = 0; for (i = 0; i < text_counter; i++) { text_out[i] = text_in[i] - (key[j] - '0'); if (j < key_counter) j++; else j = 0; } ``` Edit : @Matt solution with % seems better : ``` for (i = 0; i < text_counter; i++) { text_out[i] = text_in[i] - (key[i % key_counter] ...
When I try and make a simple 3d arraychar tmp[256][256][256];it compiles but I can't run it. How can I achieve this? Thanks! ``` int main() { int tmp[256][256][256]; getch(); } ``` That's it. It wont run.
You experienced aStack Overflow. How ironic! There are2solutions: 1.Rewrite the codeand don't request so much memory. Usedynamic memory allocation:malloc(),calloc(),free()and other. 2. Increase thestack memoryallocated to the program by the OS:link
I have a simple program like : ``` #include <stdio.h> int main(void){ *(int*) 1 = 1; return 0; } ``` but why it is giving me Segmentation fault?
This will most likely crash no most systems. The assignment ``` *(int*)1 = 1; ``` tries to assign 1 to the location in memory with address 1. This is very undefined behaviour, and in most of systems the memory protection mechanism raises an error when you try it.
By default, GDB's internal variables will be $1, $2, $3, .... How to restart naming them from $1? ``` (gdb) p v1 $1 = 7 (gdb) p v2 $2 = 8 (gdb) p v3 $3 = 9 (gdb) ??? // what should be put here? $1 = 0 ```
Looking atthe documentation, there's no explicit command to clear the value history. It does mention that thefileandsymbol-filecommands, which can change the symbol table, clear the history. Also, you can useoutputinstead ofprintto avoid putting the printed value in the value history.
can anyone tell me what will happen if I miss double in below lines? ``` time_spent = (double)(end - begin) / CLOCKS_PER_SEC; ``` I was trying to calculate running time of my sorting problem, and forgot to typecast to double. The code ran for almost 90 mins, but the output time printed was "270.000006". Can anyone p...
If the code runs for almost 90 minutes, you will be getting an overflow of clock_t type on 32-bit architecture in under 72 minutes already. I do believe that this is your case.
When i linked the .o files,some problems happened: ``` gcc -L/usr/local/apr/lib -lapr-1 -pthread -laprutil-1 devpkg.o bstrlib.o db.o shell.o commands.o -o devpkg devpkg.o: In function `main': /root/workspace/devpkg/devpkg.c:21: undefined reference to `apr_pool_initialize' /root/workspace/devpkg/devpkg.c:22: undefi...
This is most likely just a simple dependency issue. You might want to try listing all the libraries you link to after the .o files, in the right order based on their dependencies with one another.
``` #include<stdio.h> int main() { int (*p_arr)[10]; int (*ptr)[10]; int arr[10] = {1,2,3,4,5,6,7,8,9,0}; ptr = &arr; p_arr = arr; } ``` When compiling it gives an error ``` warning: assignment from incompatible pointer type [enabled by default] ``` Why is using just the name of array gives this wa...
When you say ``` ptr = &arr; ``` L.H.Sisint(*)[]andR.H.Sisint(*)[]too. Hence no issue. Now let us examine ``` p_arr = arr ``` L.H.Sisint(*)[]andR.H.Sisint[]. Therefore,the warning asassignment from incompatible pointer type
I want to get hardware address of network interface onAIXusingioctl. Like in Linux we get it through: ``` ioctl(sockFd, SIOCGIFADDR, ifr_p); ``` I didn't findSIOCGIFADDRflag in/usr/include/sys/ioctl.honAIXto get hardware address information. Is there any way to get it fromioctl? or any file in system from where I c...
There are plenty of example codes available, seehereorhere. Basically, you'll have to callgetkerninfowith theKINFO_NDDargument and then read the address from thendd_addrfield of thekinfo_nddstruct filled by that call.
This question already has answers here:How to escape the % (percent) sign in C's printf(13 answers)Closed9 years ago. When I run this following code: ``` #include <stdio.h> #include <conio.h> void main(){ clrscr(); printf("%%"); getch(); } ``` I get % as an output? What might be the reason behind this...
That is whatprintfdoes: it is print formatted (ffor formatted). It uses%as the formatting character. It is the only reserved character and needs to be escaped to represent it self, i.e.%%. See the manual for more information on formatting:printf. P.S.: Never use a string that is not a part of the program as the first...
I want to remove or hide some components from my window (button, combobox, etc). How can I do that?
So, I've found answer on pelles-c forum:http://forum.pellesc.de/index.php?topic=6382.0 ``` ShowWindow(hWnd, SW_HIDE); // where hWnd - is some component ```
``` typedef void (*LoopCallback)(int fd, void * arg); LoopCallback func_ptr = 0; void call_back(int value) { printf("%d", value); } void sys_register_input(LoopCallback call_back) { func_ptr = call_back; } int main() { sys_register_input((LoopCallback)call_back); func_ptr(33, 0); } ``` Found this ...
No, it is not valid. The prototype expected by the caller doesn't match the prototype of the function being called, so undefined behavior may result. The specific result will depend on such factors as the compiler and the calling convention (the called function may merely end up seeing garbage inarg, or the thread sta...
Is it possible? Intel documentation says opcode E8 can be used with a relative displacement value. E8 cd CALL rel32 "Call near, relative, displacement relative to next instruction. 32-bit displacement sign extended to 64-bits in 64-bit mode." Does it mean only 32 bit displacements are allowed? I am quite unclear...
Yes. It means that the opcode is followed by a 32-bit displacement. If you want longer, you can compute it yourself with anleaand an indirect call.
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 got an if condition as a multiples of 5, i need to check if condition until a value <= 10000. My if state...
You could use function pointers. ``` typedef void (*func)(); func fpointers[] = {func1, func2, func3} int check = value / 5; fpointers [check] (); ```
The following code gives output as 0 0 0 0 using Codeblocks. ``` int main() { static int i=5; if(--i){ main(); printf("%d ",i); } } ``` I perfectly understands how the above code executes. However, when I removed 'static' from the code and used int i = 5, Ideone.com(online compiler) gave me runtime err...
If you remove the static that each call to main gets its own copy of i, initialized to 5, and so your recursion never terminates.
I'm using a MINI2440 board (S3C2440 CPU), running Linux. I have this working : ``` double a=168.168; printf("\nsqrt(%f)=%f\n", a, sqrt(a)); ``` But I have this resulting in "Illegal instruction" : ``` float a = 0.0; int b = 1; a = (float)b; ``` I can't cast an int to a float .. I tried to add / remove -msoft_flo...
Got it working ... I missed to specify -march=armv4t and -mtune=arm920t options. Now works perfectly, thanks.
Consider the following code: ``` long store; int firstValue = 0x1234; int secondValue = 0x5678; store = (((long) firstValue) << 32) | secondValue; ``` Isstoreguaranteed to have the value0x12345678regardless of the endianess of the machine... in Java?in C or C++?
The bitshift operations in all those languages operate on numbers. Endianness is not a property of numbers. In Javastoreis guaranteed to have the value0x123400005678L, because0x1234L << 32is0x123400000000L. In C and C++storeis not guaranteed to have any particular value: the result depends on the sizes of the types ...
I'm currently looking at the 'PlayerRatings'-package and would like toinspect and possibly modifythe internals of the.C("elo", ...)-Function, which is part of this package. I've found resources onhow to write extensions in C, and on how toaccess C-Functions of base R, but I am still unsure, where to look for the (unc...
Steps: Google search CRAN + Player RatingsOn CRAN page, click and downloadsources linkUnpack withtar -xvzf ./PlayerRatings_1.0-0.tar.gzor some suchLook atPlayerRatings/src/ratings.c(thesrcfolder is where the C code goes). For re-build instructions look at the how to write R extensions page you link.
This question already has answers here:Command-line Parameters in C program?(5 answers)Closed9 years ago. How can I send parameters to main in C(Linux): first one is -c or -d second is a string like file. How I'm doing that?
First, send data to your program using command line argument Like @haccks said Second, get the arguments in your code using : ``` int main(int argc, char **argv) ``` Tutorial Here
I' m trying to import a.solibrary into a python code to use c functions. I think using ``` from ctypes import * import ctypes lib = CDLL('./libcaenhvwrapper.so.5.56') ``` is working fine. I need to use some user defined types which are defined in a header file but I cannot access them. thank you in advance
The types are not in the.sofile that thectypesmodule loads. C types don't work like that, they're declared in the header and you must have the header to use a (C) library, even from C. You're going to have to use the variousctypesAPIs to re-create the types in Python. Seethis part of the tutorial, for instance, for ...
I would like to know if, given: ``` string name_a; string name_b; ``` there would be some already existing function that would allow me to compare two strings for a certain number of characterslikestrncmp(), but from a particular index in mystring. For instance: ``` int main(){ string name_a = "Morning"; s...
Thestd::stringmember functioncomparehas a version with arguments you need: ``` int compare (size_t pos, size_t len, const string& str) const; ``` It starts comparing atposand uses at mostlencharacters, so you can use ``` if (name_a.compare(INDEX_FIRST_CHAR, NUMBER_OF_CHAR_COMPARED, name_b) == 0) ```
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 Hi I want to write a code for a pow function without using math.h libary. How is ...
Probably best way I think,found here ``` int pow(int base, int exp) { if(exp < 0) return -1; int result = 1; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } ```