question
stringlengths
25
894
answer
stringlengths
4
863
This question already has answers here:What does the question mark character ('?') mean?(8 answers)Closed9 years ago. Can someone help me to understand how this line work ? I know what it do but the '?' and ':' are not clear for me.. ``` C code: (buff[i - 1] == '\n') ? my_printf("%s", buff) : my_printf("%s\n", buff...
It means: If first part is true, do the second part or else do the third part. In your case, if last character of buff (buff[i-1]) is equal with end line ('\n'), print the buff. But if buff doesn't end with end line ('\n'), you print buff and then end line ("%s\n")
When I try to run the following program, it prints out the string but I still receive a warning:18 6 C:\Users\Starhowl\Documents\C problems\consoleproj\main.c [Warning] conflicting types for 'rawrprint' [enabled by default] ``` #include <stdio.h> #include <stdlib.h> char *text = "my test"; char *texta[] = {"a...
Thattextais an array of pointer tochar, and yourrawrprint()requires its arguments has type of pointer tochar. You should call it usingtexta[0]ortexta[1]as its argument, like this: ``` rawrprint(texta[0]); ``` Additionally, you had better declare a function before you call it, so that compiler can check the types of ...
I've programmed something similar and I'm wondering why it works... ``` char* produceAString(void){ char* myString; while(somethingIsGoingOn){ //fill myString with a random amountof chars } return myString; } ``` The theory tells me that I should use malloc to allocate space, when I'm using p...
It worked due to pure chance. It might not work the next time you try it. Uninitialized pointers can point anywhere in memory. Writing to them can cause an instant access violation, or a problem that will manifest later, or nothing at all.
I'm trying to putprintf("in a string ``` #include<stdio.h> #include<conio.h> main() { char print1="printf(\""; \\i used \ as an escape sequence for " printf("%s",print1); getch(); } ``` but it gives me the following warning: 5 [Warning] initialization makes integer from pointer without a cast and...
This line ``` char print1="printf(\""; \\i used \ as an escape sequence for " ``` should be ``` char *print1="printf(\""; \\i used \ as an escape sequence for " ``` or perhaps ``` char print1[]="printf(\""; \\i used \ as an escape sequence for " ```
I am a beginner to Linux console and start write some code in C. I try to compile code and hope to see messages using command gcc foo.c -o foo -v | less But the result text cannot be paged. Any wrong I do? Thanks.
The|pipe command just redirects stdout. To redirect stderr as well as stdout use|&: ``` gcc foo.c -o foo -v |& less ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question appears to be off-topic becauseit lacks sufficient information to diagnose the problem.Describe your problem in more detail orinclude a minimal examplein the question itself.Closed9 years ago.Improve this q...
You should read something aboutfork,pipeandexecsyscalls. Anyway I have one really simple shell implementation, just for your inspiration :) https://github.com/petrbel/NSWI015-unix-programming/tree/master/myshell
There is any api in c which can set multicast ip address in route table in linux. like through command it can be like this ip route add multicast dev there is any c api which will same as above command is doing. thanks in advance
You might want to look at the documentation forrtnetlink This is the userspace api to interact with the kernel routing rules.
I have a bunch of C files in a directory (each file named such that it starts with the charactersprogram, e.g.program1.c,program2.c,program3.c) and I intend for each of these C files to compile into its respective binary (program1,program2,program3). How would I write aMakefileto achieve this so I can simply issuemak...
``` PROGS := $(patsubst %.c,%,$(SRCS)) all: $(PROGS) clean: /bin/rm $(PROGS) ``` shall do it.
Hypothetically, let's say main() function creates second process calling fork() and let's say this new process starts creating its own children by function makeChildren(), one million in loop, crazy user. Fork() fails, makeChildren() returns error. How to get rid off these new processes that have been already created?...
If the parent process terminates, its children will be reassigned to theinitprocess. It willwaitfor them so they shouldn't become zombies.
I copied this exercise from my book. Use this declaration char *string = "hiii"; what are value for ``` 1) string[0] 2) *string 3) string[99] 4) *string+8 ``` I wrote the following code in an attempt to display the value ofstring[0], but when I run the code, it crashes. Can anyone tell me why my code crashes? ```...
``` printf("%s", string[0]); ``` sconversion specifier requires achar *butstring[0]is achar. Use: ``` printf("%s", string); ``` to print the string. To print the first character of the string, use: ``` printf("%c", string[0]); ```
I want to build a c file based on BlueZ but seems no bluetooth.h file in my system. ``` fatal error: bluetooth/bluetooth.h: No such file or directory ``` I am sure the bluetooth dongle is running correctly and I have built Bluez successfully. Update For my case, I find the bluetooth.h in /user/include/bluetooth fo...
You need to install libbluetooth-dev package for compiling your code ``` sudo apt-get install libbluetooth-dev ``` That should install the bluetooth header files.
I am receiving audio data inRTPstream. The audio can be either inG711 A-laworu-lawdepending on the source. How to decode the audio byte stream usingffmpegapi's? CanALSAon Linux directly play theG711audio format?
Libav for sure supports G.711. The associated codec ID areAV_CODEC_ID_PCM_MULAWandAV_CODEC_ID_PCM_ALAW. I suggest you start from the example program they provide and modifyaudio_decode_example()in order to use G.711. avcodec.h:http://libav.org/doxygen/master/avcodec_8h.htmllibav example:http://libav.org/doxygen/maste...
In order to translate windows vista thread pool API to use in my delphi application. I need to know the definition of_TP_POOL. I looked intowinnt.hand found the followingtypedefdeclaration: ``` typedef struct _TP_POOL TP_POOL, *PTP_POOL; ``` I can't find the_TP_POOLon my local header files. Which is the location of ...
ThePTP_POOLis an opaque pointer. You never get to know, or indeed need to know, what that pointer refers to. The thread pool API serves upPTP_POOLvalues when you callCreateThreadpool. And you then pass those opaque pointer values back to the other thread pool API functions that you call. The thread pool API implementa...
``` typedef struct st { double d ; struct st *n ; } st, *List ; ``` On this part: ``` } st, *List ; ``` What is this second "st"? Is it an object created (why does it have the same name as the type)? I don't understand the "*List". Does it use typedef to say that a "List" is a pointer to an "st"? Thank you....
The part ``` typedef struct st {...} st; ``` creates a new symbolstthat can be used to declare instances ofstruct stwithout the keywordstruct. You can readthis articlefor more information - it has some examples. The second declaration*Listcreates a pointer type tostruct stso you can declare a pointer to the structu...
I am using dirent.h 1.20 (source) for windows in VC2013. I can't findmkdir()in it. How am I supposed to use it? Or can I create a directory somehow only using dirent.h?
simplest way that helped without using any other library is. ``` #if defined _MSC_VER #include <direct.h> #elif defined __GNUC__ #include <sys/types.h> #include <sys/stat.h> #endif void createDir(string dir) { #if defined _MSC_VER _mkdir(dir.data()); #elif defined __GNUC__ mkdir(dir.data(), 0777); #endif } `...
Excuse me, if it is kinda silly, but I can't get value of the structure element by it's pointer. What should i put after "out = " to get "5"? ``` #include <stdio.h> #include <stdlib.h> #include <conio.h> typedef struct { int type; void* info; } Data; typedef struct { int i; char a; float f; do...
You have to cast the void pointer to type: insert pointer. ``` int out = 0 ; if( d->type == 10 ) out = (( insert* )d->info)->i ; ``` If statement is there to check what type Data is holding, otherwise you would be reading uninitialized memory.
I have defined structs as follows: ``` typedef struct decls *Decls; typedef struct expr *Expr; struct decls { Decl first; Decls rest; }; struct exprs { Expr first; Exprs rest; }; ``` and I defined a function to get the length of a Decls ``` static int list_length(Decls decls) { if (d...
Use a generic list and store a pointer to object (Expr, or Delc) in the first part and cast first to a pointer to the appropriate type to use it. ``` struct list { void *first; struct list *rest; }; static int list_length(struct list *l) { if (l) { return 1 + list_length(l->rest); } else { ...
Hypothetically, let's say main() function creates second process calling fork() and let's say this new process starts creating its own children by function makeChildren(), one million in loop, crazy user. Fork() fails, makeChildren() returns error. How to get rid off these new processes that have been already created?...
If the parent process terminates, its children will be reassigned to theinitprocess. It willwaitfor them so they shouldn't become zombies.
I copied this exercise from my book. Use this declaration char *string = "hiii"; what are value for ``` 1) string[0] 2) *string 3) string[99] 4) *string+8 ``` I wrote the following code in an attempt to display the value ofstring[0], but when I run the code, it crashes. Can anyone tell me why my code crashes? ```...
``` printf("%s", string[0]); ``` sconversion specifier requires achar *butstring[0]is achar. Use: ``` printf("%s", string); ``` to print the string. To print the first character of the string, use: ``` printf("%c", string[0]); ```
I want to build a c file based on BlueZ but seems no bluetooth.h file in my system. ``` fatal error: bluetooth/bluetooth.h: No such file or directory ``` I am sure the bluetooth dongle is running correctly and I have built Bluez successfully. Update For my case, I find the bluetooth.h in /user/include/bluetooth fo...
You need to install libbluetooth-dev package for compiling your code ``` sudo apt-get install libbluetooth-dev ``` That should install the bluetooth header files.
Say I have a time like this ``` 12:34:56 ``` How would I go about storing the parsedintegersinto achar array?(this is a requirement) argv[2]is the time passed in as a argument in the terminal. This is what I have so far: ``` char *semi; semi = strchr(argv[2],':') &semi = '\0'; while(argv[2] != null){ ``` By the ...
Why not simply usesscanf? Like ``` char hh[3], mm[3], ss[3]; const char time[] = "12:34:56"; sscanf(time, "%2s:%2s:%2s", hh, mm, ss); ``` You should check the return value fromsscanffor validation of the input.
Here is a very simple code that I'm trying to run: ``` #include <stdio.h> void main() { int x; printf( "TEST%n", &x ); } ``` I expect x to become equal 4 instead I'm getting fatal error. I use Visual Studio 2008 and Windows XP. During execution I get window saying"Microsoft Visual Studio C Runtime Library...
From theMSDN format type page: Security Note The%nformat is inherently insecure and is disabled by default; if%nis encountered in a format string, the invalid parameter handler is invoked as described inParameter Validation. To enable%nsupport, see_set_printf_count_output.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I need to capture packets which are coming from interface (say eth0) and need to print th...
Try having a look at libpcap.http://www.tcpdump.org/I believe it will do what you want.
I installed Eclipse with CDT plugin. I created a simple TCP client software that runs on Windows. I can open the project on Ubuntu also. I'd like to change build configuration in order to create Linux executable. Is it possible to create executable for the operating system that the project is compiled. I mean if I com...
It is possible. When you are creating a Project in Eclipse, you are provided with two build options. One debug and one release. The release build will create the executable for the OS in which it is run. Good Luck!
I have to design a C executable (no GUI) that is supposed to run on Raspberry PI. I'm familiar with design using IDE like Visual Studio or Eclipse (with CDT plugin). If i use Raspberry PI as a design machine, I think I have no chance to use a standard IDE. I should use makefiles and gcc compiler only. Is there any ch...
You can specify to eclipse projects with Makefiles. You can also specify a compilation toolchain. So yes, you can develop and compile for Raspberry Pi or for other plateforms using Eclipse. For getting toolchain and other tools for Rasp Pi you can find thingshere. In Eclipse, you create a new or import a project ch...
I'm having some trouble creating a user-input matrix through a function I create. The function is as follows: ``` int create(int l, int c, int one[MAX][MAX]) { for(int i = 0; i < l; ++i) for(int j = 0; j < c; ++j) scanf("%d", &one[i][j]); } ``` I then proceed to call my function from main : ``` ...
Change ``` create(lines, collumns, mat[MAX][MAX]); ``` to ``` create(lines, collumns, mat); ``` and try again.
i've found this piece of code and tested it. ``` #include <time.h> int main () { time_t start_time; time_t current_time; int TIMEOUT=5; start_time = time(NULL); current_time = time(NULL); while (current_time < start_time + TIMEOUT) { //do everything here current_time = time(NULL); } } ``` It w...
You need to use a timer. There are several APIs to do this. Just usingalarmis the simpliest. There issetitimer/getitimer. There is thetimer_create/timer_destroy/timer_settimefamily. Each has their own strengths offset by their own complexities.
I want to save the output of a system command in a variable, to use it for a GTKLabel. I know that I can use popen to record the output like this: ``` FILE *in; extern FILE *popen(); char buff[512]; char test[512]; if(!(in = popen("adb devices", "r"))){ exit(1); } while(fgets(buff, sizeof(buff), in)!=NULL){ ...
You can use output redirection for this. It works perfectly in command line, and should work good in a program as well. ``` $ program > outputfile ``` This will record the output of theprogramto the fileoutputfile. You can later read this using normalfopencommand. (The dollar is the linux prompt.)
How can we write a rotate_left(char*) function that takes a null-terminated string and rotate it to the left one character. For ex: "abcdef" --> "bcdefa" So far i have: ``` rotate_left(char* str){ int i, lin; char buff[lin+1], temp; lin = strlen(str); strcpy(buff,str); } ``` Can anyone help me comp...
I don't think I will use much of the question code. Here is an alternate solution: ``` rotate_left(char* str){ char ch; ``` 1) Store the character that will to be rotated from the left side, to the right side. ``` ch=*str; ``` 2) Shift all characters in the string left one byte. ``` memmove(str, str+1, strlen...
This question already has answers here:C - Ternary operate to if else(2 answers)Closed9 years ago. I just started learning C, and I have some problems with the? :operator. How can I change ``` x = c ? a : b; ``` into an if else statement? ``` if() { x=a; } else { x=b;} ``` Is it correct like this? I don't know ...
A turnary statement is in the form: ``` result = (booleanValue ? valueA : valueB); ``` This converts to: ``` if (booleanValue) { result = valueA; } else { result = valueB; } ``` In your case "booleanValue" is "c", "valueA" is "a", "valueB" is "b". Hope that helps!
I am pretty new to C so maybe someone can shed some light on why I am getting a segmentation fault with this program: ``` #include <stdlib.h> #include <stdio.h> int main() { char *username = "hello"; char *other; *other = *username; return 0; } ``` Why is this seg faulting?
otherhasn't been initialized. It's pointing into some random spot in memory, and you're sticking a character in there. You'll want to either allocate some space forother: ``` char *other = malloc(6); // or 1, or however much space you'll eventually need *other = *username; // first char at `other` is now 'h'; the...
I create a message queue in C like this: ``` int msgid; int msgflg = IPC_CREAT | 0666; key_t key; key = ftok(".",'a'); if ((msgid = msgget(key,msgflg)) < 0 ){ syserr("msgget error"); } ``` How can I check if the queue already exists? And I don't want to create a new if already exists.
Pass the flagIPC_EXCLtomsgget()and if it fails anderrnoequalsEEXISTthen the queue exists. ``` int msgid = -1; key_t key = -1; if (-1 == (key = ftok(".", 'a'))) { perror("ftok() failed"); } else if (-1 == (msgid = msgget(key, IPC_EXCL | IPC_CREAT | 0666))) { if (EEXIST == errno) { fprintf(stderr, "The que...
Is there anyway to emit the llvm-ir bytecode from inside my pass, into a file? I want the same format that I am getting by using the opt tool, so I can pass this file to the opt later.
To print a module in the textual representation (whichoptcan parse just file) to stdout, useModule::dump(). To save it to a file, useModule::print(and just pass null as the 2nd argument).To dump it to a bitcode file, usellvm::WriteBitcodeToFile.
i've found this piece of code and tested it. ``` #include <time.h> int main () { time_t start_time; time_t current_time; int TIMEOUT=5; start_time = time(NULL); current_time = time(NULL); while (current_time < start_time + TIMEOUT) { //do everything here current_time = time(NULL); } } ``` It w...
You need to use a timer. There are several APIs to do this. Just usingalarmis the simpliest. There issetitimer/getitimer. There is thetimer_create/timer_destroy/timer_settimefamily. Each has their own strengths offset by their own complexities.
I want to save the output of a system command in a variable, to use it for a GTKLabel. I know that I can use popen to record the output like this: ``` FILE *in; extern FILE *popen(); char buff[512]; char test[512]; if(!(in = popen("adb devices", "r"))){ exit(1); } while(fgets(buff, sizeof(buff), in)!=NULL){ ...
You can use output redirection for this. It works perfectly in command line, and should work good in a program as well. ``` $ program > outputfile ``` This will record the output of theprogramto the fileoutputfile. You can later read this using normalfopencommand. (The dollar is the linux prompt.)
How can we write a rotate_left(char*) function that takes a null-terminated string and rotate it to the left one character. For ex: "abcdef" --> "bcdefa" So far i have: ``` rotate_left(char* str){ int i, lin; char buff[lin+1], temp; lin = strlen(str); strcpy(buff,str); } ``` Can anyone help me comp...
I don't think I will use much of the question code. Here is an alternate solution: ``` rotate_left(char* str){ char ch; ``` 1) Store the character that will to be rotated from the left side, to the right side. ``` ch=*str; ``` 2) Shift all characters in the string left one byte. ``` memmove(str, str+1, strlen...
This question already has answers here:C - Ternary operate to if else(2 answers)Closed9 years ago. I just started learning C, and I have some problems with the? :operator. How can I change ``` x = c ? a : b; ``` into an if else statement? ``` if() { x=a; } else { x=b;} ``` Is it correct like this? I don't know ...
A turnary statement is in the form: ``` result = (booleanValue ? valueA : valueB); ``` This converts to: ``` if (booleanValue) { result = valueA; } else { result = valueB; } ``` In your case "booleanValue" is "c", "valueA" is "a", "valueB" is "b". Hope that helps!
I am pretty new to C so maybe someone can shed some light on why I am getting a segmentation fault with this program: ``` #include <stdlib.h> #include <stdio.h> int main() { char *username = "hello"; char *other; *other = *username; return 0; } ``` Why is this seg faulting?
otherhasn't been initialized. It's pointing into some random spot in memory, and you're sticking a character in there. You'll want to either allocate some space forother: ``` char *other = malloc(6); // or 1, or however much space you'll eventually need *other = *username; // first char at `other` is now 'h'; the...
I create a message queue in C like this: ``` int msgid; int msgflg = IPC_CREAT | 0666; key_t key; key = ftok(".",'a'); if ((msgid = msgget(key,msgflg)) < 0 ){ syserr("msgget error"); } ``` How can I check if the queue already exists? And I don't want to create a new if already exists.
Pass the flagIPC_EXCLtomsgget()and if it fails anderrnoequalsEEXISTthen the queue exists. ``` int msgid = -1; key_t key = -1; if (-1 == (key = ftok(".", 'a'))) { perror("ftok() failed"); } else if (-1 == (msgid = msgget(key, IPC_EXCL | IPC_CREAT | 0666))) { if (EEXIST == errno) { fprintf(stderr, "The que...
Is there anyway to emit the llvm-ir bytecode from inside my pass, into a file? I want the same format that I am getting by using the opt tool, so I can pass this file to the opt later.
To print a module in the textual representation (whichoptcan parse just file) to stdout, useModule::dump(). To save it to a file, useModule::print(and just pass null as the 2nd argument).To dump it to a bitcode file, usellvm::WriteBitcodeToFile.
Consider the following code ``` FILE * pOutFile; unsigned char uid; pOutFile = fopen("OutFile.bin","w") ; // open a file to write uid = 0x0A; fprintf (pOutFile,"%c",uid); // Trying to print 0x0A in to the file ``` But the print I get in the file is ``` 0x0D 0x0A ``` Where is this 0x0D coming from? Am...
Windows text files want new lines to be represented by two consecutive chars: 0x0D and 0x0A. In C, a new line is represented by a single char: 0x0A. Thus, on Windows, in C, you have two ways to open a file: text mode or binary mode. In binary mode, when you write a LineFeed (0x0A) char, a single byte (0x0A) is appe...
I was trying to understand sqlite source code. I was lookin to find that, when on CLI we do$sqlite abcd.db, where does the control transfers to , which function are called? I've to make some changes whenever I create a new database or open it i.e. $sqlite abcd.db
The amalgamation build of SQLite includes two C files.sqlite3.cis the SQLitelibrarysource code, and does not contain an entry point, since it is not a program. The SQLite shell is implemented in the fileshell.c, which is a standard C program source file with amainfunction (which is on line 3570 in my version).
I'm trying to make a simple c-shell like program on C (for Linux) that will execute scripts. I need to read a script file in order to execute it, but how can I read it if it has only execute permission, and no read permission?
In short, A binary file you can execute with only execute permissions.A script is a text file, so you need read permissions. So, you would need to play some games with group ownership, sudo, or similar.
I'm usingfgetc()to read a char from a file which consists of digits only. Then I convert the characters to int and print it out. That's fine. But after printing out all the digits, at the end I get-38-49values. I googled it, but nothing about it there. In the input file, I have the following:0105243100000002200000010...
You are reading the newline (10) and the EOF return value of fgetc (-1). Substracting '0' (48) from those yields those negative numbers. Check if the char if valid, it must be in range ['0','9'] ``` c1 = fgetc(fread); if(c1 >= '0' && c1 <= '9') { c1 -= '0'; // ... } ```
I am currently working on a project (in C), in which I'm using different win HANDLE (mutex, semaphore, thread, ...). My question is : Is there a way to retrieve the types of kernel object an HANDLE is linked to? Something like : Get_HANDLE_source() or Is_thread_HANDLE() ? Thank you, Cheers!
As said NtQueryObject. But It is probably better to use some OO concepts: ``` struct HandleVtable { /* function pointer to appropriate implementation */ }; struct HandleWrapper { struct HandleVtable *vptr; HANDLE handle; }; ``` For each type of handle, create a static const HandleVtable...
Is there a Z3 C API call that parses a general (non-Boolean) term? E.g. something like this:(+ a b)? As far as I see it, theZ3_parse_smtlib2_stringfunction parses only formulas in assertions, which are exclusively of Boolean type.
The parser (Z3_parse_smtlib2_string) parses SMT-LIB2 benchmarks. Benchmarks in this format define a logical formula. This formula is "true" if the input does not contain any assertions. This is why the parser returns "true" in your case. Z3 doesn't expose parsing facilities for terms. You can work around this by creat...
``` #define CPU Mntel_i7 void main(){ #if CPU == Intel_i7 printf("Performance should be good.\n" ); #endif getchar(); } ``` I defined CPU to be Mntel_i7 and when i test if it is Intel_i7 it includes the code in the #if #endif block and prints it to screen how is that possible ?
In your case, the following statement ``` #if CPU == Intel_i7 ``` will be expanded to ``` #if Mntel_i7 == Intel_i7 ``` Because bothMntel_i7andIntel_i7are not macros,cppwill consider them as zero, which means the above condition equals ``` #if 0 == 0 ``` and will be true. Normally, you can achieve your goal by s...
This question already has answers here:Are empty macro definitions allowed in C? How do they behave?(3 answers)Closed9 years ago. I encountered some codes as the following: ``` #define MY_IDENTIFIER void someCode() { ... MY_IDENTIFIER ... } ``` What's the upper code doing ?
Absolutely nothing. The pre-processor is simply replacingMY_IDENTIFIERwith nothing wherever it encounters it.
Consider the code: ``` if(x = a/b, a%b) printf("do this"); else printf("do that"); ``` Now if I replaceifstatement byif(x = a/b && a % b). Then it works also. So I want to know that replacing comma by&&operator and vice-versa works always or not inif-else and loops
They are quite different! In the first example,,is thecomma operator, which is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). So, ``` if(x = a/b, a%b) ``` is equivalent to (thanks to @jaket) ``` x = a/b; if(a%b...
By default what is the baud rate during serial communication. That is if a write a program where I do not mention any baud rate, then what baud rate will be taken into account?
If on a POSIX system: Open a port usingopen().Pass the the file-descriptor from 1. totcgetattr()to initialise astruct termios.Pass a reference to thestruct termiosfrom 2. tocfgetispeed()/cfgetospeed()to get the port's current inbound/outbound baud rate. Example: ``` #include <termios.h> #include <unistd.h> [...] ...
I am new to programmingCbut not new to programming. I have downloaded Code::Blocks to buildCprojects with but when I start a new project it says it can't find a compiler. I downloaded GNU GCC Compiler and when I create a new Project it still says it can't find the compiler. The compiler is downloaded on myC:drive so I...
Have you downloaded IDE with compiler. If not do so. It's large size version comes with compiler. It comes with MinGW GCC compiler. OR go to settings in the upper part -> click compiler -> choose reset to defaults. This link might help.http://wiki.codeblocks.org/index.php?title=Installing_a_supported_compiler
I write a function to decide whether it is a file or not, see the code below: ``` bool isfile(const std::string & f) { struct stat st; stat(f.c_str(), & st); if(S_ISREG(st.st_mode)) { return true; } return false; } ``` But when I invoke the function with: ``` std::cout << isfile("/home/xxx/a*") << st...
You don't check the return value ofstatand instead look atst.st_modewhether or not it contains valid data. So whenstatfails, say because the file doesn't exist, you process nonsense data.
I have below switch case in my code. ``` switch(condition) case 'A' : //Code part A break; case 'B' : //Code part A //Code part B break; case 'C' : //Some code break; ``` code Part A is repeated in both case 'A' and case 'B'. I want to avoi...
If the order is not important, you can simply do: ``` switch (condition) { case 'B': // Code part B // no break case 'A': // Code part A break; ... } ``` Acase 'B'will continue to execute through thecase 'A'code because you didn't call abreak.
Here are the two different versions: ``` Node *pointer = (Node*)malloc(sizeof(Node)); pointer = NULL; ``` . ``` Node *pointer = NULL; ``` The reason I ask is because I see the first version everywhere in this code I'm working on but I thought it'd be the same as the second. Sometimes instead of being assigned to N...
They are very different. In the first case you create aNodeon the heap and then straight away "forget" it, causing a memory leak. The second case doesn't create aNodeand so no leak. If you really see the first version everywhere in your code, I'd be pretty worried!
I am trying to print a 1d array in multiple lines. I want to print the array 8 by 9 format. ``` int main(){ int rowColm[63]; int i = 0; for(i = 0; i<sizeof(rowColm); i++){ } return 0; } ```
Here is an alternate approach: ``` int main() { // int rowColm[63]; --Most likely you meant 72, not 63 (8 * 9 = 72) int rowColm[8*9]; int row; int col; for(row=0; row < 8; ++row) { for(col=0; col < 9; ++col) printf("%d\t", rowColm[(row*9) + col]); ``` No need here for 'sizeof()'...
In my project I have to fill my buffer with data from specified input (/dev/urandom by default). I googled it how to open and read data in kernel space from character device, but the forums are about how to implement the read function of my own character device, or how to read (regular?) files (which is not recommende...
As far as I understood, there's no easy and correct way to read files from kernel space. Since in my project this file read is provisional only for test purposes, it's okay to read file the "ugly" way, described in the article in the question. If the release version of the kernel module uses such file interactions, t...
Hi i m trying to learn data structures in C.I write a program but it crash when i run it ``` #include <stdio.h> #include <stdlib.h> typedef struct{ int x; int y; }structure; typedef struct{ structure test1; }test; void function(test *trying){ trying->test1.x = 5; ...
``` test *mystruct; function(mystruct); ``` mystructpointer is not initialized and has an indeterminate value. This statement invokes undefined behavior because of the absence of initialization: ``` trying->test1.x = 5; ``` Do that instead: ``` test mystruct; function(&mystruct); ```
I have the following c code: ``` int argv = 2; char **argv = {"test arg 1", "test arg 2"}; ``` When I compile it, I get teh following warning: warning: initialization from incompatible pointer type [enabled by default] Can you please tell me what's wrong for my initialization? Thank you.
char **is a pointer type not an array type. Use an array type: ``` char *argv[] = {"test arg 1", "test arg 2"}; ```
My university professor has asked me to develop a project in C for Unix machines. I should do a soccer championship emulator, in which there is a parent, and there are some child(every match between two teams). The parent must create the matches, and the matches must tell the end result to the parent. I think the bes...
Your suggestion above is valid. That approach would work. It might be easier to use a chunk of shared memory and mutex instead, but it's ultimately your call. I've included a working example that usespthread_mutexcalls andmmapin the references below that should get you up and running. Good luck! References C procs...
I need to read a file opened like this: ``` int outfile = open(*fileName, "w"); ``` using the file descriptor, I'm doing that like this: ``` char txt[50]; int bytes; bytes = read(outfile,txt, 50); ``` But I'm getting segmentation fault and the application abort, any ideas?
Note the second argument to open. It's "w" this seems like it should indicate that you're opening the file for writing. However, my man pages foropenindicates that the second argument should be one of:O_RDONLY,O_WRONLY, orO_RDWR. (fopen uses strings like "w", "w+", "r", ... but that's fopen not open). You may be gett...
I try to declare a global variableconfig: ``` //general.h struct config_t { int num; }; extern struct config_t config; //The global variable ``` Then I define config variable ingeneral.c: ``` //general.c #include "general.h" struct config_t config = { num = 5; }; ``` But, when I try to use the global v...
This looks like a linker error. You need to make sure you link your executable properly: ``` cc -c general.c cc -c main.c cc general.o main.o ./a.out ``` The-cflag instructs your compiler not to link yet. In order to link the object file containingconfigneeds to be available at that moment.
My university professor has asked me to develop a project in C for Unix machines. I should do a soccer championship emulator, in which there is a parent, and there are some child(every match between two teams). The parent must create the matches, and the matches must tell the end result to the parent. I think the bes...
Your suggestion above is valid. That approach would work. It might be easier to use a chunk of shared memory and mutex instead, but it's ultimately your call. I've included a working example that usespthread_mutexcalls andmmapin the references below that should get you up and running. Good luck! References C procs...
I need to read a file opened like this: ``` int outfile = open(*fileName, "w"); ``` using the file descriptor, I'm doing that like this: ``` char txt[50]; int bytes; bytes = read(outfile,txt, 50); ``` But I'm getting segmentation fault and the application abort, any ideas?
Note the second argument to open. It's "w" this seems like it should indicate that you're opening the file for writing. However, my man pages foropenindicates that the second argument should be one of:O_RDONLY,O_WRONLY, orO_RDWR. (fopen uses strings like "w", "w+", "r", ... but that's fopen not open). You may be gett...
I try to declare a global variableconfig: ``` //general.h struct config_t { int num; }; extern struct config_t config; //The global variable ``` Then I define config variable ingeneral.c: ``` //general.c #include "general.h" struct config_t config = { num = 5; }; ``` But, when I try to use the global v...
This looks like a linker error. You need to make sure you link your executable properly: ``` cc -c general.c cc -c main.c cc general.o main.o ./a.out ``` The-cflag instructs your compiler not to link yet. In order to link the object file containingconfigneeds to be available at that moment.
``` struct bitCard { unsigned int face : 4; unsigned int suit : 2; unsigned int color : 1; }; ``` "The preceding structure definition indicates that member face is stored in 4 bits, member suit is stored in 2 bits and member color is stored in 1 bit. The number of bits is based on the desired range of values...
think 2 in the power of 4 = 16 possible values... binary value represent decimal number in range 0..2^x - where X=num of bits
I was wondering as why do we include an empty while(1) loop in the end of most c programs for example motor driver, gyro sensor routines? I searched but didn't find any satisfactory reason for this. Thanks. For example following code on an ATmega8: ``` #include <avr/io.h> #include <util/delay.h> void main (void) { ...
Many embedded systems use timers, interrupts or other events to drive their actions. They may also run OS's that provide threads or tasks that might be set up to performer he real work. So once that initialization is done, there's nothing left for themain()program to do, but in such simple systems there is often not...
I have been attempting C recently and have been reading C source code, however I came across this perculiar method signature with a * beside its name, can someone explain this to me please ``` int *bubble_sort(int *numbers, int count, compare_cb cmp) ``` edit: I am referring to the * infront of bubble_sort
The asterisk has nothing to do with the function signature, it's just C's way of declaring pointers. The asterisk belongs to the type on the left, i.e. the return type for the function isint *, which is read out as "pointer to integer". The first argument has the exact same type, pointer to integer. You use this synta...
Let's say I want to set a value (e.g. a function) inside a nested table from the Lua C API. ``` -- lua.lua glob = { nest = { -- set value in here } } ``` How would I have to set the stack to access the inner table? Is it just callinggettablemultiple times and then asettop, like in the following code? ```...
This code setsglob.nest.nameto a C function: ``` lua_getglobal(state, "glob"); lua_getfield(state, -1, "nest"); lua_pushcclosure(state, &func, 0); lua_setfield(state, -1, "name"); ``` To add others field toglob.nest, just keep going: ``` ... lua_pushcclosure(state, &anotherfunc, 0); lua_setfield(state, -1, "another...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site,...
You don't have the help files (aka man pages) for gcc or g++ installed in cygwin. You need to re-run the cygwin setup*.exe and select it to be installed. I'm not sure which package it is though.
``` struct bitCard { unsigned int face : 4; unsigned int suit : 2; unsigned int color : 1; }; ``` "The preceding structure definition indicates that member face is stored in 4 bits, member suit is stored in 2 bits and member color is stored in 1 bit. The number of bits is based on the desired range of values...
think 2 in the power of 4 = 16 possible values... binary value represent decimal number in range 0..2^x - where X=num of bits
I was wondering as why do we include an empty while(1) loop in the end of most c programs for example motor driver, gyro sensor routines? I searched but didn't find any satisfactory reason for this. Thanks. For example following code on an ATmega8: ``` #include <avr/io.h> #include <util/delay.h> void main (void) { ...
Many embedded systems use timers, interrupts or other events to drive their actions. They may also run OS's that provide threads or tasks that might be set up to performer he real work. So once that initialization is done, there's nothing left for themain()program to do, but in such simple systems there is often not...
I have been attempting C recently and have been reading C source code, however I came across this perculiar method signature with a * beside its name, can someone explain this to me please ``` int *bubble_sort(int *numbers, int count, compare_cb cmp) ``` edit: I am referring to the * infront of bubble_sort
The asterisk has nothing to do with the function signature, it's just C's way of declaring pointers. The asterisk belongs to the type on the left, i.e. the return type for the function isint *, which is read out as "pointer to integer". The first argument has the exact same type, pointer to integer. You use this synta...
Let's say I want to set a value (e.g. a function) inside a nested table from the Lua C API. ``` -- lua.lua glob = { nest = { -- set value in here } } ``` How would I have to set the stack to access the inner table? Is it just callinggettablemultiple times and then asettop, like in the following code? ```...
This code setsglob.nest.nameto a C function: ``` lua_getglobal(state, "glob"); lua_getfield(state, -1, "nest"); lua_pushcclosure(state, &func, 0); lua_setfield(state, -1, "name"); ``` To add others field toglob.nest, just keep going: ``` ... lua_pushcclosure(state, &anotherfunc, 0); lua_setfield(state, -1, "another...
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site,...
You don't have the help files (aka man pages) for gcc or g++ installed in cygwin. You need to re-run the cygwin setup*.exe and select it to be installed. I'm not sure which package it is though.
Why the output of following Program is ``` 0 and Garbage Value and Garbage Value ``` Program is: ``` #include<stdio.h> int main() { int a=9,b=0,x,y; x=a&b; y=a||b; printf("%d %d %d"); return 0; } ``` Why the first time %d prints 0 ?
Your codeprintf("%d %d %d");invokes Undefined Behavior From section7.19.6.1 The fprintf functionof the C99 standard: The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output.If there are in...
I've made a program which generate a Huffman's Codes from input file. Now I don't know how to end output file(which should be compressed based on the input file and generated codes). Lets say that we have 43 bits to save so how end the file? I can simply add 5 zeros in the end, but then codes could be wrong. Any ideas...
There are two ways to solve this that I can think of: Put the length of the uncompressed data in front of the compressed data. Then, when you're decompressing, count how many characters you have decompressed and stop after the right number.Put a special end symbol into your huffman tree that you only use at the end o...
I wouldn't expect the value that gets printed to be the initial negative value. Is there something I'm missing for type casting? ``` #include<stdint.h> int main() { int32_t color = -2451337; uint32_t color2 = (uint32_t)color; printf("%d", (uint32_t)color2); return 0; } ```
You took a bunch of bits (stored in signed value). You then told the CPU to interpret that bunch of bits as unsigned. You then told the cpu to render the same bunch of bits as signed again (%d). You would therefore see the same as you first entered. C just deals in bunches of bits. If the value you had chosen was nea...
Ok, I can store blocks on NSArrays using something like this: ``` NSArray *myArray = @[[myBlock1 copy], [myBlock2 copy]]; ``` and run that code later by doing, for example: ``` myBlockType runBlock = myArray[0]; runBlock(); // run baby, run ``` What about the C equivalent to this? Is that possible?
This works: ``` typedef void (^MyBlockType)(void); MyBlockType blocks[100]; for(int i = 0; i < 100; i++) { MyBlockType block= ^{printf("Run!");}; blocks[i] = block; } MyBlockType thisBlock = blocks[0]; thisBlock(); ```
I have to check Linux system information. I can execute system commands in C, but doing so I create a new process for every one, which is pretty expensive. I was wondering if there is a way to obtain system information without being forced to execute a shell command. I've been looking around for a while and I found no...
Linux exposes alotof information under/proc. You can read the data from there. For example,fopenthe file at/proc/cpuinfoand read its contents.
I wouldn't expect the value that gets printed to be the initial negative value. Is there something I'm missing for type casting? ``` #include<stdint.h> int main() { int32_t color = -2451337; uint32_t color2 = (uint32_t)color; printf("%d", (uint32_t)color2); return 0; } ```
You took a bunch of bits (stored in signed value). You then told the CPU to interpret that bunch of bits as unsigned. You then told the cpu to render the same bunch of bits as signed again (%d). You would therefore see the same as you first entered. C just deals in bunches of bits. If the value you had chosen was nea...
Ok, I can store blocks on NSArrays using something like this: ``` NSArray *myArray = @[[myBlock1 copy], [myBlock2 copy]]; ``` and run that code later by doing, for example: ``` myBlockType runBlock = myArray[0]; runBlock(); // run baby, run ``` What about the C equivalent to this? Is that possible?
This works: ``` typedef void (^MyBlockType)(void); MyBlockType blocks[100]; for(int i = 0; i < 100; i++) { MyBlockType block= ^{printf("Run!");}; blocks[i] = block; } MyBlockType thisBlock = blocks[0]; thisBlock(); ```
I have to check Linux system information. I can execute system commands in C, but doing so I create a new process for every one, which is pretty expensive. I was wondering if there is a way to obtain system information without being forced to execute a shell command. I've been looking around for a while and I found no...
Linux exposes alotof information under/proc. You can read the data from there. For example,fopenthe file at/proc/cpuinfoand read its contents.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question I am preparing for interview, so in internet somewhere I got this: What should be the "c...
Try this: ``` if(printf("Hello")<=0) printf ("Hello"); else printf("World"); ``` OR ``` if(!!!printf("Hello")) printf ("Hello"); else printf("World"); ``` How it works: On success,printfreturns the number of characters printed. On failure it returns a negative number. So the else part will be executed aft...
I am new to C. I have a struct employee like follows:- ``` struct employee { char eid[100]; char name[100]; }; ``` I want to assign this eid value as "EMP_1", "EMP_2" and so on. Whenever any employee enters its name its id should be generated dynamically like "EMP_1" for the first employee and "EMP_2" for th...
Usesnprintf(). ``` snprintf(emp.eid, sizeof emp.eid, "%s%d", "EMP_", id); ```
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this question What does compiler do behind the scene (at assembly level) when performing lvalue-to-rval...
What the compiler does in each specific case will depend on the compiler implementation, the current optimization level, the exact workings of optimizations in effect at that point, and more. But basically, lvalue to rvalue conversion corresponds to reading the memory content (roughly representing the rvalue) from th...
Can anybody tell me how to useitoafunction in C? The prototype is: ``` char*itoa(int_Val,char*_DstBuf,int_Radix) ``` I think thatint_Valis the value that I want to convertchar*_DstBuf, is the string where I want to store the result But what isint_Radix?
It is the base to convert to 10 - Decimal 16 - Hexidecimal 8 - Octal A per the manual pagehttp://www.cplusplus.com/reference/cstdlib/itoa/
I would like to know how is the run-time stack handled when running the code below ``` int i; for (i = 0; i < 100; i++) { int v[i+1]; ... } ``` Stack is reduced and grown after every loop ? Stack is initially allocated by an amount which will fit v[101] ? Is it optimized by compiler so it tre...
Depends on the compiler and optimization settings. A clever compiler could figure out that the biggest size needed is 100, and allocate that once from the stack at the beginning and reuse it. Stack allocation is practically free as it's just a pointer adjustment so it wouldn't make any sense to use the heap instead.
The program goes like this ``` if(z = x < y){ x +=3; y -= 1; } else x = y++; ``` The input values arex = 7,y = 7andz = 2. The output values arex = 7,y = 8andz = 0. I am not sure how this statement works... Can anyone help me out?
First the comparison is evaluated, since<has higher priority than=. The result of the comparison isfalse(i.e. casted to 0), thenzis made 0. The condition is then evaluated tofalse, so theelsebranch is executed, in which first the assignment is made, thenyis incremented (see how postfix++operator works). BTW, you shoul...
I would like to know how is the run-time stack handled when running the code below ``` int i; for (i = 0; i < 100; i++) { int v[i+1]; ... } ``` Stack is reduced and grown after every loop ? Stack is initially allocated by an amount which will fit v[101] ? Is it optimized by compiler so it tre...
Depends on the compiler and optimization settings. A clever compiler could figure out that the biggest size needed is 100, and allocate that once from the stack at the beginning and reuse it. Stack allocation is practically free as it's just a pointer adjustment so it wouldn't make any sense to use the heap instead.
The program goes like this ``` if(z = x < y){ x +=3; y -= 1; } else x = y++; ``` The input values arex = 7,y = 7andz = 2. The output values arex = 7,y = 8andz = 0. I am not sure how this statement works... Can anyone help me out?
First the comparison is evaluated, since<has higher priority than=. The result of the comparison isfalse(i.e. casted to 0), thenzis made 0. The condition is then evaluated tofalse, so theelsebranch is executed, in which first the assignment is made, thenyis incremented (see how postfix++operator works). BTW, you shoul...
This question already has answers here:In which step of compilation are comments removed?(2 answers)Closed5 years ago. Are comments in a c source file removed by the compiler (for example visual c++ and GCC)? ``` /* ... */ // ... ```
The compiler uses different steps to translate the sourcecode to machine readable code. The first step, the lexical analysis phase translates the characters to tokens. A token can be an identifier, a literal value, a reserved word, or an operator. Comments and whitespace are mostly ignored during this phase. They ar...
I was taking a peek at blogs, detailing the vulnerable code of the Heartbeat implementation of OpenSSL. I found this line: ``` unsigned char *P = &s->s3->rrec.data[0], *p1; ``` What i do not understand is how is this pointer *p, assigned two different values? The one is: ``` &s->s3->rrec.data[0] (also, why is he ...
The following statement ``` unsigned char *P = &s->s3->rrec.data[0], *p1; ``` equals ``` unsigned char *P = &s->s3->rrec.data[0]; unsigned char *p1; ``` this further equals ``` unsigned char *P; unsigned char *p1; P = &s->s3->rrec.data[0]; ``` And in C,&s->s3->rrec.data[0]means taking the address ofs->s3->rrec.d...
I know that integer pointer will dereference 4 bytes, then what signed and unsigned do with pointers ? what is the meaning of "unsigned int *ptr" and "signed int *ptr"
Type of pointer suggests what kind of variables address it can keep. So,unsigned int *ptrshould keep address ofunsigned intandsigned int *ptrshould keep address ofsigned int Please look at following piece of code, ``` int main() { unsigned int * ptr1; signed int * ptr2; unsigned int i; signed int ...
I am trying to write a compression program, and the logic works fine when I print bits onto screen, however I am also trying to put these bits into a file. I do this by storing them into a char and outputting that char. This method works file for all characters other than things like space (0010 0000) or tabs (0000 1...
I worked this one out. I needed to add a null character to indicate end of string.
So I was looking throughthis C tutorialand I found these lines of code: ``` struct Monster { Object proto; int hit_points; }; typedef struct Monster Monster; ``` And I thought that it would make much more sense if it were like this: ``` typedef struct { Object proto; int hit_points; } Monster; ``` ...
The first piece of code defines a typestruct Monster, and then gives it another nameMonster. The second piece of code defines structure with no tag, and typedef it asMonster. With either code, you can useMonsteras the type. But only in the first code, you can also usestruct Monster.
I am trying to figure out how to use qsort with an array of strings. My code looks like this. ``` char words[500][256]; int numOfWords; // this is calculated above int sortWordList() { int length = sizeof(words) / sizeof(char *); qsort(words, length, sizeof(char*), compare); } int compare (const void * a...
You are not casting yourconst void *toconst char *properly, to do so, use instead: ``` const char *pa = (const char *)a; const char *pb = (const char *)b; ``` Pluscompare()should be abovesortWordList()as you're using it insortWordList().
A simple C program: ``` #define MAXROW 2 #define MAXCOL 2 int main() { int (*p)[MAXROW][MAXCOL]; printf("%d\n",sizeof(*p)); return 0; } ``` The answer is 16. I don't understand how. It follows this rule: size = number of elements * sizeof (pointer variable, i.e 4) Can anybody tell me how to a...
sizeof(int) = 4on your machine.pis anarray pointerpointing at a 2D array of 2*2 int.sizeof(*p)gives the size of the type thatpcan point to, i.e. the size of the array.The size of the array = 2*2*4 = 16.
I am writing a program to play audio using 'libpulse' on linux. I have successfully played theaudio, but need to know how to change the volume. I am able to start the stream using ``` v = PA_VOLUME_NORM; pa_cvolume_set(&m_lcvolume, 1, v); pa_stream_connect_playback(s, NULL, &attr, PA_STREAM_NOFLAGS, &m_lcvolume, NULL...
Finally I am able to change the volume of each channel by callingpa_context_set_sink_input_volume. Thepa_cvolumeparameter can be used to specify the volume and channel inpa_context_set_sink_input_volume.
This question already has answers here:Using %f to print an integer variable(6 answers)Closed9 years ago. ``` int a=3.14*150; printf("%d",a); return 0; ``` This works fine, output is 471 ``` int a=3.14*150; printf("%f",a); return 0; ``` but now the output is -0.104279 I thought int will be promoted to float but ou...
It is undefined behaviour to use wrong conversion specifier forprintf. (It's true ofscanfas well). Now, the%fconversion specifier means that the bits of theintvariableawill be interpreted as a floating point value. Floating-point values are generally implemented as perIEEE Standard for Floating-Point Arithmetic (IEEE...
So I am trying to copy a string to the fuse buffer. When I try to call sizeof(buf) I get an error and my program crashes. My problem is that I believe I am reaching the maximum size of the fuse buffer because it is chopping off the last few characters. Is there anyway to change buf size from within my c file or does a...
Random guess: you're usingsizeof bufwherebufis just a pointer (probably passed to a function), and thus getting the size of the pointer instead of the size of the memory block the pointer is pointing at. You cannot get the latter usingsizeof, you must pass it in a separate variable.