question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to create a Makefile that compiles multiple C files for use in Minix. How would I change the Makefile so that it compiles multiple files at the same time? Below is the current state of my Makefile. ``` CFLAGS = -D_POSIX_SOURCE LDFLAGS = CC = cc LD = cc PROG = test OBJS = test.o $(PROG)...
Split it up this way: ``` PROG1 = test PROG2 = test2 OBJ1 = test.o OBJ2 = test2.o $(PROG1): $(OBJ1) $(LD) $(LDFLAGS) $(OBJ1) -o $(PROG1) $(PROG2): $(OBJ2) $(LD) $(LDFLAGS) $(OBJ2) -o $(PROG2) ``` etc
I am trying to declare an array ofstructs, is it possible to initialize all array entries to a defaultstructvalue? For example if mystructis something like ``` typedef struct node { int data; struct node* next; }node; ``` Is there a way to declare data to4and next tonull? Wh...
Sure: ``` node x[4] = { {0, NULL}, {1, NULL}, {2, NULL}, {3, NULL} }; ``` Even this should be fine: ``` node y[4] = { {0, y + 1}, {1, y + 2}, {2, y + 3}, {3, NULL} }; ```
``` list *attachnode(list *tmp,list *hd)//function to get the ip address { if(hd==NULL) { hd=tmp; } else { tmp->next=hd; hd=tmp; } return(hd); } ``` tmp->next=hd giving a warning of incompatible type pointer conversion by default "next" i...
you say, "next" is "list type" but i believe it should be "list *" type but without your typedef we cannot be sure okay, your comment, my edith: it should betypedef struct list {...; struct list *next;} list; the reason is, that C does need a forward declaration, else it could not determine the "type" of next. vis...
If one were to declare a plan as such, then immediately destroy it, is there a risk for segmentation fault? ``` fftw_plan myPlan; fftw_destroy_plan(myPlan); ``` My gut feeling is maybe, but I do not know if fftw does any internal bookkeeping on these things to avoid freeing unallocated memory.
Well why take the chance? fftw_plan is anopaque pointer type. So you can write ``` fftw_plan myPlan = NULL; // some code which may create a plan if (myPlan) fftw_destroy_plan(myPlan); ```
Hello. I'm new to C. I want to separate an URL into 2 part split by the first "/" in C. I have the code: ``` char *token1, *token2; token1 = strtok("website URL here", "/"); token2 = strtok(NULL, "/"); ``` the problem is, if the website is like: "www.foo.com/foo/" it works. I got "www.foo.com" and "foo" but if the...
You can usestrchrto find the first index of/: ``` /* char *url; */ char *first_slash = strchr(url, '/'); ``` Then,first_slash + 1is the rest of the url (it isNULLif/is not in the string). If you want to deal with 2 C strings, then just set to 0: ``` *first_slash = 0; ``` Then, your domain isurland the rest is inf...
The following code is giving me a Segmentation fault ``` void parseInput(char usrIn[]) { char retCmd[MAX_INPUT]; retCmd[0] = usrIn[0]; printf('Debug: %c\n', retCmd[0]); } ``` This is my first big project in C, but I think it's the printf giving me fault .. however I'm not sure...
Your original line: ``` printf('Debug: %c\n', retCmd[0]); ``` How it should be: ``` printf("Debug: %c\n", retCmd[0]); ``` Notice the change from single-quotes to double-quotes
I am having trouble trying to create an array then printing the first 10 elements from the array... this is what I have so far: ``` #include <stdio.h> int main() { char term[200][40]; FILE *ifp; int i; ifp = fopen("terms.txt", "r"); if (ifp == NULL){ fprintf(stderr, "Could not open file...\...
``` fgets(term, 40, ifp); //THIS IS WRONG ``` Modify for loop and remove above statement ``` for(i = 1; i < 11 && fgets(term[i-1], 40, ifp)!=NULL ;i++) { printf("%s", term[i-1]); } ```
I'm trying to create a char array in a similar way as using aprintfstatement. If I do this: ``` printf("%d:%d:%.2f", hours, minutes, time); ``` It will print out exactly how I want it. However I'm now trying to store this as a variable. I've been trying to do something like the line of code below, however I get a "...
You'll wantsprintf, it is the same asprintf, but instead outputs to a string, as you wish. EDIT:snprintfis indeed safer. (Thanks Troy)
i am trying to split a string with 2 delimiters '+' and '-' in C++ using a string find a delimiter... can anyone give me a go around... Using str.find(delimiter) example : a+b-c+d Output Required: a b c d Thanks in advance
Usingstd::string::substrandstd::string::find ``` std::vector<std::string> v ; //Use vector to add the words std::size_t prev_pos = 0, pos; while ((pos = str.find_first_of("+-", prev_pos)) != std::string::npos) { if (pos > prev_pos) v.push_back(str.substr(prev_pos, pos-prev_pos)); ...
The output of printBits('A') suppose to be 0100 0001 but I'm getiing 0100 0001 0100 1101 0000 0000. I can't seem to figure out the problem in my code below. ``` unsigned char getBit(unsigned char c, int n) { return c=(c&(1<<n))>>n; } void printBits(unsigned char c) { int i=7; while(i>=0){ printf("%d", (g...
Your output seems to match your input just fine, but your output shows you called your print function two more times. The output matches this sequence of calls: ``` printBits('A'); printBits('M'); printBits('\0'); ``` This is shownhere(after fixing a syntax error in your print function).
``` #include <stdio.h> int main() { int age; printf("Enter Your age: "); scanf("%lf", &age); printf("Your age is %d\n", age); return 0; } ``` If we run the program the prompt will be displayed on the terminal screen, even though there is no newline character at the end of the prompt. How can this...
That most likely happens because your C standard library chooses to flush the output buffers in its implementation ofscanf. That's a good idea because this is a common problem and you usually want the prompt at the same line as the cursor andit's not a performance problem because waiting for user input is way slower ...
This question already has answers here:Using strtok in c(7 answers)Closed9 years ago. Hey I'm currently learning c language. Is there any possibility to turnchar*type variable, which contains some words separated by spaces into an array of string(in c it'schar*[]) that way that each word on the original variable will...
C library Functionstrtok(): char * strtok ( char * str, const char * delimiters ); ``` #include <stdio.h> #include <string.h> int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," "); while (pch != NULL) { printf...
I had a question on my exam but i didnt understand what they wanted from me. Here are lines of code which has some mistakes but i didn't get it. ``` int a = 0; #pragma omp parallel for num_threads(4) for (int i = 0; i < 100000; i++) { a++;} ``` Actually, i'm thinking about a, as for me a must be inside of threads....
The problem is thata++operation is not atomic. I guess you should have learnt this term through your course, alternatively you can look up the definition onwikipedia.
I have a problem compiling the following exploit code: http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c I am using"gcc file.c"and"gcc -O2 file.c", but both of them results in the following errors: ``` sorbolinux-exec.c: In function ‘sc’: sorbolinux-exec.c:76: error: stray ‘\302’ in program sorb...
You have an invalid character on that line. This is what I saw:
The output of printBits('A') suppose to be 0100 0001 but I'm getiing 0100 0001 0100 1101 0000 0000. I can't seem to figure out the problem in my code below. ``` unsigned char getBit(unsigned char c, int n) { return c=(c&(1<<n))>>n; } void printBits(unsigned char c) { int i=7; while(i>=0){ printf("%d", (g...
Your output seems to match your input just fine, but your output shows you called your print function two more times. The output matches this sequence of calls: ``` printBits('A'); printBits('M'); printBits('\0'); ``` This is shownhere(after fixing a syntax error in your print function).
``` #include <stdio.h> int main() { int age; printf("Enter Your age: "); scanf("%lf", &age); printf("Your age is %d\n", age); return 0; } ``` If we run the program the prompt will be displayed on the terminal screen, even though there is no newline character at the end of the prompt. How can this...
That most likely happens because your C standard library chooses to flush the output buffers in its implementation ofscanf. That's a good idea because this is a common problem and you usually want the prompt at the same line as the cursor andit's not a performance problem because waiting for user input is way slower ...
This question already has answers here:Using strtok in c(7 answers)Closed9 years ago. Hey I'm currently learning c language. Is there any possibility to turnchar*type variable, which contains some words separated by spaces into an array of string(in c it'schar*[]) that way that each word on the original variable will...
C library Functionstrtok(): char * strtok ( char * str, const char * delimiters ); ``` #include <stdio.h> #include <string.h> int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," "); while (pch != NULL) { printf...
I had a question on my exam but i didnt understand what they wanted from me. Here are lines of code which has some mistakes but i didn't get it. ``` int a = 0; #pragma omp parallel for num_threads(4) for (int i = 0; i < 100000; i++) { a++;} ``` Actually, i'm thinking about a, as for me a must be inside of threads....
The problem is thata++operation is not atomic. I guess you should have learnt this term through your course, alternatively you can look up the definition onwikipedia.
I have a problem compiling the following exploit code: http://downloads.securityfocus.com/vulnerabilities/exploits/59846-1.c I am using"gcc file.c"and"gcc -O2 file.c", but both of them results in the following errors: ``` sorbolinux-exec.c: In function ‘sc’: sorbolinux-exec.c:76: error: stray ‘\302’ in program sorb...
You have an invalid character on that line. This is what I saw:
C : convert to integer using bits I need to get integer value from bit arrays of 0, 1. I want to pass integer arrays and get the decimal number using bit operator. The following is what I tried but does not work when I tried to pass int arrays, it works withchar* array. Is there any way that I can pass int arrays a...
Your loop condition assumes that the array is 0-terminated, which is valid for strings, but not integer arrays. One way to fix this would be to pass a length parameter along with the int pointer, so you know when to stop iterating. Also, in this expression: ``` (*bin_arr++ == '1') ``` you should remove the single ...
I try to allocate memory , store a string then print it but I think it didn't work. ``` #include<stdio.h> #include<windows.h> int main() { char* allochere; allochere = malloc(sizeof(char)); *allochere = "Hello"; printf("%s",allochere); return 0; } ```
The assignment to*allochereonly assigns a value to the first character of the uninitialized string. The value assigned is nonsensical to boot, since the right-hand side of the assignment is a pointer. (If you turn on compilation warnings, the compiler will warn you of problems with such an assignment.) To correctly i...
I need to find the descending order of the elements in an array of integers. Example: If I have an array: ``` x = {24, 55, 22, 1} ``` I want an algorithm in C that results in arrayorderwhere: ``` order = {2, 1, 3, 4} ``` Considering that 'my' arrayxcan become rather large (from 1k-1M), my question is as follows:...
I guess the more efficient way is the best known way. Eg: allocate a vector for all indices from 0 up to N-1 and initialize itsort the indices vector by using one of the efficient sorting algorithms egquicksortormerge sortbut by referring to the original data vector (you sort indices, you compare original data)
I want to Find wether a file named name is there or not without using dir/s subhang.txt. can you tell me how to do it using pipes and how to connect two C programs using Pipes
The command: ``` dir/s *.txt >search.txt | find "name" ``` ... doesn't work because the output ofdir/sgoes into the filesearch.txt. If you try: ``` dir/s *.txt | find "name" ``` ... that will output the results of thefindto the console, or ``` dir/s *.txt | find "name" >search.txt ``` ... will output the result ...
I'm actually working on a mini-project to determine the last date when the file was opened. My question is how to determine the last date when the file was opened in C under Windows. I just need some hints about that. thanks.
There are two such dates in Windows, accessible via theGetFileTimefunction: The Last Write Time (which only tracks files opened for writing) and the Last Access Time which tracks both reads and writes. Unfortunately, there is a performance option somewhere in the Registry that skips updating the last access date, and...
Can someone please explain to me why this code gives a Segmentation Fault: ``` char string[] = "this is a string"; char * string2 = "this is another string"; printf("%s\n",string ); printf("%s\n", string2); printf("string[2]= %s, string2 = %s\n", string[2], &string2 ); ``` It also gives the same error when I try to...
The first two are fine but in the last one you probably want: ``` printf("string[2]= %c, string2 = %p\n", string[2], (void *)&string2 ); ^ ^ ``` You are getting a segmentation fault because you are trickingprintfinto interpreting a small integer (string[2]) as a pointer (that's what%s...
Recently faced with an interesting interpretation of the EOF character console windows. On some machines running windows 7 codeputchar (255)&&putchar (-1)is displayed as a space character, and some as'a'character. The second confuses me. Tell me please, why is this happening?
EOFis not a character, it's more like a signal (not the Unix signal) indicating End-of-File. Is value is implementation dependent, but guaranteed to be unequal to any valid character, usually-1. When you useputchar(EOF), orputchar(-1), it's converted tounsigned char,255. But the ASCII value255isn't a printable charac...
I am writing pthread program which contain functions as given below and I want to call another function in between one function. ``` void *fun1(void *arg1) { fun2(NULL); } void *fun2(void *arg) { fun1(NULL); } ``` When I am calling another function as shown above I am getting error as shown below error: conflicting...
Declare : void *fun2(void *); beforefun1 The compiler assumes the default return type asintso you need to tell it the actual prototype before use
I'm debugging a program that could potentially have up to 20,000 lines output. The command prompt appears to truncate and only show the last 1000 so I can't see the ouptput the program gave at the begining. How can I fix this so I can scroll all the way up to the point where I run the program? I'm using Windows 7 and ...
Run cmd (as admin), go to Properties->Layout tab and increase the Screen buffer size to what you want, and enable "Apply these properties for future windows". Another option, just to check the output: Have it written to a file and read it later.
In the android sdk path sdk/bionic/libc/bionic/ there are the C API resource code, such as fork.c, ioctl.c etc.. when open ioctl.c: ``` #include <stdarg.h> extern int __ioctl(int, int, void *); int ioctl(int fd, int request, ...) { va_list ap; void * arg; enter code here va_start(ap, request); a...
As mentioned, the _ioctl is just a wrapper to a syscall, implemented in asm. In the AOSP code, it can be found in bionic/libc/arch-XXX/syscalls/_ioctl.S where arch-XXX is arch-arm, arch-x86 or arch-mips depending on your target architecture.
Does such a function result in a dangling pointer? ``` int *foo () { int a[2] = {2, 3}; int *p = NULL; p = a; return p; } ```
Yes. You are returning a pointer to an array with automatic storage duration. When the function returns the pointer is invalid.
C : convert to integer using bits I need to get integer value from bit arrays of 0, 1. I want to pass integer arrays and get the decimal number using bit operator. The following is what I tried but does not work when I tried to pass int arrays, it works withchar* array. Is there any way that I can pass int arrays a...
Your loop condition assumes that the array is 0-terminated, which is valid for strings, but not integer arrays. One way to fix this would be to pass a length parameter along with the int pointer, so you know when to stop iterating. Also, in this expression: ``` (*bin_arr++ == '1') ``` you should remove the single ...
I try to allocate memory , store a string then print it but I think it didn't work. ``` #include<stdio.h> #include<windows.h> int main() { char* allochere; allochere = malloc(sizeof(char)); *allochere = "Hello"; printf("%s",allochere); return 0; } ```
The assignment to*allochereonly assigns a value to the first character of the uninitialized string. The value assigned is nonsensical to boot, since the right-hand side of the assignment is a pointer. (If you turn on compilation warnings, the compiler will warn you of problems with such an assignment.) To correctly i...
I need to find the descending order of the elements in an array of integers. Example: If I have an array: ``` x = {24, 55, 22, 1} ``` I want an algorithm in C that results in arrayorderwhere: ``` order = {2, 1, 3, 4} ``` Considering that 'my' arrayxcan become rather large (from 1k-1M), my question is as follows:...
I guess the more efficient way is the best known way. Eg: allocate a vector for all indices from 0 up to N-1 and initialize itsort the indices vector by using one of the efficient sorting algorithms egquicksortormerge sortbut by referring to the original data vector (you sort indices, you compare original data)
I want to pass an integer from C# method into native C DLL set_power(), but get run-time error: "PInvokeStackImbalance" when C# calls the C function set_power(). C# declaration: ``` [DllImport("Ultrasound_Frame_Grabber.dll")] public static extern int set_power(int power_percent); ``` C# method: ``` int target_pow...
Usestdcallon the native side.
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 need for an application to generate a key event in order to emulate a keyboard.
I would guess that you can use e.g.gdk_display_put_event(), but your question is not very clear. Do you expect other applications than your own to see the emulated keyboard events? Not sure GDK can do that.
Whether there are situations when the object needs to be created in memory to a certain address? Where it can be necessary (example)? Thank you.
Take a look at placement new: "What uses are there for "placement new"?" Good examples are writing your own memory allocator, garbage collector, or trying to precisely lay out memory due to cache performance. It's a niche thing, but sometimes very useful.
I was expecting the below code to give segmentation fault. Since NULL pointer points to nothing, incrementing something that points to nothing is meaningless. But its printing 0,4,8,12,16. ``` #include<stdio.h> int main() { int *p ,i=0; p = NULL; for(i=0;i<5; i++) { printf("%d\n",p++); } ...
You'renotdereferncingp, you're converting it's storedvalueto anint. If you where doing: ``` printf("%d\n",*p++); ``` thenyou'd seg fault.
This question already has answers here:What is an undefined reference/unresolved external symbol error and how do I fix it?(39 answers)Closed9 years ago. I have created a shared library, copied it to /usr/lib, run ldconfig (it shows up on the list when run with -v) and copied the .h file into /usr/include. However wh...
#includewill include the header file when you compile your source code. However you also need to link to your shared library. For most unix compilers, that is done with the-l flag For a shared library with the namelibFoo.so, use the flag-lFoowhen linking your program.
I have some existing code in C: ``` extern const struct sockaddr_un addr = { .sun_family = AF_UNIX, .sun_path = "myreallylongpath" }; ``` Where sun_path is a character array. This used to compile fine as C in an older version of GCC. I have now converted it to C++ and am using GCC v4.7.2. I keep getting t...
Designated initializers were introduced in C99, GCC also supports them as an extension in GNU89, but not in C++. So you need to use the C89 style, which is also supported in C++. Since the struct has only these two fields: ``` extern const struct sockaddr_un addr = { AF_UNIX, "myreallylongpath" }; ``` Refer...
So I was going through the glimg section of the unofficial OpenGL library and came across something I found strange. In one of the functions a pointer parameter is being assigned to itself and I can't see how this could be accomplishing anything. Does this somehow force memory into cache or is it something else? Possi...
It's there to suppress the warning that the parameterin_faris not used in the function. Another way to suppress the warning is: ``` (void)in_far; ```
I am just not able to understand that why readdir() lists ".." as one of the files in the directory.Following is my code snippet ``` while((dir = readdir(d)) != NULL) { printf("%s \n", dir->d_name); //It displayed .. once and rest of the time file names } ```
The.and..represent the current and parent directory and are present in all directories (see footnote below).readdir()does not filter them out as they are valid entries within a directory. You can do the following to filter them out yourself. ``` while((dir = readdir(d)) != NULL) { if (strcmp(dir->d_name, ".") =...
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 As I understand a byte is comprised of 8 bits or byte and it has an address assign to it my question is if ...
What is commonly thought of as the "address" of any object or variable is the address of thefirst(lowest) byte in that variable. So if, you have a variable of type std::uint64_t (8 bytes) a pointer to that variable will be to it's first byte, while the following 7 addresses contain the other 7 bytes. Now, theorderin w...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
jnetpcapincludes the classPcapDumperwhich will write an array of bytes to a pcap file asdocumented here. [note to original questioner: this answer was downvoted because i answered your question, and criticised others for closing a reasonable question, not because the answer is actually wrong in any way]
So I'm doing a program that deals with $PATH and it gotta test each path to see if that command is located in that path and i was using the system() method , but i get all the status code for the paths that do not have that command. is there a way to stop the status code? For example, when I type ``` echo hi ``` i g...
You can use redirection ``` some_cmd 2>/dev/null ```
This question already has answers here:Compound literals in MSVC(4 answers)Closed9 years ago. Excuse me for the title of this question, I will probably update the title once I have my answer. I have this ancient code compiling and working with gcc 4.x: ``` struct S { int a; int b; }; int main(void) { r...
It's calledcompound literal, which is introduced in C99. The relevant part in the standard is6.5.2.5 Compound literals The bad news is Visual Studio only supports C89 right now, so this feature is not supported in Visual Studio.
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 have 2 functions in my code, namelyvoid compare(...)andvoid checklist(...). Invoid compare(...), I havei...
No, labels are local to the function in which they are defined. And programs would be a real mess otherwise. You should makeReselectiona function of its own.
I'm trying to create a cross-platform application that is using client applications written in C for MariaDB. But MariaDB offers a different library for each operating system and architecture for each of these. I need to know if there is a way to set up a C++ project for when you compile on Windows then take Windows l...
On linux you'll want to use the distribution's repository's mariadb, on Windows, you'll need to compile it yourself or ship the official release. It's best to use something lik CMake which allows you to either detect the presence of a library or let the builder point it to where it can be found at build time, and don...
I have a large block of code inside main and would like to return to the top of main and run through again if a certain variable in 'code' is true. How would I do this? ``` #include <stdio.h> void main(void) { // if varable in code is true return to here //code // // // } ```
``` int main(void) { int gotostart=0; // if varable 'gotostart' in code is true return to here beginning: // code [...] if(gotostart) goto beginning; return 0; } ``` as Armen has rightly pointed out,gotodeserves some warning. the most popular ist Dijsktra'sGOTO statements considered harmful, as it...
``` #include <stdio.h> int main(void){ printf("%2s\n","Monday"); //output: Monday getch(); } ``` Above code prints whole Monday. I want it to print "Mo". Why doesn't this work in Visual Studio or am I coding wrong?
%2sspecifies the padding, which will never shorten the string. To print fewer characters than are present in the string, specify the precision as%.2s: ``` printf("%.2s", "Monday"); //output: Mo ``` Also, note thatgetchis not a standard C function.
I was making a basic program of strings and did this. There is a string in this way: ``` #include<stdio.h> int main() { char str[7]="network"; printf("%s",str); return 0; } ``` It printsnetwork.In my view, it should not print network. Some garbage value should be printed because'\0'does not end this char...
That's because ``` char str[7]="network"; ``` is the same as ``` char str[7]={'n','e','t','w','o','r','k'}; ``` stris a validchararray, but not a string, because it's no null-terminated. So it's undefined behavior to use%sto print it. Reference:C FAQ: Is char a[3] = "abc"; legal? What does it mean?
I'm trying to create a cross-platform application that is using client applications written in C for MariaDB. But MariaDB offers a different library for each operating system and architecture for each of these. I need to know if there is a way to set up a C++ project for when you compile on Windows then take Windows l...
On linux you'll want to use the distribution's repository's mariadb, on Windows, you'll need to compile it yourself or ship the official release. It's best to use something lik CMake which allows you to either detect the presence of a library or let the builder point it to where it can be found at build time, and don...
I have a large block of code inside main and would like to return to the top of main and run through again if a certain variable in 'code' is true. How would I do this? ``` #include <stdio.h> void main(void) { // if varable in code is true return to here //code // // // } ```
``` int main(void) { int gotostart=0; // if varable 'gotostart' in code is true return to here beginning: // code [...] if(gotostart) goto beginning; return 0; } ``` as Armen has rightly pointed out,gotodeserves some warning. the most popular ist Dijsktra'sGOTO statements considered harmful, as it...
``` #include <stdio.h> int main(void){ printf("%2s\n","Monday"); //output: Monday getch(); } ``` Above code prints whole Monday. I want it to print "Mo". Why doesn't this work in Visual Studio or am I coding wrong?
%2sspecifies the padding, which will never shorten the string. To print fewer characters than are present in the string, specify the precision as%.2s: ``` printf("%.2s", "Monday"); //output: Mo ``` Also, note thatgetchis not a standard C function.
I was making a basic program of strings and did this. There is a string in this way: ``` #include<stdio.h> int main() { char str[7]="network"; printf("%s",str); return 0; } ``` It printsnetwork.In my view, it should not print network. Some garbage value should be printed because'\0'does not end this char...
That's because ``` char str[7]="network"; ``` is the same as ``` char str[7]={'n','e','t','w','o','r','k'}; ``` stris a validchararray, but not a string, because it's no null-terminated. So it's undefined behavior to use%sto print it. Reference:C FAQ: Is char a[3] = "abc"; legal? What does it mean?
I have a small C function and I want to make a hex file for it. Running ``` gcc -c in.c ``` makes an object file But I need hex file for this standalone function. I need to put this on a separate location, so that I can simply JMP to this location from my main code. But I want this to be in hex format. I cant do a...
By usingobjcopywe can make hex file ``` gcc -c example.c objcopy --change-address 0xE0000 -O ihex example.o example.hex ``` it will generateexample.hexfile useBless Hex Editorto see the .hex file clearly
I try to use some global variable in my project, but don't work. I declared my variable like this: In file kernel.h : ``` extern DBConnection * conn; ``` And, in my other file, called kernel.c, i do this: ``` #include "kernel.h" int get_info() { conn = (DBConnection *) malloc(sizeof(DBConnection)); } ``` But...
You provided a declaration but you also need adefinition. Add this to yourkernel.c, at the top after the include: ``` DBConnection * conn; ```
I have a struct that contains a string and a length: ``` typedef struct string { char* data; size_t len; } string_t; ``` Which is all fine and dandy. But, I want to be able to output the contents of this struct using aprintf-like function.datamay not have a nul terminator (or have it in the wrong place), so I c...
Assuming that your string doesn't have any embedded NUL characters in it, you can use the%.*sspecifier after casting thesize_tto anint: ``` string_t *s = ...; printf("The string is: %.*s\n", (int)s->len, s->data); ``` That's also assuming that your string length is less thanINT_MAX. If you have a string longer than...
I'm registering SIGSEGV (for Segmentation fault) Usingsigaction()function. It working in all cases but except one case i.e. when stack is overflowing.I searched to resolve this problem. Then I get the answer, we have to assign alternate Stack. But I don't know how to assign altrenate stack for signal registration. Ple...
You can do it withsigaltstack. ``` stack_t stack = { .ss_sp = malloc(SIGSTKSZ), .ss_size = SIGSTKSZ, .ss_flags = 0 }; if (sigaltstack(&stack, NULL)) perror("sigaltstack"); ``` At this point just establish your signal handler withsigactionand usesa_flags = SA_ONSTACK.
I am trying to get the coefficients of the Taylor series expansion of arbitrary functions. The input function has to be in the form of variables, and the output has to contain only the coefficients. I have tried some MATLAB functions like 'taylor', but they give the entire expansion in the form of an expression writt...
Are you looking forthis function?
``` for(i=0;i<t;++i) { scanf("%d",&arr[i]); scanf("%d",&brr[i]); a=arr[i]; b=brr[i]; } ``` This code block is taking inputs in two separate line(after pressing enter),ex1245How to modify it so that it take both the numbers in a single line(after pressing space),ex 12 45
How to modify it so that it take both the numbers in a single line(after pressing space) Your code already does this (it already works if you pass "12 45" - you can put any amount of whitespace between them). If you want to you can use a singlescanfcall with something like: ``` scanf("%d %d", &arr[i], &brr[i]); ``...
I'm registering SIGSEGV (for Segmentation fault) Usingsigaction()function. It working in all cases but except one case i.e. when stack is overflowing.I searched to resolve this problem. Then I get the answer, we have to assign alternate Stack. But I don't know how to assign altrenate stack for signal registration. Ple...
You can do it withsigaltstack. ``` stack_t stack = { .ss_sp = malloc(SIGSTKSZ), .ss_size = SIGSTKSZ, .ss_flags = 0 }; if (sigaltstack(&stack, NULL)) perror("sigaltstack"); ``` At this point just establish your signal handler withsigactionand usesa_flags = SA_ONSTACK.
I am trying to get the coefficients of the Taylor series expansion of arbitrary functions. The input function has to be in the form of variables, and the output has to contain only the coefficients. I have tried some MATLAB functions like 'taylor', but they give the entire expansion in the form of an expression writt...
Are you looking forthis function?
``` for(i=0;i<t;++i) { scanf("%d",&arr[i]); scanf("%d",&brr[i]); a=arr[i]; b=brr[i]; } ``` This code block is taking inputs in two separate line(after pressing enter),ex1245How to modify it so that it take both the numbers in a single line(after pressing space),ex 12 45
How to modify it so that it take both the numbers in a single line(after pressing space) Your code already does this (it already works if you pass "12 45" - you can put any amount of whitespace between them). If you want to you can use a singlescanfcall with something like: ``` scanf("%d %d", &arr[i], &brr[i]); ``...
This question already has an answer here:Why doesn't gcc allow a const int as a case expression?(1 answer)Closed9 years ago. I did this code only for learning purpose. But while doing so I found a problem. Here x is constant integer,still compiler is giving me error. I am using gcc compiler. Please explain what is th...
you can use the preprocessor as a workaround: ``` #define X 10 // ... case X: ```
I don't understand why the following code prints out7 2 3 0I expected it to print out1 9 7 1. Can anyone explain why it is printing7230?: ``` unsigned int e = 197127; unsigned char *f = (char *) &e; printf("%ld\n", sizeof(e)); printf("%d ", *f); f++; printf("%d ", *f); f++; printf("%d ", *f); ...
Computers work with binary, not decimal, so 197127 is stored as a binary number and not a series of single digits separately in decimal 19712710= 0003020716= 0011 0000 0010 0000 01112 Suppose your system useslittle endian,0x00030207would be stored in memory as0x07 0x02 0x03 0x00which is printed out as (7 2 3 0) as e...
It is possible to check if an app bundle's binary process is running in 32 or 64 bit mode, asanswered in this question, but I can verify that it only works with GUI processes. However, I need to also check processes that don't have a GUI and is not part of a bundle. So, programmatically,without calling system functi...
Ok, so I finally found the answer was already on SOhere, for Carbon. In order to use that code now, this include is required: ``` #include <sys/sysctl.h> ``` Also, it appears that the member to the process structure has changed from ``` proc->kp_proc.p_flags ``` to this: ``` proc->kp_proc.p_flag ```
I am using openCV to write a code that can find and replace one image with another image Here is my 1st image Now i have 2nd image as this I need to replace the second image with this and final output should be like this So how to start about ? I am not sure how can i find it, I tried usingTemplate Matchingbut th...
SURF algorithm, that's you want it.OPENCV SURF Example
Is this valid in C language? ``` #include <stdio.h> int main() { int i = 5; int a[i]; // Compiler doesn't give error here. Why? printf("%d",sizeof(a)); //prints 5 * 4 =20. 4 is the size of integer datatype. return 0; } ``` Compiler doesn't give error at the statementint a[i];. i isn't a constant then ho...
Yes, this is valid as ofC99, and is called avariable-length array(VLA). In other words, it has been in an official language standard for around 14 years. No, it's not valid in C++,see this questionfor details. Also note thatsizeofis not a function, so that can be written asprintf("%zu\n", sizeof a);which also uses t...
Given a pointer I want to compare the first two bytes to fixed values.datais a void pointer. Is there a "better" way than this: ``` unsigned char foo[] = {0xFF, 0x3B}; memcmp(data, foo, 2); ``` Maybe where I dont have to create a new char array? Thanks!
You should certainlytrydoing it usingmemcmp(), but if that creates overhead you can do it like@LS_devsuggested, although I would suggest doing explicit character accesses to avoid the endianness issue: ``` if(((unsigned char *) data)[0] == 0xff && ((unsigned char *) data)[1] == 0x3b) { } ``` of course, it would make...
This question already has an answer here:Pointer to a specific fixed address(1 answer)Closed9 years ago. I need to write 0x00001234 in the address 0x8000000, is it possible in C?
If you work with hardware register in embedded system then standard way is: ``` int volatile * const p_reg = (int *) 0x8000000; *p_reg = 0x1234; ``` You can have a lot of problems with optimizing compiler, if you omitvolatile
I tried to degub c automake project with Cygwin in Windows. I ran the following: ``` ./configure CFLAGS="-g -o0" make ``` after that, I loaded ``` gdb file src/slim.exe ``` and it says ``` no debugging symbols found ``` file out says: ``` file src/slim.exe src/slim.exe: PE32+ executable (console) x86-64 (str...
What you have to do is search for *.sym (Symbol files) in obj directory Then ``` gdb gdb>attach <process -id> gdb> symbol-file <path of symbol file> ```
How can we handle exceptions and errors in C like C++ and Java we usetry {}andcatch{}? Is there any way in C?
No, you can't but there are some patterns usinggoto(Goto is notalwaysevil). Example taken fromthis site ``` int foo(int bar) { int return_value = 0; allocate_resources_1(); if (!do_something(bar)) goto error_1; allocate_resources_2(); if (!init_stuff(bar)) goto error_2; allocate_resources_3(...
This one prints 100: ``` int j=2; int i= pow(10,2); printf("%d\n", i); ``` and this one prints 99: ``` int j=2; int i= pow(10,j); printf("%d\n", i); ``` Why?
What's going on is that you have a C implementation whose standard library has a very low quality implementation ofpowwhich is returning inexact results even when the exact result is representable in the type (double). The call topow(10,2)seems to producing the value just below100.0, which, when rounded to an integer,...
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 want to use c dll in my javascript code. Is that possible to do that usingnode? Thanks! Seems to be po...
I'm assuming you meannode.jsand the answer is yes. Look up building native modules fornode.js.
Is there a way to get the parent of the parent of my pid? There isgetpid()andgetppid(), I'm looking for the "getpppid()" PS: I'm on Linux, and the code will be run only on Linux (Not Unix nor any other variants)
Here you are. ``` pid_t getpppid(void) { char exe[256],proc[81],state; FILE *fp; int pid,ppid=-1; snprintf(proc,81,"/proc/%d/stat",(int)getppid()); fp=fopen(proc,"r"); if(fp) { fscanf(fp,"%d %s %c %d",&pid,exe,&state,&ppid); fclose(fp); } return (pid_t)ppid; } ``...
So, as far as I can tell, there wasn't another issue for this that was recent enough to be compatible with new major updates.I am programing on a Mac using XCode 4.I need to write a program for Windows.How would I do this, and is it the same exact code just compiled differently?!?Any and all help would be appreciated,...
If you stick strictly to the subset of POSIX C supported by both Mac and Windows (which implicitly limits you to console applications), you can possibly get a Windows cross-compiler for OS X and build applications that way. However, you will likely find your life vastly simplified if you just run Windows in a VM (or ...
Why does this line cause a segfault? From what I know about pointers, and also from debugger output, the assignment should work. ``` int delimChar(char **in ){ //in is a pointer to a pointer to the start of a char del = '|'; // string with atleast two | characters while (**in!=del){ (*in)++; } (*...
I reproduced it by calling the function wrong: ``` int main() { char *ptr = "one|two|three"; // Wrong! *ptr cannot be modified! // delimChar(&ptr); } ``` Here is the fixed version: ``` int main() { char val[] = "one|two|three"; char *ptr = val; // Right delimChar(&ptr); } ```
I am trying to display a decimal as a hex. If I have a decimal such as 3703484078, how can I use fputc to display it as hex DCBEAEAE? Is there some formula that I could use?
Call the input number X.Call a string S that is initially blank.Compute X mod 16.Convert the answer you got from the previous step to a character using the following mapping: 0->'0' 1->'1' 2->'2' 3->'3' 4->'4' 5->'5' 6->'6' 7->'7' 8->'8', 9->'9' 10->'A' 11->'B' 12->'C' 13->'D' 14->'E' 15->'F'.Replace string S with the...
I'm on a Mac and in terminal I'm compiling my program ``` gcc -Wall -g -o example example.c ``` it compiles (there are no errors), but when I try to provide command line arguments ``` example 5 hello how are you ``` terminal responds with "-bash: example: command not found" how am supposed to provide the argument...
Run it like this with path: ``` ./example 5 hello how are you ``` Unless the directory where theexamplebinary is part of the PATH variable, what you have won't work even if the binary you are running is in the current directory.
One of my (embedded) targets only has a C89 compiler. I am working on a (hobby) project which targets multiple devices. Is there a way of compiling (transpiling?) a C11 code base into C89? (Otherwise I will have to code like it's 1989, literally.)
No I don't think that it is possible for all of C11. C11 has features that simply not exist in C89 or C99:_Generic,_Atomic,_Thread,_Alignof, well defined sequenced before ordering, unnamedstructandunionmembers ... These don't have counter parts in the older versions and would be really difficult toemulate. For any of...
I want to use getaddrinfo() but get only the first result. more specifically, I want the function to first scan the hosts file and fetch the first result found, and only if not found in hosts I want to query the dns server. is it possible? thanks.
You can't. It behaves as documented. You only have touseone result: that's up to you.
I'm implementing TCP in Objective C and C. When I send a Syn Packet to a server I do not get an answer. A pcap file of the packet can be found here:Tcp-Syn.pcap Is the packet malformed or am I missing some convention which leads to my packet being dropped?
Open your file in wireshark. Go toEdit->Preferences->Protocols->TCP, enable "Validate the TCP checksum if possible" You will find that the TCP checksum you've generated is wrong. The MAC addresses in the ethernet headers are all 0 as well, which looks odd - where's this packet going to ?
``` #include<stdio.h> int main() { printf("%s\n", "Hello"); printf("%s\n", &"Hello"); return 0; } Output : Hello Hello ``` Can anyone explain to me why"Hello"and&"Hello"produce the same result?
Applying&to "Hello" yields a pointer to that array (yes, it is an array and it doesn't decay to a pointer in this context). It still points tothe same location, but ithas a different type(it haschar (*)[6], i.e. a pointer to an array of 6 chars).printfignores the real type of the pointer and treats it as achar *so it...
Should I uselua_tointeger(), orlua_tonumber(), when converting Lua numbers tooff_tvalues? I checked the source code of Lua itself and I see that theirfile:seekfunction useslua_Number, notlua_Integer. I also see that theluaposixpackage useslua_tonumber()(or luaL_checknumber() etc) extensively, even to read file decri...
Sinceoff_tandsize_tare both integral types, you should uselua_tointeger. Fromthe source,lua_tointegeractually gets the number aslua_Number, thenconverts it tolua_Integer. The only concern is thatlua_Integermay be too small, but as it's implemented asptrdiff_twhich in practice is usually 32-bit on 32-bit machine and 6...
Hi I have this book with a practice question which I am unable to answer. And no...this is not a homework question. This is my self study from a book recommended to me called: "Computer systems, A programmer's perspective" Here is the question: Any help is appreciated!
lengthis unsigned, so if you pass0for that parameter,length - 1will beUINT_MAX, not-1like you want it to be; therefore the loop will run and you'll make acceses outside the size ofa.
I'm fairly new to Lua. While testing I discovered#INF/#IND. However, I can't find a good reference that explains it. What are#INF,#IND, and similar (such as negatives) and how do you generate and use them?
#INFis infinite,#INDis NaN. Give it a test: ``` print(1/0) print(0/0) ``` Output on my Windows machine: ``` 1.#INF -1.#IND ``` As there's no standard representation for these in ANSI C, you may get different result. For instance: ``` inf -nan ```
I am beginner in C and have started writing code in c. I am having doubts regarding the scope of variables. When any variable is written inside the block then its scope is inside that block. But, when return word is used how is the variable accessed outside the block? Example: ``` int add(int a, int b) { int c;...
It isn't accessed outside the block. When you doreturn c;, a copy ofc's value is returned, notcitself. ``` int foo() { int c = 3; return c; } ``` This just returns 3, thevaluecholds. Some languages permit the compiler to "cheat" by extendingc's scope, but this is anoptimizationand doesn't change the logic.
This is a simple test program where I am trying to get the func function to modify the variables a and b which are then used in the main function. Is there a way to get func to return the modified variables so they can be used? (preferably without using struct as I don't understand how it works) ``` #include <stdio.h...
If you want to modify variables in the calling function, you have to pass their address tofunc(i.e. pass a pointer to these variables ``` void func(int* a, int* b) { *a=*a+1; *b=*b+1; } func(&a,&b); ``` Your code passes its arguments by value. This means thataandbare copied into new variables which are ini...
Assuming the following lua code: ``` local FooTable={ ["FooKey"]="FooValue" } ``` The index of"FooValue"is"FooKey". So I can access it like this without any issues (Assuming FooTable is on top of the stack.): ``` lua_getfield(L, -1, "FooKey"); ``` When I try something like this: ``` local FooTable={ "FooValue" } ...
In the second case the index is number one, not a string "1". One way of getting the first element is using the following function: ``` void lua_rawgeti (lua_State *L, int index, int key); ``` Another way is to push a key on the stack and call: ``` void lua_gettable (lua_State *L, int index); ``` The first way wi...
I am new to c programming and I was coding some simple programs "Hello world" style. In all of these programs I put#include<stdio.h>in the top but I am not sure what this means exactly. I googled it and I found that stdio.h is a file that has commands for the preprocessor, but what is a preprocessor? I thought when ...
It looks for thestdio.hfile and effectively copy-pastes it in the place of this#includestatements. This file contains so-called function prototypes of functions such asprintf(),scanf(), ... so that compiler knows what are their parameters and return values.
``` #include<stdio.h> #include<string.h> int main() { char * p = "abc"; char * p1 = "abc"; printf("%d %d", p, p1); } ``` When I print the values of the two pointers, it is printing the same address. Why?
Whether two different string literals with same content is placed in the same memory location or different memory locations is implementation-dependent. You should always treatpandp1as two different pointers (even though they have the same content) as they may or may not point to the same address. You shouldn't rely ...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ...
Yes, it's possible if you use the C driver for MySQL.
Let's say I do something like: ``` char* test[] = {"foo","bar","car"}; ``` What exactly is this equivalent to if I did it the long way? Is this automatically creating memory that I will need to free? I'm just sort of confused. Thanks.
You are declaring an array of pointers. The pointers point to string literals. The variabletestfollows the normal rule, if it's an automatic variable(scope inside some function), when out of the function, it gets out of scope, so you don't have to free the memory. If it's statically allocated(global orstaticvariable)...
Let's say x = 2/3 and n = 10 then I would like to print: .6666666666 (10 sixes, because n is 10) instead of .6666666667 <- I don't want that seven!!!! How would you print in that way either in C or C++ ?
C: ``` double foo = 2.0 / 3.0; printf("%.10f", floor(foo * pow(10, 10)) / pow(10, 10)); ``` C++: ``` double foo = 2.0 / 3.0; std::cout << std::fixed << std::setprecision(10) << std::floor(foo * std::pow(10.0, 10.0)) / std::pow(10.0, 10.0); ```
When to use sqlite3_blob_write and sqlite3_blob_read? When this functions is more useful than sqlite3_prepare_v2 + sqlite3_bind_blob?
You use them when the blobs are too large for the memory available for your program, or when you need to access only a small part of a large blob. This matters mostly in embedded applications.
This question already has answers here:How garbage values are assigned to variables in c(6 answers)Closed9 years ago. In C++/C if we don't initialize a variable, it will have some garbage values right? I would like to know from where these values are coming? Is it assigned by the compiler? Does this value have range?...
Any value can be garbage. It's whatever was left over in that spot of memory from the last operation that occurred there. It is unpredictable and never reliable, but it could be 5 or 500.
I am beginner in C and have started writing code in c. I am having doubts regarding the scope of variables. When any variable is written inside the block then its scope is inside that block. But, when return word is used how is the variable accessed outside the block? Example: ``` int add(int a, int b) { int c;...
It isn't accessed outside the block. When you doreturn c;, a copy ofc's value is returned, notcitself. ``` int foo() { int c = 3; return c; } ``` This just returns 3, thevaluecholds. Some languages permit the compiler to "cheat" by extendingc's scope, but this is anoptimizationand doesn't change the logic.
This is a simple test program where I am trying to get the func function to modify the variables a and b which are then used in the main function. Is there a way to get func to return the modified variables so they can be used? (preferably without using struct as I don't understand how it works) ``` #include <stdio.h...
If you want to modify variables in the calling function, you have to pass their address tofunc(i.e. pass a pointer to these variables ``` void func(int* a, int* b) { *a=*a+1; *b=*b+1; } func(&a,&b); ``` Your code passes its arguments by value. This means thataandbare copied into new variables which are ini...
I am trying to count how many times a.appear in a single string passed in by the command line. callingmyprog "this...is a test." returnsThe count is 0? What am I doing wrong here? Note:I know this code may look odd but is for education purposes ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int m...
You are counting the number of commas, not of periods. To count periods change the if statement to: ``` if (*p =='.'){ count++; } ```
How can I define such a Lua function using C API? ``` function Caller(f) f() end ``` This is what I've tried but it crashes: ``` typedef lua_CFunction luaFunc; int Caller(lua_State* luaVM) luaFunc Func = lua_tocfunction(luaVM, 1); lua_pushcfunction(luaVM, Func); lua_call(luaVM, 0, 0); return 0...
The equivalent of the Lua code ``` function Caller(f) f() end ``` is ``` int Caller(lua_State* luaVM) lua_call(luaVM, 0, 0); return 0; } ```