question
stringlengths
25
894
answer
stringlengths
4
863
I am new to C and have a problem with my code. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> bool a(char[], int); void b(char[], int[], int); void c(char[], int[], int, int); void d(char[], int, int[], int); int main(int argc, char ** argv) { return 0; } bool a(char[] x, int y) { return true; } void b(char[] x, int[] y, int z) { } void c(char[] x, int[] y, int z, int q) { } void d(char[] x, int y, int[] z, int q) { } ``` This code doesn't compile, but gives me an error message instead. The problem is, I don't see why it does that...
``` bool a(char[] x, int y) { ``` must be ``` bool a(char x[], int y) { ``` (And so on for the other definitions.)
Heres a snippet from the code I am trying to complete for building a linked list. for some reason I keep getting the error "error: expected ‘;’, identifier or ‘(’ before ‘struct’ " when trying to compile the code. Can someone help me out. ``` struct node; struct node* buildList(int x); void push(struct node** headRef, int data); int findLen(struct node** headRef); struct node{ int data; struct node* next; } struct node* buildList(int x){ struct node* head = NULL; head = malloc(sizeof(struct node)); head->data = x; head->next = NULL; return head; } ```
Try putting a semicolon after the struct declaration ``` struct node{ int data; struct node* next; }; ```
I was looking atDo I cast the result of malloc?and it appears that you should not cast the result in pure c code because it's potentially hides bugs and is redundant. But I also see people saying that c++ requires the cast, so should all c libraries cast the result of malloc because they could realistically be used in a c++ project?
it appears that you should not cast the result in pure c code because it's potentially hides bugs and is redundant That is correct. shouldn't all c libraries cast the result of malloc because they could realistically be used in a c++ project? No. A C library can be used from within a C++ project but still be compiled as C.
I am going through the K&R book{2nd Addition} on C lang. On Page No 107, I found that struct type "Point" is missing form the "return type" of the "addpoint" function. From The Book ``` /* addpoints: add two points */ struct addpoint(struct point p1, struct point p2) { p1.x += p2.x; p1.y += p2.y; return p1; } ``` Was expecting something like ``` struct point addpoint(struct point p1, struct point p2) { . . . ``` Is my understand correct when I say "point" is missing from return type? What are other errata that I need to look for in this book? I found this linkhttp://cm.bell-labs.com/cm/cs/cbook/2ediffs.html,Is this complete list? If someone can point me more examples like this it will be good. Thanks in Advance.
It's not missing since p1 is defined as struct point in the paramter, also I've looked up the K&R and the addpoint is defined asstruct point addpoint(struct point p1,struct point p2);
I am trying to make a c function work in some publicly available linear algebra code. the publicly available prototype is… ``` int ilaenv_(int *, char *, char *, int *, int *,int *, int *); ``` The publicly available code has the function call… ``` nb = ilaenv_(&c__1, "DGEQRF", " ", m, n, &c_n1, &c_n1); ``` where m, n, c_1, and c_n1 are integers, The error message is. ``` C++ 11 does not allow conversation from string literal to char *. ``` I did not create the code, but downloaded it from the LAPACK site. I hesitate to make too many changes to publicly available code that supposedly works, for fear of introducing errors. However, this error is showing up on a number of functions in the program that I am working on. How can I resolve this?
Your function takes "char *", not "const char *". String literals can be assigned only to "const char *".
In an Arduino script how do I compare a date pointer with a string that is a date. Currently I am trying: ``` while(year(t)=="1970") { getTime(); } ``` but I am getting a can't compare a pointer with a string compiler error which I understand but I would like to compare the two somehow and the somehow is where I am stuck. Thanks for any help for this newbie
``` if(year(t)==1970) { getTime(); } ``` year() returns 4-digit year integer. not a string.
How can you ensure that an executable is silently launched with admin (or sufficiently elevated) privileges when that executable is launched by a user who is logged into a Windows account which has default user privileges (i.e., not an admin account)? I don’t want the user to have to enter an admin password to be able to launch the exe with admin privileges. Background: The executable is sending out network packets which has to be marked with a certain DSCP value (QOS, qwave.lib). This is not possible unless the executable is executing with elevated privileges.
This goes against the security of the OS. You are basically asking to be able to bypass a security measure enforced by the OS. If you were allowed to do this, any malicious code could do the same thing, so I don't think that you can (or should) do it.
I have to write a ping function to run on Linux. The language is C++, so C if fine too. Searching on the Internet and looking at the source code for thepingcommand, it turns out that I should create a raw socket: ``` icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); ``` If I run my application without being superuser, thesocketfunction returns-1i.e. the socket is not created successfully. If I run it as a superuser, all works fine. Now, thepingcommand do create a raw socket and I can run itwithout superuser rights. My question is: how can I grant my application all permissions needed to create a raw socket without being executed by a superuser?
pingneeds thecap_net_rawcapability to do this without (other) superuser rights, and so does your program. Run ``` setcap cap_net_raw+ep your_executable_file ``` as root, and then normal users will be able to use the program.
I've noticed some code in the linux kernel with the following: In the files3c-dma-pl330.hthere is a definition: ``` enum dma_ch { ... }; ``` and at the end of that file there is:#include <plat/dma.h>In that file (dma.h) there is:enum dma_ch;Noexternis written, can you tell what is actually happens? Doesdma_chin dma.h is the same as in s3c-dma-pl330.h? Why isn't there theexternspecifier?
enum dma_ch;is a forward declaration of the enumeration. We useexternwhen we want to refer to an instance of an object that is found in (possibly) some other translation unit.dma_chis not an object, it is a type.
Description of problem: When I call method defined like this: ``` static PyMethodDef Parser_methods[] = { {"read", (PyCFunction)Parser_read, METH_KEYWORDS, "read from input source"}, {NULL, NULL, 0, NULL} }; static PyObject * Parser_read(Parser * const self, PyObject * unused0, PyObject * unused1) { ... } ``` I got: ``` SystemError: Bad call flags in PyCFunction_Call. METH_OLDARGS is no longer supported! ``` The code works fine on Python2, but crashes on Python3
Could be this bug... http://bugs.python.org/issue11587 Which means it's a python version issue. One fix seems to be to useMETH_KEYWORDS | METH_VARARGS.
I have a question about compare only some part of a string For example: ``` char *string = "nameOfPeople_Allen"; char searchName[20] = "Allen"; ``` how to trim thechar *string = "nameOfPeople_Allen";from_to get the nameAllen, then compare it withsearchName, I know how to compare string, but how to get the last part of the"nameOfPeople_Allen"from_?
Just usestrchr() ``` char *pointer; if ((pointer = strchr(string, '_')) != NULL) { printf("The text after _ is %s\n", pointer + 1); } ```
I have to write a ping function to run on Linux. The language is C++, so C if fine too. Searching on the Internet and looking at the source code for thepingcommand, it turns out that I should create a raw socket: ``` icmp_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); ``` If I run my application without being superuser, thesocketfunction returns-1i.e. the socket is not created successfully. If I run it as a superuser, all works fine. Now, thepingcommand do create a raw socket and I can run itwithout superuser rights. My question is: how can I grant my application all permissions needed to create a raw socket without being executed by a superuser?
pingneeds thecap_net_rawcapability to do this without (other) superuser rights, and so does your program. Run ``` setcap cap_net_raw+ep your_executable_file ``` as root, and then normal users will be able to use the program.
I've noticed some code in the linux kernel with the following: In the files3c-dma-pl330.hthere is a definition: ``` enum dma_ch { ... }; ``` and at the end of that file there is:#include <plat/dma.h>In that file (dma.h) there is:enum dma_ch;Noexternis written, can you tell what is actually happens? Doesdma_chin dma.h is the same as in s3c-dma-pl330.h? Why isn't there theexternspecifier?
enum dma_ch;is a forward declaration of the enumeration. We useexternwhen we want to refer to an instance of an object that is found in (possibly) some other translation unit.dma_chis not an object, it is a type.
Description of problem: When I call method defined like this: ``` static PyMethodDef Parser_methods[] = { {"read", (PyCFunction)Parser_read, METH_KEYWORDS, "read from input source"}, {NULL, NULL, 0, NULL} }; static PyObject * Parser_read(Parser * const self, PyObject * unused0, PyObject * unused1) { ... } ``` I got: ``` SystemError: Bad call flags in PyCFunction_Call. METH_OLDARGS is no longer supported! ``` The code works fine on Python2, but crashes on Python3
Could be this bug... http://bugs.python.org/issue11587 Which means it's a python version issue. One fix seems to be to useMETH_KEYWORDS | METH_VARARGS.
I have a question about compare only some part of a string For example: ``` char *string = "nameOfPeople_Allen"; char searchName[20] = "Allen"; ``` how to trim thechar *string = "nameOfPeople_Allen";from_to get the nameAllen, then compare it withsearchName, I know how to compare string, but how to get the last part of the"nameOfPeople_Allen"from_?
Just usestrchr() ``` char *pointer; if ((pointer = strchr(string, '_')) != NULL) { printf("The text after _ is %s\n", pointer + 1); } ```
Hi i am writing a simple c program to test parsing a buffer in c but when i run the program i get the following errors: ``` ./test.c: line 4: syntax error near unexpected token `(' ./test.c: line 4: `int main()' ``` Does anyone know why these errors are occurring? Thanks ``` #include <stdio.h> #include <stdlib.h> int main() { char* command; char* buf = malloc(100 *sizeof(char)); buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n"; command = strtok(buf, " "); printf("%s", command ); free(buf); } ```
I think you are trying to run source code without compiling. That's not the proper way to do.First compile the source code ``` gcc test.c -o test ``` Then execute it ``` ./test ```
I have a project and somewhere in my code I'm writing this: ``` else if (character[0] == '\'){ ``` How can I compare my character with this symbol? Every other symbol that I tried to compare like,,;, etc. is done and this is the only symbol that I'm getting a wrong message.
The backslash\is used as anescape character, so you would need to write: ``` else if (character[0] == '\\'){ ``` In this case the backslash is being used to escape itself.
I came across the following snippet which in my opinion is to convert an integer into binary equivalence. Can anyone tell me why an &1 is used instead of %2 ? Many thanks. ``` for (i = 0; i <= nBits; ++i) { bits[i] = ((unsigned long) x & 1) ? 1 : 0; x = x / 2; } ```
The representation of unsigned integers is specified by the Standard: An unsigned integer withnvalue bits represents numbers in the range [0, 2n), with the usual binary semantics. Therefore, the least significant bit is the remainder of the value of the integer after division by 2. It is debatable whether it's useful to replace readable mathematics with low-level bit operations; this kind of style was popular in the 70s when compilers weren't very smart. Nowadays I think you can assume that a compiler will know that dividing by two can be realized as bit shift etc., so you can just Write What You Mean.
``` #include<Stdio.h> #include<conio.h> void main() { char a[100]; clrscr(); printf("enter a paragraph\n"); scanf("%s",a); printf("%s",a); getch(); } ``` output: enter a paragraph my name is vasanth my how do I read the entire line "my name is vasanth" using scanf function?
Using thescanffunction: ``` scanf("%99[^\n]", a); ``` Where%[^\n]is a character set specifier that allows all characters except newlines, and%99[^\n]limits the match to at most 99 characters (sinceahas space for that many characters plus the null terminator). Alternatively, you can use ``` fgets(a, 100, stdin); ``` This is arguably more common, but be aware that it leaves the newline at the end intact.
I have a string, but I don't know its length, because I read from a file. (I must do this way, so pls don't tell me that read somehow else) I want to read all double number from it, but I don't know how many numbers it has. I wanted to use sscanf, but it doesn't work, it always reads the first number of course. Ideas?
Something like this will work. ``` const char *p = str; double d; int n; while (sscanf(p,"%lf%n",&d,&n) == 1) { // do something with d p += n; } ``` The reason you are having issues with sscanf is because it does not automatically move the buffer provided, you must ask it how many characters it has read (%n) and move it yourself.
Hej, I was wondering , can one get a container of the pointer using macro container_of in linux kernel? Can simmilar macro be used? F.ex ``` struct container { int a; struct *b; }; ``` Having *b how can obtain *container? Thank you
bis a pointer to some random address independent of the container, you need to pass a pointer to pointer and then useoffsetof: ``` #include <stdio.h> #include <stddef.h> struct item { int c; }; struct container { int a; struct item *b; }; #define item_offset offsetof(struct container, b) void fn(struct item **b) { struct container *x = (struct container *)((char *)b - item_offset); printf("b->container->a = %d, b->c = %d\n", x->a, x->b->c); } int main(void) { struct container x; struct item b = {20}; x.a = 10; x.b = &b; fn(&x.b); return 0; } ```
``` #include<stdio.h> #include<conio.h> void main() { void display(); clrscr(); printf("main function"); getch(); } void display() { printf("user function"); } ``` the output of the above program is main function but I want thedisplay()function to be executed before the main function. the output should be: user function main function
Your problem is here: ``` void main() { void display(); <--- here .... ``` Thisdeclaresa function but does notcallit. Call it like this ``` display(); ``` Do note that yourdisplayfunction accepts arbitrary parameters. And yourmainsignature is wrong. Your program should be: ``` #include<stdio.h> #include<conio.h> void display(void); int main(void) { clrscr(); // clear screen first display(); printf("main function"); getch(); return 0; } void display(void) { printf("user function"); } ```
I have made udp-server and udp-client communication via border router node. It able to communicate from client to server. I have difficulty in how to get packet info like ... source IP, Destination IP at border router node?? I am able to get it at server node but how to get same thing in border router node?
When recieved by a router, a packet is routed by the functiontcpip_ipv6_output, into filetcpip.c. You can activate PRINTFs of this file by setting theDEBUGmacro toDEBUG_PRINT. In this function, you can get the source & destination addresses withUIP_IP_BUF->destipaddrandUIP_IP_BUF->srcipaddr. Check, for example, when the route to the destination is looked up in the routing table : ``` uip_ds6_route_t *route; /* Check if we have a route to the destination address. */ route = uip_ds6_route_lookup(&UIP_IP_BUF->destipaddr); ```
I anticipated it would produce: 10 5 3 2 1 but instead it prints 10 5 3 2 1 1 1 1 1 1 1 1 1... Why? ``` #include <stdio.h> int main(void) { int i; for(i = 10; i >= 1; i /= 2) printf("%d ", i++); return 0; } ``` 2 is printed, then one is added making it 3, divided by 2 is 1. As 1 is equal to 1, 1 is printed and then one is added making it 2, divided by 2 is 0. As 0 is less than 1, the loop should end.
Wheniis 1, you print it with theprintfstatement. Thenigets incremented (via the++operator in yourprintfstatement). Theni /= 2is performed, which results toi = 2 / 2which results to1. This satisfies your conditioni >= 1, making it an infinite loop.
``` #include <stdio.h> struct Name {char d[11]}; int main (){ char str[11]; scanf("%s",str); struct Name new = {str}; } ``` I want to initialize the Name structure new, but there is a warning: suggest braces around initialization of subobject. How can I put the char array I read in my Name structure?
There are couple of ways: ``` int main () { char str[11]; scanf("%10s",str); // Make sure you don't read more than // what the array can hold. struct Name name1 = {"name"}; // This works only if you use string literal. struct Name name2; strcpy(name2.d, str); // Use this when you want to copy from another variable. } ```
Here is my machine details (ubuntu): ``` $uname -a ``` Linux rex-think 3.13.0-46-generic #76-Ubuntu SMP Thu Feb 26 18:52:13 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux I have enabled huge page in root user with: ``` $echo 20 > /proc/sys/vm/nr_hugepages ``` Now I want to mount huge page as a file system and open it for read/write, e.g., using the C API below ``` #define FILE_NAME "/mnt/hugepages/hello" fd = open(FILE_NAME, O_CREAT | O_RDWR, 0755); // writing to huge page using file sys API ``` But I am not sure how to mount the huge page. In /proc/sys/vm/, I can see hugetlb_shm_group hugepages_treat_as_movable but from the descriptionhere, I dont think they are the files I am looking for.
To mount huge tlp as file system use the below command ``` mount -t hugetlbfs nodev /mnt/huge ```
I want to make variable null in C in dev C. This code isn't work ``` char a = '5'; a = ''; ``` I don't know why this is not work. And I want to make characterabe empty. The error message is "[Error] empty character constant"
It depends what you mean by empty.. '\0' means the value 0 (NUL).
This is my Half Adder: ``` void HalfAdder(int a, int b, int * addrCarry, int * addrSum){ *addrCarry = a && b; *addrSum = a != b; } ``` How do I take that and make it a Full Adder?
This is how full adder implemented using the half adders: So translation to C is straightforward: ``` void FullAdder(int a, int b, int cin, int * addrCarry, int * addrSum){ int s1, c1, c2; // For intermediate results HalfAdder(a, b, &c1, &s1); // First adder stage HalfAdder(cin, s1, &c2, addrSum); // Second adder stage *addrCarry = c1 || c2; // The OR stage } ```
Here is my machine details (ubuntu): ``` $uname -a ``` Linux rex-think 3.13.0-46-generic #76-Ubuntu SMP Thu Feb 26 18:52:13 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux I have enabled huge page in root user with: ``` $echo 20 > /proc/sys/vm/nr_hugepages ``` Now I want to mount huge page as a file system and open it for read/write, e.g., using the C API below ``` #define FILE_NAME "/mnt/hugepages/hello" fd = open(FILE_NAME, O_CREAT | O_RDWR, 0755); // writing to huge page using file sys API ``` But I am not sure how to mount the huge page. In /proc/sys/vm/, I can see hugetlb_shm_group hugepages_treat_as_movable but from the descriptionhere, I dont think they are the files I am looking for.
To mount huge tlp as file system use the below command ``` mount -t hugetlbfs nodev /mnt/huge ```
I want to make variable null in C in dev C. This code isn't work ``` char a = '5'; a = ''; ``` I don't know why this is not work. And I want to make characterabe empty. The error message is "[Error] empty character constant"
It depends what you mean by empty.. '\0' means the value 0 (NUL).
When declaring a constant string, is the entire stringread-onlyor just the initial character? ``` const char* s = "hello"; ```
``` "hello" ``` is a string literal. The string literal object is of achararray type and is specified as unmodifiable by C. It means that trying to modify it invokes undefined behavior. ``` const char* s = "hello"; ``` Now with the declaration abovesis a pointer to the string literal object"hello". It points to the first character of the string. By qualifying it asconstyou make a promise to the compiler that you won't usespointer to modify what it is pointing to. Any pointer arithmetic onsby adding it an integer value also yields aconst char *. For examples + 1is also aconst char *and so you cannot uses + 1to modify what it points to, that is for examples[1] = 0(or equivalent*(s + 1) = 0) is not valid.
I have an application that parses the output from a command line usingpopen. However, when tested on Android, it crashes onpclose: Why? When tested in other Unix environment I have no error... ``` char commandLine[256] = "ps -A | grep -c myApplication"; FILE * fPipe = popen(commandLine, "r"); if (fPipe == NULL) return 0; int count = -1; fscanf(fPipe, "%d", &count); ///If here I print count, I get zero, which is correct... pclose(fPipe); ///Here it crashes! return count; ``` Update:It seems that usingpopencauses my application to crash anyway, at a later as stage, as if doing this call kills my application.
popenusesforkwhich apparentlyshouldn't be used in Android. To see which processes are running probably the only safe way is to check in the/procdir. More reading:popen on android NDK
I am programming an µC in C, and for programming I have to use a serial connection. Using this is quite easy, I just have to store the values (e.g.10011000) I want to send as ints, and then convert them for sending into binary and send them one after another. But now some command bytes should look likeXXXX1001, i.e. they contain some bits which are not set. But after the transmission size is fixed to one byte per cycle, I have to fill them up somehow. Furthermore, how can I store them? Does is simply mean that these bits are neglected, and I can set them either to1or to0?
AssumingXXXX1001is value for a control register to do some settings thenXXXXmeans dont care here.You can set them to any value. But beware,the same register can have different settings based on upper nibble.If so make sure you are setting them correctly.
My gradle build for a native shared library looks like this at the moment: ``` apply plugin: 'c' apply plugin: 'visual-studio' model { components { main(NativeLibrarySpec) { sources.c { source { srcDirs "src/main/c" include "**/*.c" } exportedHeaders { srcDirs "src/main/headers" } } } } } ``` How can I add folder that contains .h and .lib files, which I depend on, so that they are found while compiling / linking? The folder I want to add is stored in LIB_NAME env variable.
After more research and help from the gradle forum I got what I wanted. You need to use thePrebuiltLibrariesspecification. SeeGradle examples.
I am trying to link OpenCL libraries with Eclipse (luna) CDT (with GCC, version-4.9.1) on my Windows(8.1,64 Bit) machine. I have installed AMD APP SDK 2.9-1. To configure Eclipse, I followed thistutorialand linked the corresponding include folder (C:\Program Files(x86)\AMD APP SDK\2.9-1\include) and library (C:\Program Files(x86)\AMD APP SDK\2.9-1\lib\x86_64) on my machine. To test the OpenCL libraries, I took the sample code fromhere. But, when I am building the project, I am getting the following error. Description Resource Path Location Type make: *** [OpenCL_Test] Error 1 OpenCL_Test C/C++ Problem How to fix this error?
Follow thislinkfor library and include folder setup. Additional step is to go toProperties->C/C++ build->Setting->Cross GCC Linker->Binary Parser(it's a tab). Under Binary Parsers, I ticked all of the options and it worked.
Im wondering the print statements in my code are taking up processing cycles when the robot isn't connected to the com port. I am running a time sensitive process and have reason to believe the execution of these lines could be slowing my bot down.
Yes It will take processing time even if no serial monitor or other device is connected. A good practice is to a have a#definepre-processor directive in your code indicating whether you are debugging or not. e.g. #define DEBUG_PHASE ``` #ifdef DEBUG_PHASE printf(...); #endif ```
I am currently working on a program where I need to have this kind of output: I have to output the binary in IEEE 754 of 64 and 32-bit numbers in C. I already have the double and single floating point approximation, but I'm having trouble finding out how to output the binary of these in IEEE 754 notation, and color code them as well. Any thoughts/solutions on how to do this would be much appreciated.
This does not guarantee the correct answer if the underlying machine is something esoteric, however: ``` float f = 3.14; uint32_t u; memcpy(&u, &f, sizeof u); for (int i = 31; i >= 0; i--) putchar('0' + ((u >> i) & 1)); ```
I am doing a program in C, and currently I'm having problems. I don't know how to remove the last part of the string. For example: ``` char str[100] = "one => two"; ``` I want to remove=> two. Can you help me? Thanks in advance.
If you want to remove the part after a particularchartoken then use: ``` char str[100] = "one => two"; char *temp; temp = strchr(str,'='); //Get the pointer to char token *temp = '\0'; //Replace token with null char ```
I want to create a format string that will be used inscanfby specifying aMAX_LENGTHfor a string input. What I have is the following but the compiler says it's wrong: ``` const int MAX_LENGTH = 50; char format[9]; sprintf(format, "\%%d[^\n]s", MAX_LENGTH); ``` The compiler says that the data argument is not used by the format string. The first%should be escaped, and the second one is part of the%dwhich should be read in fromMAX_LENGTH. How do I accomplish this? By the way, the format string should read at mostMAX_LENGTHcharacters until a newline is reached.
The % sign should be escaped here using%%,not\%.
``` //function to copy string t to string s using pointers void strcpy(char *s,char *t) { while((*s++=*t++)!='\0'); return; } ``` i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.
*s++=*t++ is basically ``` *s = *t; s++; t++; ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question In C, the cascade switch statement can be used to easily implement this flow: ``` switch (var) { case c: C(); case b: B(); case a: A(); default: // no op } ``` Are there alternatives to support this flow in other programming languages? E.g. in Python, Java?
You can support that flow in any language that hasifstatements, and a logical OR operator (which would be all of them) ``` flow = 0; if ( var == a ) { A(); flow = 1; } if ( flow || var == b ) { B(); flow = 1; } if ( flow || var == c ) { C(); flow = 1; } // and so on ```
I have a question about syntax of pointer to arrays. Well we know arrays are pointers themselves(what our uni professor said) so why when we point to them with another pointer (which would be a pointer to pointer) we use this syntax: ``` int array[10]; int *pointer = array; ``` Instead of this syntax: ``` int array[10]; int **pointer = &array; ``` Although i know this would be correct using malloc but why not in the normal way, is it a compiler or syntax thing or i am wrong somewhere else??
Tell your professor they are wrong. Arrays arenotpointers. Arrays candecayto pointers, but theyarenot pointers. int* pointer = array;declares a pointer that points to the first element inarray. int** pointer = &array;is not correct. As mentioned byjschultz410in the comments, the type of&arrayisnotint**, it isint (*)[10]aka a pointer to an array of 10 ints, which cannot decay toint**.
I am reviewing pointers and how to access the content of a memory location pointed by a pointer. My question is: Are there any differences between indirection and dereferencing when they access the value of a pointer in C?
I could find exactly one occurrence of "dereferencing" (and none of "dereference") in the current C11 draft, and this was in a footnote, in the phrase "dereferencing a pointer". The standard calls unary*theindirection operator. I would find "indirecting a pointer" strange (the standard doesn't use the verb "to indirect"), but this question is more about linguistics than about programming. I'm not aware of any common usage of "dereferencing" meaning something else than indirection, and I doubt there is.This Wikipedia articlecalls unary*indirection as well as dereference.
Uploading sketches to my arduino uno worked fine. Now uploading won't work. I get the following error. Is there a way to reset my board? Using the built-in reset button does not help. Error: ``` Arduino: 1.0.6 (Mac OS X), Board: "Arduino Uno" Binary sketch size: 7,878 bytes (of a 32,256 byte maximum) avrdude: stk500_recv(): programmer is not responding ``` Please give any information on how to fix or reset the board.
there are many reason and you need to try 2 or 3 different operations in order to understand why avrdude is not responding First, check serial port on Arduino IDE, then check what kind of board you have selected in IDE. Have you left some connected on pin 0 or 1 of your board? They are serial TX and RX used by FTDI to write the sketch on your Atmega, I don't know why but sometimes if you left something connected there, you could have some problems during upload. Hope this will help you!
``` //function to copy string t to string s using pointers void strcpy(char *s,char *t) { while((*s++=*t++)!='\0'); return; } ``` i am confused how is the expression *s++==*t++ evaluated.I know associativity of increament operator is higher than assignment operator.
*s++=*t++ is basically ``` *s = *t; s++; t++; ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question In C, the cascade switch statement can be used to easily implement this flow: ``` switch (var) { case c: C(); case b: B(); case a: A(); default: // no op } ``` Are there alternatives to support this flow in other programming languages? E.g. in Python, Java?
You can support that flow in any language that hasifstatements, and a logical OR operator (which would be all of them) ``` flow = 0; if ( var == a ) { A(); flow = 1; } if ( flow || var == b ) { B(); flow = 1; } if ( flow || var == c ) { C(); flow = 1; } // and so on ```
I have a question about syntax of pointer to arrays. Well we know arrays are pointers themselves(what our uni professor said) so why when we point to them with another pointer (which would be a pointer to pointer) we use this syntax: ``` int array[10]; int *pointer = array; ``` Instead of this syntax: ``` int array[10]; int **pointer = &array; ``` Although i know this would be correct using malloc but why not in the normal way, is it a compiler or syntax thing or i am wrong somewhere else??
Tell your professor they are wrong. Arrays arenotpointers. Arrays candecayto pointers, but theyarenot pointers. int* pointer = array;declares a pointer that points to the first element inarray. int** pointer = &array;is not correct. As mentioned byjschultz410in the comments, the type of&arrayisnotint**, it isint (*)[10]aka a pointer to an array of 10 ints, which cannot decay toint**.
I am reviewing pointers and how to access the content of a memory location pointed by a pointer. My question is: Are there any differences between indirection and dereferencing when they access the value of a pointer in C?
I could find exactly one occurrence of "dereferencing" (and none of "dereference") in the current C11 draft, and this was in a footnote, in the phrase "dereferencing a pointer". The standard calls unary*theindirection operator. I would find "indirecting a pointer" strange (the standard doesn't use the verb "to indirect"), but this question is more about linguistics than about programming. I'm not aware of any common usage of "dereferencing" meaning something else than indirection, and I doubt there is.This Wikipedia articlecalls unary*indirection as well as dereference.
Uploading sketches to my arduino uno worked fine. Now uploading won't work. I get the following error. Is there a way to reset my board? Using the built-in reset button does not help. Error: ``` Arduino: 1.0.6 (Mac OS X), Board: "Arduino Uno" Binary sketch size: 7,878 bytes (of a 32,256 byte maximum) avrdude: stk500_recv(): programmer is not responding ``` Please give any information on how to fix or reset the board.
there are many reason and you need to try 2 or 3 different operations in order to understand why avrdude is not responding First, check serial port on Arduino IDE, then check what kind of board you have selected in IDE. Have you left some connected on pin 0 or 1 of your board? They are serial TX and RX used by FTDI to write the sketch on your Atmega, I don't know why but sometimes if you left something connected there, you could have some problems during upload. Hope this will help you!
I am reviewing pointers and how to access the content of a memory location pointed by a pointer. My question is: Are there any differences between indirection and dereferencing when they access the value of a pointer in C?
I could find exactly one occurrence of "dereferencing" (and none of "dereference") in the current C11 draft, and this was in a footnote, in the phrase "dereferencing a pointer". The standard calls unary*theindirection operator. I would find "indirecting a pointer" strange (the standard doesn't use the verb "to indirect"), but this question is more about linguistics than about programming. I'm not aware of any common usage of "dereferencing" meaning something else than indirection, and I doubt there is.This Wikipedia articlecalls unary*indirection as well as dereference.
Uploading sketches to my arduino uno worked fine. Now uploading won't work. I get the following error. Is there a way to reset my board? Using the built-in reset button does not help. Error: ``` Arduino: 1.0.6 (Mac OS X), Board: "Arduino Uno" Binary sketch size: 7,878 bytes (of a 32,256 byte maximum) avrdude: stk500_recv(): programmer is not responding ``` Please give any information on how to fix or reset the board.
there are many reason and you need to try 2 or 3 different operations in order to understand why avrdude is not responding First, check serial port on Arduino IDE, then check what kind of board you have selected in IDE. Have you left some connected on pin 0 or 1 of your board? They are serial TX and RX used by FTDI to write the sketch on your Atmega, I don't know why but sometimes if you left something connected there, you could have some problems during upload. Hope this will help you!
I have a question that might look strange but i arised in my mind. I have made a small socket client-server chat application in C#. I wanted to know that does sockets save any data on the hard drive or they only use RAM? If yes then is the case same for the C/C++ as well? I mean for example, if I send some message from client to the server. Is it saved somewhere on the Hard-drive or it just exists there in the RAM only? I mean if OS is storing it somewhere or not? I am sorry, if i asked a dumb question. Thanks Regards
Not a dumb question, but not one we can answer either. It depends on the implementation and also how far down the stack you want to consider. In general, I would not expect the network stack to save the data to the disk. However, the OS might write it to disk as part of its virtual memory management (so, for example, if this is a security question, then yes it could end up on disk).
Here is code to destroy a circularly linked list. When it runs, it produces an abort trap 6: pointer being freed was not allocated ``` NODE *roamer = list->head; do{ NODE *oldRoamer = roamer; roamer = roamer->next; printf("freeing prev"); free(oldRoamer); printf("prev freed"); }while (roamer != NULL); ``` The program prints both printf statements a bunch of times, but then gives the error just after printing "freeing prev".
It's CIRCULAR. That means the last item points to the first, which has already been freed. ``` do .... while (roamer != list->head); ```
Here is code to destroy a circularly linked list. When it runs, it produces an abort trap 6: pointer being freed was not allocated ``` NODE *roamer = list->head; do{ NODE *oldRoamer = roamer; roamer = roamer->next; printf("freeing prev"); free(oldRoamer); printf("prev freed"); }while (roamer != NULL); ``` The program prints both printf statements a bunch of times, but then gives the error just after printing "freeing prev".
It's CIRCULAR. That means the last item points to the first, which has already been freed. ``` do .... while (roamer != list->head); ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question How can I send the names of files contents in a folder from a server to a client? I would that in a client I could see the list of files contents in a folder receive from a server. Thank you very much!
Server side: socketbindlistenaccept on listening socketrecv request via accepted socketopendir, readdir, closedirsend dir-listclose accepted socketstart over with 4. Client side: socketconnectsend requestrecv dir-listcloseprintf dir-list
i tried to search on the net but i didn't find anything about it. Only how to increase stack size and similar. I want to know the stack size on cygwin 64 bit for windows. I'm programming with C on netbeans and i tried to make a stack overflow to find the answer. From the code I obtained 43104 as result... Now, what this number is? bit-Kb-Mb? I hope you could help me, sorry for my english :)
Since you are usingcygwinthis is very easy withgetrlimit ``` #include <stdio.h> #include <sys/resource.h> #include <sys/time.h> int main(void) { struct rlimit rl; if (getrlimit(RLIMIT_STACK, &rl) != 0) return -1; fprintf(stdout, "current: %ld kB\n\n", rl.rlim_cur / 1024); return 0; } ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question b = 25 | a; Assume that a corresponds to register $t0 and b corresponds to register $t1.? Can anyone explain how to approach this and can give me the final answer so I can compare with mine after I do it?
I suppose you meanori $t1, $t0, 25? That would be the equivalent. You can find tons of references about MIPS with a Google search. A good example would be thisMIPS instruction reference.
The below code prints a passed string as hex values, I'm using it to check strings which include non-printable characters prior to transmission on a serial network. I understand the code but am just unsure why if we assume that aninton my system is 4 bytes, the pointer doesn't advance by four bytes each time(unsigned int) *s++is computed by the loop. Could someone please explain why this is the case? Is there some sort of operator precidence like general arithmetic? ``` static void printhexstring(const char *s) { while(*s) { printf("<%02X> ", (unsigned int) *s++); } printf("\n"); } ```
``` printf("<%02X> ", (unsigned int) *s++); ``` You are incrementing the pointerswhich is of typecharand when this increment is done the pointersis moved by one byte and not 4 bytes. Casting has no effect on pointer arithmetic here. %Xconverts an unsigned int to unsigned hexa and display the value out so you have the castunsigned int
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed8 years ago.Improve this question b = 25 | a; Assume that a corresponds to register $t0 and b corresponds to register $t1.? Can anyone explain how to approach this and can give me the final answer so I can compare with mine after I do it?
I suppose you meanori $t1, $t0, 25? That would be the equivalent. You can find tons of references about MIPS with a Google search. A good example would be thisMIPS instruction reference.
The below code prints a passed string as hex values, I'm using it to check strings which include non-printable characters prior to transmission on a serial network. I understand the code but am just unsure why if we assume that aninton my system is 4 bytes, the pointer doesn't advance by four bytes each time(unsigned int) *s++is computed by the loop. Could someone please explain why this is the case? Is there some sort of operator precidence like general arithmetic? ``` static void printhexstring(const char *s) { while(*s) { printf("<%02X> ", (unsigned int) *s++); } printf("\n"); } ```
``` printf("<%02X> ", (unsigned int) *s++); ``` You are incrementing the pointerswhich is of typecharand when this increment is done the pointersis moved by one byte and not 4 bytes. Casting has no effect on pointer arithmetic here. %Xconverts an unsigned int to unsigned hexa and display the value out so you have the castunsigned int
So I create this small program to represent my problem. Run program enter 'a' press ENTER. C Code: ``` #include <stdio.h> #include <stdlib.h> int main(void) { char o; while(1) { printf("> "); scanf("%c",&o); switch(o) { case 'a' : printf("%c\n",o); break; case 'q' : return 0; } } } ``` Output is: ``` > a a > > *(waiting for input)* ``` What I expected it to be: ``` > a a > *(waiting for input)* ``` Please give me some advice how to get my problem solved. Thank you.
There is a\nonstdinafter you scan outa. Either callgetchar()after you have grabbed the character or change yourscanftoscanf("%c%*c", &o). Because of this, the second time your loop looks for input, it will already have the\nwaiting, and it will switch on that value, do nothing, and prompt again.
http://www.sanfoundry.com/c-program-sorting-bubble-sort/ My questions are: At line 28: Whynum - i - 1?At line 30: what does theifcondition mean? especially, whyj + 1?How to display the elements of the sorted array randomly? No Asc or Dsc order?How to differ in the displayed random numbers?
at Line 30 code is doingj+1that is why the condition isj<num-i-1so that array out of bound exception will not occur. you can change the logic as ``` for (i = 0; i < num; i++) { for (j = 1; j < (num - i); j++) { if (array[j-1] > array[j]) { temp = array[j]; array[j] = array[j-1]; array[j-1] = temp; } } } ``` if you want to display array in random way then there is no need of sorting!! because there is already no order in array. you can write your own logic to display array elements randomly.
I need to build an application which can read PNG files. On MacOSX mavericks thelibpngis not available anymore (see). Is there any other way to read PNG file on MacOSX (Cocoa / Carbon Framework...). I'd rather stay with the native framework than download and compile a local libpng. I also need to read TIFF and JPEG files, so ideally the native framework would also allow me to read those ? I am usingCprogramming.
I would expect that to be handled by the (aptly named)Image I/Oframework.This pagehas example code on how to set up an "image source" and load an image from it. I don't think you need to care at the application level whether the image is PNG or not, the framework abstracts that out.
I'm going to boil this problem down to the simplest form: Let's iterate from [0 .. 5.0] with a step of 0.05 and print out 'X' for every 0.25 multiplier. ``` for(double d=0.0; d<=5.0; d+=0.05) { if(fmod(d,0.25) is equal 0) print 'X'; } ``` This will of course not work sincedwill be [0, 0.05000000001, 0.100000000002, ...] causingfmod()to fail. Extreme example is whend=1.999999999998andfmod(d,0.25) = 1. How to tackle this?Here isan editable online example.
I'd solve this by simply not using floating point variables in that way: ``` for (int i = 0; i <= 500; i += 5) { double d = i / 100.0; // in case you need to use it. if ((i % 25) == 0) print 'X'; } ``` They're usually problematic enough that it's worth a little extra effort in avoiding them.
The program below prints ``` root 3 next 11 ``` However, I am not sure if the program keeps root.next until the end of the program. ``` #include<stdio.h> typedef struct sequence { int x; sequence* next; }sequence; int main() { sequence root; root.x = 3; { sequence p; p.x = 11; root.next = &p; } printf("root %d\n",root.x); printf("next %d\n",root.next->x); return 0; } ```
The scope ofpends at the closing bracket. ``` { sequence p; p.x = 11; root.next = &p; } <---- here ``` When you callprintf("next %d\n",root.next->x);the variablepyou are pointing to withroot.nextdoesn't exist anymore. Therefore it isn't "safe", since it causes undefined behavior.
Okay I am getting lost in these pointers can somebody exactly tell me what is(are) the difference betweenchar * x,y,z;,char* x,y,z;andchar (*)x,y,z;? If you can please provide resources to your answer or something.
These two records ``` char * x,y,z; char* x,y,z; ``` are identical and equivalent to ``` char *x; char y; char z; ``` Take into account that these declarations are equivalent ``` char*x; char* x; char * x; char *x; ``` All them declare variable x as pointer to char. This record ``` char (*)x,y,z; ``` is invalid and will not be compiled. I think you mean the following ``` char (*x),y,z; ``` In this case declaration ``` char ( *x ); ``` is equivalent to ``` char *x; ``` You may enclose in parentheses a declarator. So the above record you could write like ``` char ( *x ), ( y ), ( z ); ```
Does lldb or gdb set any environment variables or have any other tells?
Cribbed fromGoogle Breakpad: ``` #include <sys/syscntl.h> bool isInDebugger() { bool result=false; pid_t pid = getpid(); int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; int mibSize = sizeof(mib) / sizeof(int); size_t actualSize; if (sysctl(mib, mibSize, NULL, &actualSize, NULL, 0) == 0) { struct kinfo_proc *info = (struct kinfo_proc *)malloc(actualSize); if (info) { // This comes from looking at the Darwin xnu Kernel if (sysctl(mib, mibSize, info, &actualSize, NULL, 0) == 0) result = (info->kp_proc.p_flag & P_TRACED) ? true : false; free(info); } } return result; } ```
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.Closed8 years ago.Improve this question What are potential issues with the following code? ``` short foo() { short a,b,c; b=10; c = a + b; return c; } ```
Variable a was not initialized. It has an indeterminate value.
The programe generates Segmentation fault: 11, on Yostemite ``` #include<stdio.h> #include<math.h> #include<string.h> int main (){ unsigned long long int inputNumber[99]={0}; int i = 0; unsigned long long int input= 0; scanf("%llu", &input); while( input != EOF ){ inputNumber[i] = input; ``` /** while debugging with gdb it gives : Program received signal SIGBUS, Bus error. on above line. */ i++; }; ``` for( ; i > 0; i--){ printf("%.4f\n", sqrt(inputNumber[i])); } return 0; } ```
Your scanf call is not in the loop, so this runs forever and then overruns the array buffer: ``` while( input != EOF ){ inputNumber[i] = input; i++; }; ``` Change to: ``` while( input != EOF ){ inputNumber[i] = input; i++; scanf("%llu", &input); }; ```
So I was trying to find the largest and 2nd largest integer in an array. So I assisnged it to be the smallest value possible and it seems like it can go below -(2^31). I tried with value as large as -2^63 and it still work ``` void findMax1Max2(int m[], int size, int *max1, int *max2) { int i; *max1 = -2147483648; *max2 = -2147483648; for (i = 0; i < size; i++) { if (m[i] > *max1){ *max2 = *max1; *max1 = m[i]; } else if (m[i] > *max2){ *max2 = m[i]; } } } ```
The right way to get the smallest integer value is ``` #include <limits.h> int val = INT_MIN; ``` Regarding your question you should read thisblog postexplaining why INT_MIN is defined as-2147483647 - 1instead of-2147483648.
Okay I am getting lost in these pointers can somebody exactly tell me what is(are) the difference betweenchar * x,y,z;,char* x,y,z;andchar (*)x,y,z;? If you can please provide resources to your answer or something.
These two records ``` char * x,y,z; char* x,y,z; ``` are identical and equivalent to ``` char *x; char y; char z; ``` Take into account that these declarations are equivalent ``` char*x; char* x; char * x; char *x; ``` All them declare variable x as pointer to char. This record ``` char (*)x,y,z; ``` is invalid and will not be compiled. I think you mean the following ``` char (*x),y,z; ``` In this case declaration ``` char ( *x ); ``` is equivalent to ``` char *x; ``` You may enclose in parentheses a declarator. So the above record you could write like ``` char ( *x ), ( y ), ( z ); ```
Does lldb or gdb set any environment variables or have any other tells?
Cribbed fromGoogle Breakpad: ``` #include <sys/syscntl.h> bool isInDebugger() { bool result=false; pid_t pid = getpid(); int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; int mibSize = sizeof(mib) / sizeof(int); size_t actualSize; if (sysctl(mib, mibSize, NULL, &actualSize, NULL, 0) == 0) { struct kinfo_proc *info = (struct kinfo_proc *)malloc(actualSize); if (info) { // This comes from looking at the Darwin xnu Kernel if (sysctl(mib, mibSize, info, &actualSize, NULL, 0) == 0) result = (info->kp_proc.p_flag & P_TRACED) ? true : false; free(info); } } return result; } ```
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.Closed8 years ago.Improve this question What are potential issues with the following code? ``` short foo() { short a,b,c; b=10; c = a + b; return c; } ```
Variable a was not initialized. It has an indeterminate value.
My question is pretty simple and straightforward: if I have e.g. 1MB of RAM assigned to the program's stack, can I get the addresses of the start and the end, or the start and the length? I'm using Visual Studio 2013.
You should question your assumptions about stack layout. Maybethe stack doesn't have just one top and bottom Maybeit has no fixed bottom at all Clearly there's no portable way to query concepts which are not portable. From Visual C++, though, you can use the Win32 API, depending on Windows version. On Windows 8 it is very easy, just callGetCurrentThreadStackLimits Earlier versions need to useVirtualQueryExand process the results somewhat. Getting one address in the stack is easy, just use&on a local variable. Then you need to find the limits of the reserved region that includes that address. Joe Duffy has writtena blog post showing the details of finding the bottom address of the stack
I want to mergeNordered linked lists into one ordered linked list. However, I also want the individual ordered linked list to be retained. I am successful in doing so using an array ofNodepointers with each array element as a node corresponding to first node of individual lists. However, with array size fixed, I cannot proceed with merging more than array size. Now my question is, is there a way I can dynamically change array size. If not I am thinking of using Queue instead to hold the first node of individual lists in a queue linked list. Am I going right or wrong? Please give me some tips regarding the problem.
It sounds like you are looking forrealloc, assuming you dynamically allocated your array in the first place.
I have this path: ./demodir/a1/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1 When I allocate the space for the path name in a string using just one (1) extra byte (for the '\0') the string prints differently. ``` path = (char *) malloc( strlen(dirname) + strlen(direntp->d_name) + 1 ); ``` Prints: ./demodir/a1!�/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1 � .... is the issue I need to all "+2" bytes to the memory allocation, besides the length of the content.. Why is that?
You need the extra byte to include the slash '/' separating the dirname from the basename. ``` char *path = (char *) malloc( strlen(dirname) + 1 + strlen(direntp->d_name) + 1 ); sprintf(path, "%s/%s", dirname, dirent->d_name) ```
How to catch error when program crashes? Example - Java when crash writes an error log to file. I writed this code to cause an error: ``` int * invalidPointer = NULL; printf("%d\n", invalidPointer[0]); ``` And java crashes and saving an error log (hs_error_pid(pid).log) to file, I want to handle an error in program written with C (not in Java, this is only example) Second example - Chrome when crashes shows information and we can restart browser by clicking yes.
Though it isundefined behavior, you can use this if you're getting segmentation fault. ``` #include <signal.h> #include <stdio.h> void Segfault_Handler(int signo) { fprintf(stderr,"\n[!] Oops! Segmentation fault...\n"); } int main() { signal(SIGSEGV,Segfault_Handler); return 0; } ```
Can someone explain why the output of this program is false?? x && y gives 1. Still the output is false. ``` #include <stdio.h> int main() { int x = 1, y = 2; if(x && y == 1) { printf("true."); } else { printf("false."); } return 0; } ```
Because==has a higher precedence than&&So first this get's evaluated: ``` x && (y == 1) ``` ``` y == 1 // 2 == 1 //Result: false ``` Which is false and then second: ``` x && false //1 && false //Result: false ``` So the if statement will be false For more information about operator precedence see here:http://en.cppreference.com/w/cpp/language/operator_precedence
I've been trying to call the main method of a class and pass it some arguments. My code is as below: ``` args = (*env)->NewObjectArray(env, 2, myClass, NULL); arg1 = (*env)->NewStringUTF(env, "Hello"); arg2 = (*env)->NewStringUTF(env, World!"); (*env)->SetObjectArrayElement(env, args, 0, arg1); (*env)->SetObjectArrayElement(env, args, 1, arg2); (*env)->CallStaticVoidMethod(env, myClass, mainMethod, args); ``` But it seems that it doesn't work. When I print theargsarray in the java code it prints null.
You're creating an Array of "myClass" instead of String ``` stringClass = (*env)->FindClass(env, "java/lang/String"); args = (*env)->NewObjectArray(env, 2, stringClass, NULL); ```
I have a context free grammar (CFG). I want to write a c++ code to do the same thing like CFG. Is there any built-in function or easy way to convert? Or, something to execute CFG?
You are looking forparser generators(sometimes called compiler-compilers). You already know aboutbison. You could tryANTLR3(orANTLR4for Java). Here is acomparison. BTW, most of the time programming languages are not really context free (e.g. because they need somesymbol table). Also, some parsers are hand writtenrecursive descent ones, (e.g. GCC, seethis) Notice that acontext-free grammaris aspecificationfor some formal syntax (which you couldimplementin some parser). Butsemanticsandpragmaticsalso matters.
I want to run server-client program in eclipse. I made two different projects one for client and other one to server. while running the project for client i am getting error as "connect no such file or directory in eclipse". I tried the same by putting one project in different workspace still getting the same error.. i would like to know what changes i should make to fix this problem??
This error is to do with you #include file not being found. Either you have not included the appropriate library for the code you're trying to execute, or the library does not exist in the directory. Regardless, for this issue to be resolved you need to provide a sample of your code
I have an application which gets 10 different numbers (which are less than 100) as input. If any thing other than number is entered, it should display "Invalid input" ex: If I enter 'C' which is not a number between 1 to 100, Program should display "Invalid input" I don't want to compare the input with all the characters and special symbols If the number is a single digit number, isdigit() or isalpha() does the job. How can I solve this?
I would just use something like this:scanf("%d", &variable)and checkreturn valueof this function. It will work unless you have something other than digit on stdin. You can put this in the loop and catch this error using return value ofscanf()function.
I am new to embedded and I am confused with this word "Platform" whether it specifies about the 'board' or 'Operating system'? For example, some says like, "I am working on windows platform" and some says like "The platform I am using is Raspberry Pi" etc. I know this is a silly or stupid question for many but if you need to block this question, kindly do it after some answers.
The termplatformis used to denote any collection of software, services and resources that, within a specific context, are considered a given so they can be used as building blocks for application software (or to build a higher level platform on top of that - something considered a platform in another context) refer the awesome answerHERE
I'm using Sublime Text 3 for C programming. I want to compile and run my programs in the gnome terminal using a keybinding or something like that instead of the ST3 console (like CodeBlocks does). How can I do it?
ClickTools->Build System->New build systemto add a new build system, copy following code: ``` { "cmd" : ["gnome-terminal -x bash -c \"gcc $file_name -o ${file_base_name} -lm -Wall; ./${file_base_name}; exec bash\""], "selector" : "source.c", "shell":true, "working_dir" : "$file_path" } ``` Save this file. Then clickTools->Build Systemto choose the newly stored build system. Every time you press "Ctrl+B", the keybinding ofTools->build, it will run gnome-terminal and compile&run your program automatically.
How to catch error when program crashes? Example - Java when crash writes an error log to file. I writed this code to cause an error: ``` int * invalidPointer = NULL; printf("%d\n", invalidPointer[0]); ``` And java crashes and saving an error log (hs_error_pid(pid).log) to file, I want to handle an error in program written with C (not in Java, this is only example) Second example - Chrome when crashes shows information and we can restart browser by clicking yes.
Though it isundefined behavior, you can use this if you're getting segmentation fault. ``` #include <signal.h> #include <stdio.h> void Segfault_Handler(int signo) { fprintf(stderr,"\n[!] Oops! Segmentation fault...\n"); } int main() { signal(SIGSEGV,Segfault_Handler); return 0; } ```
Can someone explain why the output of this program is false?? x && y gives 1. Still the output is false. ``` #include <stdio.h> int main() { int x = 1, y = 2; if(x && y == 1) { printf("true."); } else { printf("false."); } return 0; } ```
Because==has a higher precedence than&&So first this get's evaluated: ``` x && (y == 1) ``` ``` y == 1 // 2 == 1 //Result: false ``` Which is false and then second: ``` x && false //1 && false //Result: false ``` So the if statement will be false For more information about operator precedence see here:http://en.cppreference.com/w/cpp/language/operator_precedence
I've been trying to call the main method of a class and pass it some arguments. My code is as below: ``` args = (*env)->NewObjectArray(env, 2, myClass, NULL); arg1 = (*env)->NewStringUTF(env, "Hello"); arg2 = (*env)->NewStringUTF(env, World!"); (*env)->SetObjectArrayElement(env, args, 0, arg1); (*env)->SetObjectArrayElement(env, args, 1, arg2); (*env)->CallStaticVoidMethod(env, myClass, mainMethod, args); ``` But it seems that it doesn't work. When I print theargsarray in the java code it prints null.
You're creating an Array of "myClass" instead of String ``` stringClass = (*env)->FindClass(env, "java/lang/String"); args = (*env)->NewObjectArray(env, 2, stringClass, NULL); ```
I have a context free grammar (CFG). I want to write a c++ code to do the same thing like CFG. Is there any built-in function or easy way to convert? Or, something to execute CFG?
You are looking forparser generators(sometimes called compiler-compilers). You already know aboutbison. You could tryANTLR3(orANTLR4for Java). Here is acomparison. BTW, most of the time programming languages are not really context free (e.g. because they need somesymbol table). Also, some parsers are hand writtenrecursive descent ones, (e.g. GCC, seethis) Notice that acontext-free grammaris aspecificationfor some formal syntax (which you couldimplementin some parser). Butsemanticsandpragmaticsalso matters.
I want to run server-client program in eclipse. I made two different projects one for client and other one to server. while running the project for client i am getting error as "connect no such file or directory in eclipse". I tried the same by putting one project in different workspace still getting the same error.. i would like to know what changes i should make to fix this problem??
This error is to do with you #include file not being found. Either you have not included the appropriate library for the code you're trying to execute, or the library does not exist in the directory. Regardless, for this issue to be resolved you need to provide a sample of your code
I have an application which gets 10 different numbers (which are less than 100) as input. If any thing other than number is entered, it should display "Invalid input" ex: If I enter 'C' which is not a number between 1 to 100, Program should display "Invalid input" I don't want to compare the input with all the characters and special symbols If the number is a single digit number, isdigit() or isalpha() does the job. How can I solve this?
I would just use something like this:scanf("%d", &variable)and checkreturn valueof this function. It will work unless you have something other than digit on stdin. You can put this in the loop and catch this error using return value ofscanf()function.
I am new to embedded and I am confused with this word "Platform" whether it specifies about the 'board' or 'Operating system'? For example, some says like, "I am working on windows platform" and some says like "The platform I am using is Raspberry Pi" etc. I know this is a silly or stupid question for many but if you need to block this question, kindly do it after some answers.
The termplatformis used to denote any collection of software, services and resources that, within a specific context, are considered a given so they can be used as building blocks for application software (or to build a higher level platform on top of that - something considered a platform in another context) refer the awesome answerHERE
I'm using Sublime Text 3 for C programming. I want to compile and run my programs in the gnome terminal using a keybinding or something like that instead of the ST3 console (like CodeBlocks does). How can I do it?
ClickTools->Build System->New build systemto add a new build system, copy following code: ``` { "cmd" : ["gnome-terminal -x bash -c \"gcc $file_name -o ${file_base_name} -lm -Wall; ./${file_base_name}; exec bash\""], "selector" : "source.c", "shell":true, "working_dir" : "$file_path" } ``` Save this file. Then clickTools->Build Systemto choose the newly stored build system. Every time you press "Ctrl+B", the keybinding ofTools->build, it will run gnome-terminal and compile&run your program automatically.
``` int bar(const size_t value) { char *d = (char*) value; *d = 'B'; } int main() { char bar = 'A'; bar((size_t)&d); } ``` Is usingsize_tto emulate a void pointer type legal? Why?What benefits/drawbacks does it have?
Fordatapointers, round trip from a pointer to an integer types back to theoriginalpointer type is well defined as long as the integer type is wide enough to hold the pointer without loss. size_thas been defined to hold object size. They are usually big enough to hold a pointer representation but that is not guaranteed and they were implementations where the assumption didn't hold. uintptr_tandintptr_tare integer types defined to be wide enough to hold a pointer without loss. Forfunctionpointers, I'm aware of no such guarantee.
This may seem to be a dumb question but I don't really have a good understanding offork()other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed viafork(), how to correctly assign tasks to parent process and child process?
Check the return value offork. The child process will receive the value of0. The parent will receive the value of the process id of the child.
This may seem to be a dumb question but I don't really have a good understanding offork()other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed viafork(), how to correctly assign tasks to parent process and child process?
Check the return value offork. The child process will receive the value of0. The parent will receive the value of the process id of the child.
``` #include <stdio.h> #include <stdint.h> int p() { char data[7]="Hello!\0"; uint64_t *ptr=((uint64_t)data + 0x18); printf("%s",data); (*ptr)-=10; return 0x00; } int main(int argc,char **argv) { p(); } ```
As mentioned in other answers and in comments writingchar data[7]="Hello!\0";could be a problem but I dont think that is the only source of problem here. My guess is :uint64_t *ptr=((uint64_t)data + 0x18); (*ptr)-=10;By doing this probably you are modifying return address from stack or doing something like that.
This question already has answers here:what makes java not pure object oriented language? [closed](3 answers)Closed8 years ago. What is difference between these two.I google it down but could not find the satisfied answer.For example java is a oop(Object oriented programming) but not pure oop(was written on some sites).Can anybody explain?
Java is oop but not pure because, There are Primitive data type in java like int, float etc. and they are not classes/Objects. This is only one reason that java is not Pure OOP. For example of Pure OOP . Objective C is Pure OOP language in which every thing is in the form of object.
Here's a simple program: simple.c ``` int inverse(int input) { if( input == 0 ) return 1; else return 0; } int main() { inverse(1); return 0; } ``` My question is: Doesinverse()push a local copy of the parameter named ``` int input ``` or does it just keep referencing the parameter each time it is accessed?
Please keep in mind.int inputdefinition is local to the functioninverse(). So each timeinverse()is called, stack space forinputis allocated separately and onceinverse()has finished execution, there will be no existence ofinputvariable. * Without any compiler optimization
My program executes with two arguments (put inargv) like below: ``` $ myProgram input output ``` How do I redirect allprintf(..)to the output file? I saw some suggestion about usingfflush(stdout)but I haven't used it before. Could anyone please show me an example?
If you are trying to redirect the output of your program then that can be done easily from the command line itself with out adding any additional code to your program. Just modify the command like this. ``` $ myProgram input output > example.txt ``` And if you want to append the output to the end of your output file then the command will be like this. ``` $ myProgram input output >> output ``` However in both cases nothing will be printed on the screen. The entire output of the program will be written in the file.
When I run this program and give laks as input I get laks as output plus one extra character.Also if I want to break the program as soon as a new line is entered i.e when I press enter I want the loop to discontinue but while statement does not seem to work. ``` # include <stdio.h> # include <conio.h> # include <ctype.h> void main() { clrscr(); char person[5]; int i; printf("enter person name \n"); for(i=0;i<5;i++) { scanf("%c",&person[i]); //while(person[i]!='/n') } printf("%s",person); getch(); } ```
You are not null terminating your string So have ``` person[i] = '\0'; ``` after the for loop. I would have ``` char person[6] = ""; ``` and later do a scan