question
stringlengths
25
894
answer
stringlengths
4
863
I got a problem when I want to use make, containing a variable linking to my folder. Like this : ``` DIR_ST = I\ \:\ The\ Scared\ Stones SRC_ST = $(DIR_ST)/main.c OBJ_ST = $(SRC_ST:.c=.o) ``` But when I want to compile like this: ``` all : $(ST) $(ST) : $(OBJ_ST) $(CC) $(OBJ_ST) -o strategic ``` i got this error: ``` make: *** No rule to make target `I \: The Sacred Stones/main.o', needed by `binaries/strategic'. Stop. ``` How can I use this folder's name in a Makefile?
you could place a symbolic link in the current directory to the 'I:\ The Scared Stones directory suggest using a link name that does not have any spaces
Quick question: Since int is 2 bytes and char is 1 byte, I want to store an int variable in 2 char variables. (like bit 1 - 8 into the first char, bit 9-16 into second char). Using C as programming language. How can I achieve that? Will something like: ``` int i = 30543; char c1 = (char) i; char c2 = (char) (i>>8); ``` do the job? I couldn't find whether casting an int into a char will just drop the bits 9-16.
This was extracted from the c11 draft n1570 6.5.4 Cast operatorsIf the value of the expression is represented with greater range or precision than required by the type named by the cast (6.3.1.8), then the cast specifies a conversion even if the type of the expression is the same as the named type and removes any extra range and precision. So the cast will indeed remove the extra bits, but it's not needed anyway because the value will be implicitly converted tochar, and the above would apply anyway.
I have a matrix in the form below where the position is only given via one iterable (x). ``` A B 1 0 3 2 0 2 4 5 ``` where for matrixA[x] and matrixB[x] ``` matrixA[0] = 1, matrixA[1] = 0, matrixA[2] = 0, matrixA[3] = 2 matrixB[0] = 3, matrixB[1] = 2 etc. ``` What would be the best way to implement a multiplication of matrices A and B (preferably in C) when the only way to receive the position within a matrix is through variable x (also have the length of width and height)? (the examples I have gotten from google all use two variables - height and width to solve this however I'm only working with one)
I think matrix'swidthhad been given as input. If so, You can convertmatrix[x][y]tomatrix[x*width+y]and apply any ordinary multiplication algorithm.
I'm writing a code that got a path to C file, and I want to compile the file by the program code. Meaning that the compile will not be in the command line like: ``` gcc -o a.out file.c ``` There is a way to do it?
If you are trying to compile a C source file in a programmatic manner, you can try this: ``` execlp("gcc", "gcc", "file.c", "-o", "a.out", NULL); ``` execlphas the advantage of searching the dirs stored in your environment$PATHto find the required executable. It returns-1if the call fails. Don't forget to#include <unistd.h>for this to work. You can also get away with another simple call: ``` system("gcc file.c -o a.out"); ``` This requires#include <stdlib.h>and will executegccby invoking/bin/sh.
Consider the following function: ``` void free_or_not ( int count ) { int i ; int *ip = malloc ( count * sizeof ( int ) ) ; for ( i = 0 ; i < count ; i ++ ) ip[i] = i ; for ( i = 0 ; i < count ; i ++ ) printf ( "%d\n" , ip[i] ) ; free ( ip ) ; } ``` Will this cause memory leak if I don't callfree()insidefree_or_not()?
Will this cause memory leak if I don't callfree()insidefree_or_not()? Yes, it will cause memory leak. Once your function finishes execution, you don't have anypointersto the allocated memory tofree()it. Solution:If you change the return type of your function tovoid *(or similar) and return the allocated pointer (ip)from the function, then, you can collect that pointer tn the caller andfree()the pointer from the caller of this function.
I would like to write a C-program that allocates 20,000 memory lines with each line containing 8 bytes and are labeled in the range 2500 to 24999.. The program actually simulates a simple assembly language IDE. All the 20,000 memory lines may or may not be used at once. Suggest me how to allocate memory for those locations in the C program. Should it be a static allocation? Visithttp://screencast.com/t/69T7u0avH
Try ``` unsigned char (*ptrtomem)[8]; unsigned char (*ptr)[8]; /* ... */ ptrtomem = malloc(20000*8); ptr = ptrtomem-2500; /* use ptr[2500][] to ptr[24999][] */ /* when done */ free(ptrtomem); ``` or use _alloca() (or alloca() depending on compiler) if you want to allocate off the stack.
I would like to do something like this: ``` char in[] = {'a','b','c','d','f','r','t','b','h','j','l','i'}; char out[3]; out = &in; ``` and get only the first 3 characters but I get an error of incompatible types
outis anarray name, which can't be modified. There's no straight forward way to get asliceof the array in C. You can usememcpy: ``` memcpy(out, in, sizeof out); ``` And you need to take thatinhas sufficient elments to copy from.
Does thesize_tvalue of the virtual memory pointer returned bymalloc()have an upper boundary? I am wondering whether I can safely set the most significant bit of a 64 bits pointer to indicate that this is not a pointer but a literal integer instead.
malloc returns avoid*not an integer. Casting a pointer to an integer is not giving you the (virtual memory) address, but some value that has to adhere to the semantics as defined in the C language standard (0 for a null pointer and adding and subtracting is related to pointer arithmetic), but that's about it. You must make no assumptions whatsoever about the values of pointers-cast-to-integers other than that. As a matter of fact a C implementation may very well be in its right to tag non-null pointer cast to integer with some internal information in the upper bits.
I have readloads of Microsoft documentation regarding RPC programmingand still do not figure out how do we get from RPC server the IP address of the connecting client. I am sure there is a simple way to get client IP address from server when connecting, but do not know how to do this :/ Thanks for helping, a simple pointer to a documentation would be great.
No - there is no documented way to accomplish this. Windows RPC by design abstracts the network transport (and associated metadata like network addresses) from it's clients. If you really need something like this, you could bake it into your interface (e.g. implement a Connect() method where your client provides it's IP address that you could stash in aContext Handle). This assumes of course, that you can trust your clients to provide valid IP addresses...
Code snippet: ``` void function(void) { while(1) { int i = 0; i += 1; if(i == 500) break; } } ``` The variableiis stored in stack every time when restart the loop ? What is the memory structure when running this code ? What is the behavior of this variable ? It is a bad or good practice do this ? Thanks.
You will never reachi == 500.It's being reset every time through the loop since it's within the scope ofwhile(1){}. The following will work. ``` void function(void) { int i = 0; while(1) { i += 1; if(i == 500) break; } } ```
Is there any way to print Greek characters in C? I'm trying to print out the word "ΑΝΑΓΡΑΜΜΑΤΙΣΜΟΣ" with: ``` printf("ΑΝΑΓΡΑΜΜΑΤΙΣΜΟΣ"); ``` but I get some random symbols as output in the console.
Set your console font to a Unicode TrueType font and emit the data using an "ANSI" mechanism (that's assuming Windows... ). For example this code prints γειά σου: ``` #include "windows.h" int main() { SetConsoleOutputCP(1253); //"ANSI" Greek printf("\xE3\xE5\xE9\xDC \xF3\xEF\xF5"); // encoded as windows-1253 return 0; } ```
I understand floating point has rounding errors, but I'm wondering if there are certain situations where the error does not apply, such as multiplication by zero . Does zero times any number = zero for all floating points ?
False: ``` 0f * NAN == NAN 0f * INFINITY == NAN ``` and ... ``` 0f * -1f == -0f (negative 0f), with 0f == -0f :-) ``` (on Intel, VC++, and probably on any platform that uses IEEE 754-1985 floating points) Example onideone(that uses GCC on some Intel compatible platform probably)
My program asks the user to provide astring, which will be copied into an array of characters. Then, with aforloop, the program simply copies the elements of the first array into the second array. ``` int main() { int i; char string1[4], string2[4]; // Get the first string printf("Insert your string: "); scanf("%s", string1); // Copy the values into the second array for (i = 0; i < 4; i++) { string2[i] = string1[i]; } // Print the second string printf("%s", string2); return 0; } ``` However, when I print thestringusing theprintf()function thestringgets printed twice. Let's say I input the word bars The output will be barsbars Why is this happening?
``` char string1[4], string2[4]; ``` 4-element char array is not enough for 4-character strings. You need one more for the terminating'\0'character.
I'm new with C, i'm trying to make simple program with sqlite3 db. I have query like this: ``` sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS) " \ "VALUES (1, 'Paul', 32, 'California' ); " \ ``` I have values in char* variables, is it possible to use %s like on printf for example: ``` sql = somefunction("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS) " \ "VALUES (%d, '%s', %d, '%s');", 1, 'Paul', 32, 'California'); ``` If that is not possible what is the best way to do this? Thanks!
sprintf()looks appropriate for your problem (introduced in C89). Now simply do something like this: ``` sprintf(sql, "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS) " "VALUES (%d, '%s', %d, '%s');", 1, "Paul", 32, "California"); ``` To prevent a buffer overflow, usesnprintf()(introduced in C99).
I'm looking for a way to write an input loop that continues to print prompts until the user enters a blank line. This is what I want to do: Loop starts, prints prompt>to the command line. User enters a line that ends with '\n', my program does whatever with that line, and then prints>again. This continues until the user enters a blank line (\n), at this point the loop terminates.
Would something along these lines answer your needs? ``` int ret; // Basically, in order, 1 to indicate the file descriptor of the standard output // ">" as the string you want to print // 1 as the number of characters you want printed. write(1, ">", 1); while ((ret = read(0, buff, SizeBuff)) > 0) { buff[ret] = 0; if (buff[0] == '\n' && strlen(buff) == 1) return (0); /*Do your stuff*/ write(1, ">", 1); } ```
I understand floating point has rounding errors, but I'm wondering if there are certain situations where the error does not apply, such as multiplication by zero . Does zero times any number = zero for all floating points ?
False: ``` 0f * NAN == NAN 0f * INFINITY == NAN ``` and ... ``` 0f * -1f == -0f (negative 0f), with 0f == -0f :-) ``` (on Intel, VC++, and probably on any platform that uses IEEE 754-1985 floating points) Example onideone(that uses GCC on some Intel compatible platform probably)
My program asks the user to provide astring, which will be copied into an array of characters. Then, with aforloop, the program simply copies the elements of the first array into the second array. ``` int main() { int i; char string1[4], string2[4]; // Get the first string printf("Insert your string: "); scanf("%s", string1); // Copy the values into the second array for (i = 0; i < 4; i++) { string2[i] = string1[i]; } // Print the second string printf("%s", string2); return 0; } ``` However, when I print thestringusing theprintf()function thestringgets printed twice. Let's say I input the word bars The output will be barsbars Why is this happening?
``` char string1[4], string2[4]; ``` 4-element char array is not enough for 4-character strings. You need one more for the terminating'\0'character.
I'm learning C using C by Example. There is a question where we need to take an input integer and square it and print it to the screen. I'm having a strange error, when no matter what Int I enter it give me this output: ``` Please enter a number. 5 Number = 2686764 Square of Number = 2686760 ``` Here is the program I wrote. ``` #include <stdio.h> #include <conio.h> //for getch() main(){ int number, square; printf("Please enter a number. \n"); scanf("%d", &number); square = number*number; printf("\n Number = %d ", &number); printf("\t Square of Number = %d", &square); getch(); } ```
You are printing the memory address of thenumberandsquarevariables, not their values. Try this instead: ``` printf("\n Number = %d ", number); printf("\t Square of Number = %d", square); ```
I have a Python program asking the user for input like a shell, and if I detect some specific keywords I want to go inside some specific functions. The thing is that I would like to avoid doing a lot ofifandelse if. Usually in C to avoid this situation I use a function pointer array that I travel with awhileand usestrcmpto check the input. I would like to know how to do that in Python if it is even possible.
In Python you use adictionary. Example: ``` keyword2func = { "word1": function_word1, "word2": function_word2, } word = input("") keyword2func[word]() ```
I have some wave files (.wav) and I need to convert them in base64 encoded strings. Could you guide me how to do that in Python/C/C++ ?
@ForceBru's answer ``` import base64 enc=base64.b64encode(open("file.wav").read()) ``` has one problem. I noticed for some WAV files that I encoded the string generated was shorter than expected. Python docs for "open()" say If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. Hence, the code snippet doesn't read in binary. So, the below code should be used for better output. ``` import base64 enc = base64.b64encode(open("file.wav", "rb").read()) ```
In order to make some _Generic expressions work properly, it appears that the only option is to convert integer types to structure types and vice versa, with these meaningless conversions only ever being present in non selected expressions. I am having trouble definitively answering the question as to whether or not this is strictly c11 standard compliant.
Simple answer: In C you cannot convert an integer (or any scalar value) to a structure type and you cannot convert a structure object to an integer. You can use pointers (as mentioned byQixin the comments) to achieve the same and then dereference the converted object but it invokes undefined behavior by violating aliasing rules and possibly breaking alignment.
I'm beginner on C and checking this code ``` int is_finished() { int counter = 0; sem_wait(&global_mutex); counter = NotEatenCount; sem_post(&global_mutex); return counter==0; } ``` the function should return an integer. What doesreturn counter==0means in here? It looks like: ``` if(counter==0){ return true; } else{ return false; } ```
==evaluates to an integer that is either 0 or 1, depending on the comparison outcome. In this case, the function will return 1 (true) if counter is equal to 0; it will return 0 otherwise.
I'm learning C using C by Example. There is a question where we need to take an input integer and square it and print it to the screen. I'm having a strange error, when no matter what Int I enter it give me this output: ``` Please enter a number. 5 Number = 2686764 Square of Number = 2686760 ``` Here is the program I wrote. ``` #include <stdio.h> #include <conio.h> //for getch() main(){ int number, square; printf("Please enter a number. \n"); scanf("%d", &number); square = number*number; printf("\n Number = %d ", &number); printf("\t Square of Number = %d", &square); getch(); } ```
You are printing the memory address of thenumberandsquarevariables, not their values. Try this instead: ``` printf("\n Number = %d ", number); printf("\t Square of Number = %d", square); ```
I have a Python program asking the user for input like a shell, and if I detect some specific keywords I want to go inside some specific functions. The thing is that I would like to avoid doing a lot ofifandelse if. Usually in C to avoid this situation I use a function pointer array that I travel with awhileand usestrcmpto check the input. I would like to know how to do that in Python if it is even possible.
In Python you use adictionary. Example: ``` keyword2func = { "word1": function_word1, "word2": function_word2, } word = input("") keyword2func[word]() ```
I have some wave files (.wav) and I need to convert them in base64 encoded strings. Could you guide me how to do that in Python/C/C++ ?
@ForceBru's answer ``` import base64 enc=base64.b64encode(open("file.wav").read()) ``` has one problem. I noticed for some WAV files that I encoded the string generated was shorter than expected. Python docs for "open()" say If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. Hence, the code snippet doesn't read in binary. So, the below code should be used for better output. ``` import base64 enc = base64.b64encode(open("file.wav", "rb").read()) ```
In order to make some _Generic expressions work properly, it appears that the only option is to convert integer types to structure types and vice versa, with these meaningless conversions only ever being present in non selected expressions. I am having trouble definitively answering the question as to whether or not this is strictly c11 standard compliant.
Simple answer: In C you cannot convert an integer (or any scalar value) to a structure type and you cannot convert a structure object to an integer. You can use pointers (as mentioned byQixin the comments) to achieve the same and then dereference the converted object but it invokes undefined behavior by violating aliasing rules and possibly breaking alignment.
I'm beginner on C and checking this code ``` int is_finished() { int counter = 0; sem_wait(&global_mutex); counter = NotEatenCount; sem_post(&global_mutex); return counter==0; } ``` the function should return an integer. What doesreturn counter==0means in here? It looks like: ``` if(counter==0){ return true; } else{ return false; } ```
==evaluates to an integer that is either 0 or 1, depending on the comparison outcome. In this case, the function will return 1 (true) if counter is equal to 0; it will return 0 otherwise.
I do know how to read all the files from the current directory by opening directory"./"and then usingreaddir. But, how do I list only.txtfiles or any other specific extension? ``` DIR *p; struct dirent *pp; p = opendir ("./"); if (p != NULL) { while ((pp = readdir (p))!=NULL) puts (pp->d_name); (void) closedir (pp); } ```
Just check the filename before you print it. ``` DIR *p; struct dirent *pp; p = opendir ("./"); if (p != NULL) { while ((pp = readdir (p))!=NULL) { int length = strlen(pp->d_name); if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0) { puts (pp->d_name); } } (void) closedir (p); } ``` Incidentally you were also callingclosedir()on yourdirent(pp) rather than yourDIR *(p).
I looked over the internet trying to find a solution for writing line by line into a file in c. I found solutions like changing the mode offopen()tow+,wt,wbbut it did not work for me. I even read to put\rinstead of\nin the end of the line but still when I try to write to the file the only thing that is written there is the last line. ``` FILE *log = NULL; log = fopen(fileName, "w"); if (log == NULL) { printf("Error! can't open log file."); return -1; } fprintf(log, "you bought %s\n", pro[item].name); fclose(log); ``` Many thanks for your time and help.
It is because everytime you execute fprintf in "w" mode,the log gets overwrittenwith the new contents as the file was not opened in the 'append' mode but in 'write' mode. Better thing would be to use: ``` fopen("filename", "a"); ```
I have a struct that is supposed to be 8 byte in size. ``` struct Slot { uint8_t T; uint8_t S; uint32_t O : 24; uint32_t L : 24; } ``` However,sizeof(Slot)tells me the size is 12 byte. So the compiler seems to pad the data although it shouldn't be necessary (probably because the 24-bit cannot be aligned properly). A hacky solution would be to use 3 one-byte fields instead of a single three-byte field: ``` struct Slot2 { uint8_t T; uint8_t S; uint8_t O1; uint8_t O2; uint8_t O3; uint8_t L1; uint8_t L2; uint8_t L3; }; // sizeof(Slot2) = 8 ``` Is there any other way to achieve this?
This gives size 8 bytes on MSVC without packing pragma. ``` struct Slot { uint32_t O : 24; uint32_t T : 8; uint32_t L : 24; uint32_t S : 8; }; ```
``` #include<stdio.h> int a; int fun(int b) { static int c=3; return ((++a)+(++b)+(++c)); } Main() { int i,a=2; for(i=0;i<2;i++) printf("%5d",fun(a)); } ``` I think answer is 1012 but don't have comp I wanna know progress
in response to Frank Hao comment Globalint ais initialized as 0. ``` for i = 0; first call fun(2) { return ((1)+(3)+(4)); } for i = 1; second call fun(2) { return ((2)+(3)+(5)); } ```
Hello I have a little problem in my program ``` FILE* f; char * psz = new char[wcslen(file) + 1]; wsprintfA(psz, "%S", file); fopen_s(&f,psz, "w+b"); char * buffer = "data\heightmap.bmp"; fwrite(buffer,256, 1, f); fclose(f); //later in another class: FILE* f; char * bufer; fopen_s(&f,"data\test.dat", "rb"); fread(buffer,256, 1, f); fclose(f); ///buffer is "dataheightmap.bmp" not "data\heightmap.bmp" as it should be to open the file later. FILE* f; fopen_s(&f,buffer, "rb"); count = fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, f); fclose(f); ``` someone can help me please. Thanks Window7,visual studio 2013.
Remember that you need to escape your slashes: ``` "data\heightmap.bmp" "data\test.dat" ``` Should be: ``` "data\\heightmap.bmp" "data\\test.dat" ```
Is it safe to return a struct with array data member in C? Something like ``` struct my_str { int v[5]; }; struct my_str ret_stupid() { struct my_str rval; /*do something..*/ return rval; } ``` I don't know why... I'm a bit puzzled. (I've tried and it does work). Is there some standard explaining how this operation actually is performed? I mean the mechanism of struct return and assignment too could be useful to understand better.
Is it safe to return a struct with array data member in C? Yes. structare copied bit-wise. Bit-wise copying astructthat has an array as a member makes sure that the copy ofstructhas a copy of the array too.
was wondering how I would be able to store a user inputted string in the format "string,character,integer,integer" into a struct. For example storing "apple,c,5,10" into ``` typedef struct { char item[80]; char letter; int x,y; }information; information apple; ``` I am trying to avoid going through using scanf and a long piece of code to make the comma into a delimiter so wondering if there was any other way to quickly read from scanf and chucking this information into the struct
You can specify complex formats usingscanf, like: ``` scanf("%79[^,],%c,%d,%d", apple.item, &apple.letter, &apple.x, &apple.y); ``` %79[^,]means scan anything that is not a comma character, up to 79 characters. Note that this does no error handling if the user enters a poorly formatted string, like"aaa;b;1;2". For that, you'll need to write a lot more code. Seestrtok
so I have a string with the following value [7, 8] Now I wan't to store each value (only the numbers) in a 2D array [1][2].I'm pretty sure using sscanf is the best way to do this, but how do I tell sccanf to only read the integers? Thanks in advance
``` sscanf("[%d,%d]", Array[a][b], Array[c][d]); ```
I am trying to send a msg from a socket that will be in the form on ``` double,int,int,int,int,...,int ``` N int values how can i send it? i have opened a socket but how can i put all those elements in one array that will be sent in: ``` status=sendto(SendSocket,msg,sizeof(double)+N*sizeof(int), 0,(void*)&out_socketaddr,sizeof(out_socketaddr)); ``` Where MSG is the memory(array) of all those elements and out_socketaddr is the destination
``` uint8_t array [sizeof(this) + sizeof(that) + ...]; uint8_t* ptr = array; memcpy(ptr, &this, sizeof(this)); ptr+=sizeof(this); memcpy(ptr, &that, sizeof(that)); ptr+=sizeof(that); ... ``` Avoid making a struct. Although structs will make the code more readable, they also introduce padding, which will be an issue in this case.
Recently I had an Interview inC. The interviewer has asked me to explain how to access particular element in2D arrayusingdouble pointer. I gave the answer as*(*(a+i)+j), whereais a double pointer,iis number of rows andjis number of columns. Later he asked me to explain using an example. I am confused at*(a+i)as it gives value instead of address and adding tojgives some junk value. Can anyone please explain.
Remember that in a 1D arraya[i]equals*(a+i). And there are no 2D arrays in C, just arrays of arrays. Soa[i][j]is actually equal to*(*(a+i)+j). If the type ofaisint**, then the type of(a+i)is stillint**, you need to dereference it. Type of*(a+i)isint*and the type of*(*(a+i)+j)isint. About the interview question, no matter thatais a double pointer, you should still use the[]notation. The alternative is too cumbersome: ``` int **a = ...; int x = a[i][j]; ```
My program uses excve to run a ls, and the second argument is filled by the user : ``` char * envp[1] = { 0 }; execve(my_command, user_input, envp); ``` Is it possible for a user to inject a command in the user_input parameter even though it is considered as an argument? I tried running this but the $( is interpreted before : ``` ./my_program.out "$(cat /etc/passwd)" ``` Is there a way to escape the$but still inject the command?
No they can't inject commands unless there is a vulnerability inside ls. Seehttp://linux.die.net/man/2/execve The argument vector and environment can be accessed by the called program's main function, when it is defined as:int main(int argc, char *argv[], char *envp[])
I was wondering how the C compiler allocated memory for a character array you initialize yourself, for instance: ``` char example[] = "An example string"; ``` If it was a single character it would be8 byte, so would the example be17 bytesor does it have more because it needs to the\0to finish it off? Or does it overestimate how much memory it needs?
This code: ``` #include <stdio.h> int main(void) { char example[] = "An example string"; printf("%zu", sizeof(example)); } ``` Compiled with: ``` gcc -std=c99 -o proof proof.c ``` Returns: 18(bytes, not bits) Because of the\0character at the end of string
I fell over this little thing while coding: ``` char* strinit(char* str) { str = (char*) malloc(100); strcpy(str, "hello SO"); return str; } int main() { char* str = strinit(str); return 0; } ``` As you can see, I am using the same variable that I am declaring to initialize it. This is no problem. I tried the same thing in Java. That causes errors. So my question is: Is there any problems doing this? Can I use it in my code in good conscience?
C & C++ consider thatchar* str = strinit(str);is legal; because it is evaluated to: ``` char* str; str = strinit(str); ``` seeWhy is 'int i = i;' legal?
Whats difference in the working of ``` while(i++<100) ``` and ``` while(i++<100); ``` Is this correct that in 1st case,iincreases until its value reach to99but in 2nd case,;is an error that's why nothing is going to happen?
No: while(i++<100);is a loop with a empty command (does nothing untiliis 100), (there is no compilation error). Andwhile(i++<100) {commands}is a same loop but does someting.
I am writing some simple test automation to access the USB port in Ubuntu, and determine driver specific details, devices that are connected, and operating mode (USB 2 , 3 , etc ...). I have not done any development in this area, and was looking for advice on libraries / recommendations to accomplish this. Thank you for you help! Dan.
I've done this using libusb. You can get get started here.http://libusb.sourceforge.net/api-1.0/If you're just looking at seeing various usb devices, it's pretty easy. Here are some examples that you can get up and running pretty quickly:http://www.dreamincode.net/forums/topic/148707-introduction-to-using-libusb-10/
so I have a string with the following value [7, 8] Now I wan't to store each value (only the numbers) in a 2D array [1][2].I'm pretty sure using sscanf is the best way to do this, but how do I tell sccanf to only read the integers? Thanks in advance
``` sscanf("[%d,%d]", Array[a][b], Array[c][d]); ```
I am trying to send a msg from a socket that will be in the form on ``` double,int,int,int,int,...,int ``` N int values how can i send it? i have opened a socket but how can i put all those elements in one array that will be sent in: ``` status=sendto(SendSocket,msg,sizeof(double)+N*sizeof(int), 0,(void*)&out_socketaddr,sizeof(out_socketaddr)); ``` Where MSG is the memory(array) of all those elements and out_socketaddr is the destination
``` uint8_t array [sizeof(this) + sizeof(that) + ...]; uint8_t* ptr = array; memcpy(ptr, &this, sizeof(this)); ptr+=sizeof(this); memcpy(ptr, &that, sizeof(that)); ptr+=sizeof(that); ... ``` Avoid making a struct. Although structs will make the code more readable, they also introduce padding, which will be an issue in this case.
Recently I had an Interview inC. The interviewer has asked me to explain how to access particular element in2D arrayusingdouble pointer. I gave the answer as*(*(a+i)+j), whereais a double pointer,iis number of rows andjis number of columns. Later he asked me to explain using an example. I am confused at*(a+i)as it gives value instead of address and adding tojgives some junk value. Can anyone please explain.
Remember that in a 1D arraya[i]equals*(a+i). And there are no 2D arrays in C, just arrays of arrays. Soa[i][j]is actually equal to*(*(a+i)+j). If the type ofaisint**, then the type of(a+i)is stillint**, you need to dereference it. Type of*(a+i)isint*and the type of*(*(a+i)+j)isint. About the interview question, no matter thatais a double pointer, you should still use the[]notation. The alternative is too cumbersome: ``` int **a = ...; int x = a[i][j]; ```
My program uses excve to run a ls, and the second argument is filled by the user : ``` char * envp[1] = { 0 }; execve(my_command, user_input, envp); ``` Is it possible for a user to inject a command in the user_input parameter even though it is considered as an argument? I tried running this but the $( is interpreted before : ``` ./my_program.out "$(cat /etc/passwd)" ``` Is there a way to escape the$but still inject the command?
No they can't inject commands unless there is a vulnerability inside ls. Seehttp://linux.die.net/man/2/execve The argument vector and environment can be accessed by the called program's main function, when it is defined as:int main(int argc, char *argv[], char *envp[])
I was wondering how the C compiler allocated memory for a character array you initialize yourself, for instance: ``` char example[] = "An example string"; ``` If it was a single character it would be8 byte, so would the example be17 bytesor does it have more because it needs to the\0to finish it off? Or does it overestimate how much memory it needs?
This code: ``` #include <stdio.h> int main(void) { char example[] = "An example string"; printf("%zu", sizeof(example)); } ``` Compiled with: ``` gcc -std=c99 -o proof proof.c ``` Returns: 18(bytes, not bits) Because of the\0character at the end of string
I fell over this little thing while coding: ``` char* strinit(char* str) { str = (char*) malloc(100); strcpy(str, "hello SO"); return str; } int main() { char* str = strinit(str); return 0; } ``` As you can see, I am using the same variable that I am declaring to initialize it. This is no problem. I tried the same thing in Java. That causes errors. So my question is: Is there any problems doing this? Can I use it in my code in good conscience?
C & C++ consider thatchar* str = strinit(str);is legal; because it is evaluated to: ``` char* str; str = strinit(str); ``` seeWhy is 'int i = i;' legal?
Whats difference in the working of ``` while(i++<100) ``` and ``` while(i++<100); ``` Is this correct that in 1st case,iincreases until its value reach to99but in 2nd case,;is an error that's why nothing is going to happen?
No: while(i++<100);is a loop with a empty command (does nothing untiliis 100), (there is no compilation error). Andwhile(i++<100) {commands}is a same loop but does someting.
I am writing some simple test automation to access the USB port in Ubuntu, and determine driver specific details, devices that are connected, and operating mode (USB 2 , 3 , etc ...). I have not done any development in this area, and was looking for advice on libraries / recommendations to accomplish this. Thank you for you help! Dan.
I've done this using libusb. You can get get started here.http://libusb.sourceforge.net/api-1.0/If you're just looking at seeing various usb devices, it's pretty easy. Here are some examples that you can get up and running pretty quickly:http://www.dreamincode.net/forums/topic/148707-introduction-to-using-libusb-10/
The syntax commonly used in C to initialize pointers is ``` int *p = &x; ``` wherepis our pointer andxis a previously declared variable. I unfortunately don't understand this syntax:*pisnotequal to&x, but is instead equal tox. So why isn't the correct syntax ``` int *p = x;? ``` Does the compiler simply make an exception to the normal rules of variable assignment when dealing with pointers?
read it this way ``` int* p = &x; ``` ie int* is a type - a pointer to an int;
How do I that? I don't want to use the Visual Studio IDE, yet I want to use the provided compiler (cl.exe) and the Developer Command Prompt for VS2013.
I used to do it to via command line ``` cl /EHsc /MD main.cpp /Fetest.exe /I F:\C++_Libraries\SDL2\SDL2-2.0.3\include /link /LIBPATH:F:\C++_Libraries\SDL2\SDL2-2.0.3\lib\x86 SDL2.lib SDL2main.lib /SUBSYSTEM:CONSOLE ```
Can anyone explain to me the C-syntax below (from thistutorial)? I understand this is a macro for C, but the "DEBUG %s:%d: " M "\n"part seems strange to me: why is there the macro parameter 'M' in the middle of the format part? ``` #define debug(M, ...) fprintf(stderr, "DEBUG %s:%d: " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) ```
C has an interesting quirk that it concatenates string literals. If you type ``` "DEBUG %s:%d: " "HELLO %s!" "\n" ``` Then the compiler sees that as one string:"DEBUG %s:%d: HELLO %s!\n". So users can use this macro as if it were simply had printf parameters: ``` debug("HELLO %s", username); //on line 94 of myfile.cpp ``` and the macro will automatically add the file name and line number. This format is useful because it helps you knowwhichdebug statement is logging information. ``` DEBUG myfile.cpp:94: HELLO zell ```
This question already has answers here:How can I convert an int to a string in C?(11 answers)Closed8 years ago. I'm trying to convert an integer to a string in C but the current code doesn't make it. I'm not seeking to display it in the screen, so all the functions printf, sprintf... are irrelevant. ``` int X = 15; char *T; T = (char*)X; // Expected result : "15" ``` Can anyone help please ? Thanks.
Not displaying it to screen doesn't invalidate functions like sprintf() since they literally "print to string". ``` int X = 15; char buffer[10]; memset(&buffer, 0, sizeof(buffer)); // zero out the buffer sprintf(buffer, "%d", X); // Expected result : "15" printf("contents of buffer: %s\n", buffer); ```
Under Visual Studio source-code-defined strings likeL"abc"result into a C-string with 2-bytes wide chars. What about Linux compilers ? Is it also possible to use the L"" syntax ?If yes, are the chars of the C-string linux wide chars (i.e 4-bytes wide) ?Is there a "cross-compiler" way to define UCS-2 or UTF-16 encoded unicode strings ? Thank you. :) EDIT : Forgot to mention that I can't use C++11.
There is no cross-platform way to conveniently write UTF-16 string literals without using at least C11 or C++11 (where you can useu"..."). The wide string syntax (L"...") creates aconst wchar_t*using an implementation-defined encoding. On Windows, this encoding is UTF-16; with GCC (using GNU's libc), this encoding is UTF-32. The only safe and portable way to create UTF-16—or any UTF—strings (pre-C11/C++11) is to write them as integer arrays. For example: ``` const uint16_t str[] = { 0x24EA, 0x0 }; ```
How do I calculate a power in C, and do you have to include anything? I have tried to include math.h, however it didn't work. What is de difference between a int and a double in this case.
To calculate a power in C, the best way is to use the functionpow(). It takes twodoublearguments: the first is the number that will be raised by the power, and the second argument is the power amount itself. So:double z = pow(double x, double y); Then the result will be saved into the double z. You will have to use themath.hlibrary in order to use this function.
I'm a real newbie in C programming, I've read a lot about pointers but it seems i'm still confusing myself. I'm trying to get a single character from a string sucessively, here is my code: ``` #include <stdio.h> int main(int argc, const char *argv[]) { char input[128]; char *ch; scanf("%s", &input); for (ch = input; *ch; ch++) { printf("%s\n", ch); } return 0; } ``` If I enter "hello" i get the following output: ``` hello ello llo lo o ``` I have triedprintf("%s\n", &ch[0]);, but still the same thing. Any help with this would be great, thanks.
You are still printing a string and incrementing its starting position. ``` printf("%c\n", *ch); ```
``` int main(int argc, char *argv[]) { char *arr; arr = (char*)malloc((strlen(argv[1]) + 1) * sizeof(char));//1 additional byte for the backslash. strcpy(arr, argv[1]); strcat(arr, '\\'); return 0; } ``` After this code I getAccess violation readingerror.Basically I'm just trying to append a backslash to a dynamic string that contains the first argument of the program.
This is probably wrong: ``` arr = (char*)malloc((strlen(argv[1]) + 1) * sizeof(char)); ``` argv[1]+1is the second argument, if exists. You wanted: ``` arr = malloc(strlen(argv[1]) + 2); ``` I simplified this line a lot sincesizeof(char)is1by definition and adding2instead of1as you would need additional byte for the nul terminator. Castingmallocisunnecessary. strcatoperates on strings.'\\'is not a string. It should be: ``` strcat(arr, "\\"); ```
Please explain the difference between ``` char* str = "Hello"; ``` And ``` char* str = {"Hello"}; ```
ISO 9899-1990 6.5.7("Initialization") says : An array of character type may be initialized by a character string literal, optionally enclosed in braces.
I'm a real newbie in C programming, I've read a lot about pointers but it seems i'm still confusing myself. I'm trying to get a single character from a string sucessively, here is my code: ``` #include <stdio.h> int main(int argc, const char *argv[]) { char input[128]; char *ch; scanf("%s", &input); for (ch = input; *ch; ch++) { printf("%s\n", ch); } return 0; } ``` If I enter "hello" i get the following output: ``` hello ello llo lo o ``` I have triedprintf("%s\n", &ch[0]);, but still the same thing. Any help with this would be great, thanks.
You are still printing a string and incrementing its starting position. ``` printf("%c\n", *ch); ```
``` int main(int argc, char *argv[]) { char *arr; arr = (char*)malloc((strlen(argv[1]) + 1) * sizeof(char));//1 additional byte for the backslash. strcpy(arr, argv[1]); strcat(arr, '\\'); return 0; } ``` After this code I getAccess violation readingerror.Basically I'm just trying to append a backslash to a dynamic string that contains the first argument of the program.
This is probably wrong: ``` arr = (char*)malloc((strlen(argv[1]) + 1) * sizeof(char)); ``` argv[1]+1is the second argument, if exists. You wanted: ``` arr = malloc(strlen(argv[1]) + 2); ``` I simplified this line a lot sincesizeof(char)is1by definition and adding2instead of1as you would need additional byte for the nul terminator. Castingmallocisunnecessary. strcatoperates on strings.'\\'is not a string. It should be: ``` strcat(arr, "\\"); ```
Please explain the difference between ``` char* str = "Hello"; ``` And ``` char* str = {"Hello"}; ```
ISO 9899-1990 6.5.7("Initialization") says : An array of character type may be initialized by a character string literal, optionally enclosed in braces.
I'm trying to handcraft a HTTP request. My question is, how is the protocol header supposed to be separated from the body? Is there a special byte used or should\r\nbe adequate? Thanks
You separate the header from the body by a double crlf. Example from Wikipedia: ``` HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT ETag: "3f80f-1b6-3e1cb03b" Content-Type: text/html; charset=UTF-8 Content-Length: 138 Accept-Ranges: bytes Connection: close <html> <head> <title>An Example Page</title> </head> <body> Hello World, this is a very simple HTML document. </body> </html> ```
I have developed a simple console utility in C which parses various text files. IDE - Code Blocks OS - windows I intend to distribute its executable. The executable works fine, however unlike when executed from the IDE, the execution does not pause/wait for keystroke at the end of execution. I tried using getchar()/system("pause"), but the execution doesn't pause there. Is there an alternative to wait for keystroke before ending execution, so that the user can view the output?
You can use getchar(); twice , because its very likely that last '\n' newline character will get consumed by your getchar(). or use scanf(" %c"); with that extra space at the end of your file .
I have a file which includes datas as [name surname] [birthday] [id] when i try this code ``` while(fscanf(file,"%s %s %s",name,bdate,uid) == 3) ``` bdate gets surname] as a value how can i read informations between square brackets. thanks.
You're better off withfgets()and a real parser, but try the usingscanf "scanset"for a quick fix ``` fscanf(file, " [%[^][]] [%[^][]] [%[^][]]", name, bdate, uid) // ^ ^ ^ ordinary whitespace // ^ ^ ^ ^ ^ ^ ordinary characters // ^^---^ ^^---^ ^^---^ scanset specification // ^ "reverse" scanlist // ^^ characters in scanlist ```
I'm currently learning how to code C and stumbled upon an interesting line, Apparently, ``` struct node{ node *next; }; node *head = (node *)calloc(1, sizeOf(node)); head->next = NULL; node *currentNode = head; while (!currentNode) ``` In this context, is ``` while(!currentNode) ``` different to ``` while(currentNode != NULL) ``` ? I thought they meant to check for the same stuff, when current Node is not NULL but they are returning different results and I dont' understand...
``` while(currentNode) ``` and ``` while(currentNode != NULL) ``` are equivalent. The first says that whilecurrentNodehas some value (could be anything, even garbage), the second one says that whilecurrentNodeis notNULL, i.e., has some value. On the other hand, ``` while(!currentNode) ``` means that whilecurrentNodedoes not hold any value, i.e, isNULL.
I am in need to open the default file manager of the user's system (not a dialog, but the file manager used by the system) using gtk and C. meaning, when a user chooses a directory, file manager will open and not a dialog. is there any way to achieve this?
You should use GIO: ``` GError *error = NULL; if (!g_app_info_launch_default_for_uri ("file:///", NULL, &error)) { g_warning ("Failed to open uri: %s", error->message); } ``` Note that this almost certainly requires a running GLib main loop (but if you're using GTK+, you already have that). Also, there's no 100% guarantee that a file manager will be opened, but on any sanely set up system that is going to be the default handler for uris that are directories. On a normal GNOME system @keltars xdg-open method forks, runs a shell script that starts a binary that then runs the sameg_app_info_launch_default_for_uri()function.
I implemented a squaring define directive as this : ``` #include <stdio.h> #define SQR(y) ((y)*(y)) int main() { int a; printf("Enter : "); scanf("%d",&a); a = SQR(a); printf("The square is: %d\n",SQR(a)); return 0; } ``` But when I execute it, I don't get any error, but it is giving wrong answer every time. Why is it giving 4th power instead of second power of input?
You are squaring it twice. In your code: ``` a = SQR(a); printf("The square is: %d\n",SQR(a)); ``` this first makesa = a*aNow you printSQR((a*a)*(a*a)), ora*a*a*a You can replaceSQR(a)inprintfwith a,orremove thea = SQR(a) Try this : ``` #include <stdio.h> #define SQR(y) ((y)*(y)) int main() { int a; printf("Enter : "); scanf("%d",&a); printf("The square is: %d\n",SQR(a)); return 0; } ```
I have developed a simple console utility in C which parses various text files. IDE - Code Blocks OS - windows I intend to distribute its executable. The executable works fine, however unlike when executed from the IDE, the execution does not pause/wait for keystroke at the end of execution. I tried using getchar()/system("pause"), but the execution doesn't pause there. Is there an alternative to wait for keystroke before ending execution, so that the user can view the output?
You can use getchar(); twice , because its very likely that last '\n' newline character will get consumed by your getchar(). or use scanf(" %c"); with that extra space at the end of your file .
I have a file which includes datas as [name surname] [birthday] [id] when i try this code ``` while(fscanf(file,"%s %s %s",name,bdate,uid) == 3) ``` bdate gets surname] as a value how can i read informations between square brackets. thanks.
You're better off withfgets()and a real parser, but try the usingscanf "scanset"for a quick fix ``` fscanf(file, " [%[^][]] [%[^][]] [%[^][]]", name, bdate, uid) // ^ ^ ^ ordinary whitespace // ^ ^ ^ ^ ^ ^ ordinary characters // ^^---^ ^^---^ ^^---^ scanset specification // ^ "reverse" scanlist // ^^ characters in scanlist ```
I'm currently learning how to code C and stumbled upon an interesting line, Apparently, ``` struct node{ node *next; }; node *head = (node *)calloc(1, sizeOf(node)); head->next = NULL; node *currentNode = head; while (!currentNode) ``` In this context, is ``` while(!currentNode) ``` different to ``` while(currentNode != NULL) ``` ? I thought they meant to check for the same stuff, when current Node is not NULL but they are returning different results and I dont' understand...
``` while(currentNode) ``` and ``` while(currentNode != NULL) ``` are equivalent. The first says that whilecurrentNodehas some value (could be anything, even garbage), the second one says that whilecurrentNodeis notNULL, i.e., has some value. On the other hand, ``` while(!currentNode) ``` means that whilecurrentNodedoes not hold any value, i.e, isNULL.
I am in need to open the default file manager of the user's system (not a dialog, but the file manager used by the system) using gtk and C. meaning, when a user chooses a directory, file manager will open and not a dialog. is there any way to achieve this?
You should use GIO: ``` GError *error = NULL; if (!g_app_info_launch_default_for_uri ("file:///", NULL, &error)) { g_warning ("Failed to open uri: %s", error->message); } ``` Note that this almost certainly requires a running GLib main loop (but if you're using GTK+, you already have that). Also, there's no 100% guarantee that a file manager will be opened, but on any sanely set up system that is going to be the default handler for uris that are directories. On a normal GNOME system @keltars xdg-open method forks, runs a shell script that starts a binary that then runs the sameg_app_info_launch_default_for_uri()function.
I implemented a squaring define directive as this : ``` #include <stdio.h> #define SQR(y) ((y)*(y)) int main() { int a; printf("Enter : "); scanf("%d",&a); a = SQR(a); printf("The square is: %d\n",SQR(a)); return 0; } ``` But when I execute it, I don't get any error, but it is giving wrong answer every time. Why is it giving 4th power instead of second power of input?
You are squaring it twice. In your code: ``` a = SQR(a); printf("The square is: %d\n",SQR(a)); ``` this first makesa = a*aNow you printSQR((a*a)*(a*a)), ora*a*a*a You can replaceSQR(a)inprintfwith a,orremove thea = SQR(a) Try this : ``` #include <stdio.h> #define SQR(y) ((y)*(y)) int main() { int a; printf("Enter : "); scanf("%d",&a); printf("The square is: %d\n",SQR(a)); return 0; } ```
I try to get an idea how to save a text file while i keep the user write the name of this text file. ``` char filename[20]; gets(filename); fp = fopen ( filename, "wb+"); ``` When I save it, it will not be a text file. I can do it byf=fopen("file.txt", "r")but I want the name is chosen by the user.
First get file name: ``` char name[100] = {0}; fgets (name, 100, stdin); ``` Then create text file: ``` // Open as text file FILE *f = fopen(name, "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } // write some text const char *text = "Write this to the file"; fprintf(f, "Some text: %s\n", text); fclose(f); ```
Create file using C in Ubuntu. I've tried that code and it doesn't work. ``` #include<stdio.h> #include<string.h> int main() { char a[50]; char command[150]; printf("Enter The File's Name"); gets(a); strcpy("touch "); strcat("a"); system(command); return 0; } ```
Your strcpy should bestrcpy(command, "touch")and your strcat should bestrcat(command, a) But there are much better ways to create an empty file...
This question already has answers here:MySQL and C : undefined reference to `_mysql_init@4'|(3 answers)Closed8 years ago. When I try to connect to my database I get an error : undefined reference to 'mysql_init@4' ``` #include<mysql.h> int main() { MYSQL *con; con = mysql_init(NULL); return 0; } ``` I use code blocks. What is the issue?
"Undefined Reference" to something implies a linker error. In this case you are possibly not linking to the right mysql C library. Link with the appropriate C libraries. Also, a similar question is answeredhere
I have a main() routine which takes in all the command line arguments as a 'char **'. How do I display every one of the arguments in the console using printf()? Thanks!
If you mean command line arguments then I think the simplest approach looks like ``` #include <stdio.h> int main( int argc, char * argv[] ) { while ( *argv ) printf( "%s\n", *argv++ ); } ``` Take into account that ( C Standard, 5.1.2.2.1 Program startup, p.N2) — If the value of argc is greater than zero,the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
Why doesn't this work? ``` printf("%d \n\n\n\n", atoi("11110010100")); ``` it outputs -1774891788... I just want it outputted as it is. It seems to work just fine if the number is a bit smaller.
atoireturns anint. You pass a string which contains a number bigger than whatint(in your implementation) can hold. So, you have an integer overflow. To print the maximum value anintcan hold, includelimits.hand printINT_MAX.
Newbie question: why can't I getprintfto output the binary number as it is, instead of converting it? ``` int gpa = 01011001; printf("pure: %i \n", gpa); ``` gives the output: 266753 How can I get it to output 01011001 or just 1011001?
0preceding an integer literal is hold for octa-decimal number. Decimal equivalent of01011001is266753. Remove that preceding0to print as it is.
When a ListView item is selected, its color changes to indicate that it is selected. Now what I want to do is to disable this visual effect and implement my own, so for example I want when an item is selected to draw a rectangle around the item. How can I do that? (Note that I am talking about the Icon view).
This is a case forcustom drawing of controls. It's all about handling theNM_CUSTOMDRAWnotification and then to draw the control more or less by yourself. I've never done it by myself changing the appearance seriously but I've change background colors of controls using this mechanism. There is a lot of information about this on the internet...
I'm really sorry if my question is a duplicate, but I didn't find useful infos in the site. I'm using non blocking sockets and a select(). How can I detect if a client closed the connection on non-blocking socket? I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read and also when a connection is closed. How can I discriminate above cases?
When the peer has closed the connection: select()will return the socket as readable.Arecv()orread()on the socket will return zero. I saw that a read() returns -1 with errno = EWOULDBLOCK when no datas are available to be read Correct, but the connection isn't closed. and also when a connection is closed. No you didn't. That's not correct. It returns zero. How can I discriminate above cases? They aren't the same, and they don't manifest themselves in the same way.
I have a code something like this, but I want to display it in two dimensional array like 4*10. I'm thinking of copying the elements of one dimensional array to two dimensional. But how can i edit this below code. Thank you. ``` long int arr[40]; printf("The Fibonacci range is: "); arr[0]=0; arr[1]=1; for(i=2;i<range;i++){ arr[i] = arr[i-1] + arr[i-2]; } for(i=0;i<range;i++) printf("%ld ",arr[i]); ```
You have all of the one dimensional completed. Using the same process you can add it toarray[x][y], and loop through. The only thing is you would need to keep track of two indexes instead of one. Code it all and you will get it.
Create file using C in Ubuntu. I've tried that code and it doesn't work. ``` #include<stdio.h> #include<string.h> int main() { char a[50]; char command[150]; printf("Enter The File's Name"); gets(a); strcpy("touch "); strcat("a"); system(command); return 0; } ```
Your strcpy should bestrcpy(command, "touch")and your strcat should bestrcat(command, a) But there are much better ways to create an empty file...
This question already has answers here:MySQL and C : undefined reference to `_mysql_init@4'|(3 answers)Closed8 years ago. When I try to connect to my database I get an error : undefined reference to 'mysql_init@4' ``` #include<mysql.h> int main() { MYSQL *con; con = mysql_init(NULL); return 0; } ``` I use code blocks. What is the issue?
"Undefined Reference" to something implies a linker error. In this case you are possibly not linking to the right mysql C library. Link with the appropriate C libraries. Also, a similar question is answeredhere
I have a main() routine which takes in all the command line arguments as a 'char **'. How do I display every one of the arguments in the console using printf()? Thanks!
If you mean command line arguments then I think the simplest approach looks like ``` #include <stdio.h> int main( int argc, char * argv[] ) { while ( *argv ) printf( "%s\n", *argv++ ); } ``` Take into account that ( C Standard, 5.1.2.2.1 Program startup, p.N2) — If the value of argc is greater than zero,the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
I use access in order to understand file is exist or not. ``` char file[100]; strcpy(file, "/home/asd/test.txt"); if(access(file, F_OK) >= 0) { printf("file is exist \n"); } else { printf("file is not exist \n"); } ``` I try to understand is there any file with txt extension or not so I want to use this code for file extension not file name. How can I do that?
I've thrown together a minimal solution usingglobwhich could serve you as a base for proper code. It lacks proper error handling but that's something you can work out from examples likethis one. ``` #include <stdio.h> #include <glob.h> int main() { glob_t results; int r = glob("/tmp/*.txt", 0, 0, &results); if (r == 0) { fprintf(stdout, "text files found"); } else if (r == GLOB_NOMATCH) { fprintf(stdout, "No files found"); } else { fprintf(stdout, "glob error"); } return 0; } ```
I have a simple C program that represents a loading screen within the console, but I can't get the cursor to hide. I tried cranking up the speed of the sleep function so that the cursor timer would be reset and the cursor would be gone but that doesn't work. Any tips on how to hide the cursor? Code: ``` #include <stdio.h> #include <stdlib.h> const int TIME = 1; int main(int argc,char *argv[]){ int i; while (1){ printf("loading"); for (i=0;i<3;i++){ sleep(TIME); printf("."); } sleep(TIME); printf("\r"); system("Cls"); sleep(TIME); } } ```
To extend on Bishal's answer: To hide the cursor:printf("\e[?25l"); To re-enable the cursor:printf("\e[?25h"); Source
I tried to read some data from file and insert it to queue, Insert function works well, and i tried to catch the error with printfs. I saw that in while() line there is error. The data in file forms like that 12345 2 11232 4 22311 4 22231 2 ``` void read_file(struct Queue *head){ FILE *fp; int natid; int cond; fp=fopen("patients.txt","r"); while (fscanf(fp,"%d %d", natid, cond) != EOF) insert(head,natid,cond); fclose(fp);} ```
You must passpointersto wherefscanf()shall store the values, and check that all expected conversions succeed: ``` while (fscanf(fp, "%d %d", &natid, &cond) == 2) ```
I am having trouble building a tokenizer. I am new to c++ and was wondering if anyone could help. When I run the program, I enter the user input as "x = a + 1". When i do this, the only token output is thex. I want to display"x\n = a\n +\n 1\n" ``` #include <iostream> #include <string> using namespace std; int main(void) { char *text = (char*)malloc ( 40 *sizeof( char )); cout << "Enter the first arrangement of data." << endl; cin >> text; char *token = strtok(text, " "); while ( token ) { if ( strlen(token) > 0 ) { printf(" %s", token); } token = strtok(NULL, " "); } return 0; } ```
You are not reading the entire input. Change ``` cin >> text; ``` to ``` cin.getline(text, 40); ```
I have this code that works for me: ``` fp = fopen("person.dat", "rb"); struct Person{ int pnummer; char name[20]; float lenght; float weight; }; struct Person*object=malloc(sizeof(struct Person)); fread(object, sizeof(struct Person), 1, fp); printf("%s\n%d\n%f\n%f\n",object->name,object->pnummer,object->lenght,object->weight); ``` Output: Andreas 660311 181.000000 82.000000 I would like to read an array of this struct. So that i can have 10 persons. How do I write the last 3 lines? ``` typedef struct{ int pnummer; char name[20]; float lenght; float weight; }Person; Person p_lista[10]; ```
``` Person p_lista[10]; ... fread(p_lista, sizeof(struct Person), 10, fp); ``` There is no error checking for simplicity.
``` #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node* insert(struct node *root) { root->data = 12; //here return root; } int main() { struct node *root; insert(root); return 0; } ``` Shouldn't my program crash at the place where I have placed the comment in theinsertfunction because I have not initialized it withmalloc?
This is calledundefined behaviorYou never know what might happen.Crash is still a possibility. Using uninitialized variabled lead to undefined behavior.
``` index = {27,27,27,27,27}; //as many as rootsize ``` Compiler gives me an error when I try this in a function. Index is globally initialized in the same file with: ``` int index[5]; ``` error: expected expression index = {27,27,27,27,27}; //as many as rootsize Is this not legal? How would I set an array to some values all at once? Would I need a loop?
You cannot directly assign to an array. You can, however,memcpy()to it from a compound literal: ``` #include <string.h> memcpy(index, (int [5]){ 27, 27, 27, 27, 27 }, sizeof index); ``` Note that compound literals like this are a C feature, but not C++.
I'm trying to find how to color my text in orange. I tried this: ``` SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | BACKGROUND_GREEN); ``` But it will give me a red on green text. Is it even possible to get the color orange? i tried different codes i found in the internet, but none of them gave me orange. thanks for the help.
You can try the following bit mask:FOREGROUND_RED | FOREGROUND_GREEN. It will change the color of thetextto orange. You may still want to experiment withBACKGROUND_*to adjust the background color to your needs.
I need to read a huge number from the stdin, here is the code i have so far: ``` int main() { int x; int* n1; scanf("%d", &x); // I get the number of digits the integer will have n1 = malloc(x * sizeof(int)); // I resize the integer pointer } ``` So my question is how can I read this possibly huge sized int from stdin?
There is no such thing as a "dynamic sized int" in C. As others have suggested, depending on your use case, reading the number as a string might be what you want. (If you usescanffor this, beware of buffer overflows.) If you need to do arithmetic on the number, you might wish to use an existing library such aslibgmpfor this to benefit from an existing solution to the problem. You could also re-implement libgmp's functionality yourself, but unless you're doing this as a learning exercise, there's little reason to.
If I compile my program withccthen it works. But I must compile usinggcc -pedantic -Wall -ansi -O4. Then I get a warning for the statementwait(NULL) ``` miniShell.c: In function ‘main’: miniShell.c:84:13: warning: implicit declaration of function ‘wait’ [-Wimplicit-function-declaration] wait(NULL); ^ ``` Can I rewrite it to please the compiler?
From theLinux Programmer's Manual: ``` WAIT(2) Linux Programmer's Manual WAIT(2) NAME wait, waitpid, waitid - wait for process to change state SYNOPSIS #include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); ``` So add those two#includes to usewait().
When you have loop in the loop or nested loop, let`s say for-loop, regardless of the programming language(of course must be imperative) ``` for(int j = 1; j <= 100; j++){ for(int k = 1; k <= 200; k++){ \\body or terms } } ``` is the mathematical equivalent, when I want to sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on : And the red-circled condition is unnecessary, right? And the same applies for multiple nested loops?
The code you provided will run as you explained sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on However, the mathematical equivalent iswithoutthe condition marked in red. The sigmaswiththe condition is equivalent to this code: ``` for(int j = 1; j <= 100; j++){ for(int k = 1; k < j; k++){ \\body or terms } } ``` Hope I helped.
I'm trying to find how to color my text in orange. I tried this: ``` SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | BACKGROUND_GREEN); ``` But it will give me a red on green text. Is it even possible to get the color orange? i tried different codes i found in the internet, but none of them gave me orange. thanks for the help.
You can try the following bit mask:FOREGROUND_RED | FOREGROUND_GREEN. It will change the color of thetextto orange. You may still want to experiment withBACKGROUND_*to adjust the background color to your needs.
I need to read a huge number from the stdin, here is the code i have so far: ``` int main() { int x; int* n1; scanf("%d", &x); // I get the number of digits the integer will have n1 = malloc(x * sizeof(int)); // I resize the integer pointer } ``` So my question is how can I read this possibly huge sized int from stdin?
There is no such thing as a "dynamic sized int" in C. As others have suggested, depending on your use case, reading the number as a string might be what you want. (If you usescanffor this, beware of buffer overflows.) If you need to do arithmetic on the number, you might wish to use an existing library such aslibgmpfor this to benefit from an existing solution to the problem. You could also re-implement libgmp's functionality yourself, but unless you're doing this as a learning exercise, there's little reason to.
If I compile my program withccthen it works. But I must compile usinggcc -pedantic -Wall -ansi -O4. Then I get a warning for the statementwait(NULL) ``` miniShell.c: In function ‘main’: miniShell.c:84:13: warning: implicit declaration of function ‘wait’ [-Wimplicit-function-declaration] wait(NULL); ^ ``` Can I rewrite it to please the compiler?
From theLinux Programmer's Manual: ``` WAIT(2) Linux Programmer's Manual WAIT(2) NAME wait, waitpid, waitid - wait for process to change state SYNOPSIS #include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); ``` So add those two#includes to usewait().
When you have loop in the loop or nested loop, let`s say for-loop, regardless of the programming language(of course must be imperative) ``` for(int j = 1; j <= 100; j++){ for(int k = 1; k <= 200; k++){ \\body or terms } } ``` is the mathematical equivalent, when I want to sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on : And the red-circled condition is unnecessary, right? And the same applies for multiple nested loops?
The code you provided will run as you explained sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on However, the mathematical equivalent iswithoutthe condition marked in red. The sigmaswiththe condition is equivalent to this code: ``` for(int j = 1; j <= 100; j++){ for(int k = 1; k < j; k++){ \\body or terms } } ``` Hope I helped.