question
stringlengths
25
894
answer
stringlengths
4
863
Hello so I compiled tcc (Tiny C Compiler) with the armv7 cross compiler on Ubuntu, arm-linux-gnueabi-gcc. I pushed it to the android bin (/system/bin) and was able to execute it, however I'm missing all of the C header files! Where would I put the arm c header files on a android device? (sorry if this is the wrong community this community is where I guess this question should go).
To fix the issue I created the folder /usr/include in root directory (/) and put header files in the include folder, and successfully compiled with header files!
I am reading in a text file and using a comma as a delimiter, the line below does work however when I print out lname it does not ignore the white space after the comma and prints a space before name. How can I adjust the code to ignore white space? example of text: Rob, Smith, 4, 12, sometextSteve, Jones, 41, 286, sometext ``` sscanf(line, "%[^,],%[^,],%d,%d,%s", fname,lname,&num1,&num2,info); ```
Just add a whitespace character if you want to ignore whitespace: ``` sscanf(line, " %[^,], %[^,], %d, %d, %s", fname, lname, &num1, &num2, info); ``` The space before%dand%sare not required as they already skip leading whitespace characters. The only format specifiers which does not skip leading whitespace are%c,%[and%n. Note that a whitespace character in the format string of*scanfinstructsscanfto scan any number of whitespace, including none, until the first non-whitespace character.
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question In the following code, I am trying to read a file char by char and display each char on the console: ``` #include <stdio.h> #pragma warning(disable:4996) int main(){ FILE *file; file = fopen("input.txt", "r"); int c; while ((c = fgetc(file)) != EOF) { printf("%c ",(char)c ); } return 0; } ``` I got the following error: Can someone help me solving this issue?
You must check the result of fopen. The pointer file is NULL because the opening failed. ``` file = fopen("input.txt", "r"); if (file == NULL) { //error } ```
I have an anonymous union nested within a struct, as well as other common fields. Is there any reason to place the union in a specific place within the struct (e.g. first or last)? For example, is this: ``` typedef struct _Message { MessageType type; union { SystemMessageArgs systemArgs; OtherMessageArgs usbArgs; }; } Message; ``` better than this: ``` typedef struct _Message { union { SystemMessageArgs systemArgs; OtherMessageArgs usbArgs; }; MessageType type; } Message; ``` in any way? The context is embedded-C, specifically TI's MSP430
There may be a possible difference in padding, you can find that out by usingsizeof()on both of them and comparing the results. This may be relevant if you are dealing with heavily constrained memory amounts. Other than that, they are equivalent.
When I use strsep() to iterate through the tokens of a string, is it safe for me to store pointers to those tokens, and refer to them later? Example: ``` char str[] = "some word tokens"; char *sameStr = str; char *token, *old1, *old2; token = strsep(&sameStr, " "); old1 = token; token = strsep(&sameStr, " "); old2 = token; token = strsep(&sameStr, " "); printf("%s\n%s\n%s\n", token, old1, old2); ``` It seems like strsep() always modifies the original character array, inserting null characters after each token. If so, I should be safe storing and later using theold1andold2pointers, right? Also, does my use ofsameStrcause any problems? I can't use the pointerstrdirectly due to strsep() expecting a restricted char** type.
The stored pointers will be valid until the original string goes out of scope. Until then, you can access them however you need to. The use ofsameStrshouldn't cause any problems.
Is there a way to ensure that a thread was created before moving on to other instructions (without using a detour such assleep())? I have a loop that looks something like this: ``` for(i = 0; i < NUM_THREADS; ++i) { if(pthread_create(&threads_id_array[i], NULL, ThreadFunction, &args)) { perror("pthread_create() error"); exit(1); } args.base += args.offset; } ``` Wherebaseis a pointer to an array. I want to ensure that a thread was created before the promotion ofbaseso that I can be sure that the thread'sargs.baseholds the correct value. Currently, this causes bugs.
If you are doing that to speed up some CPU-bound work, consider OpenMP instead of pthreads. Like this: ``` #pragma omp parallel for for(i = 0; i < NUM_THREADS; i++) { auto threadArgs = args; threadArgs.base += i * threadArgs.offset; ThreadFunction( &threadArgs ); } ```
I want to be doing C/C++ development with the ESP8266 using my favorite editor at the time (VS Code). Don't want to be using the Arduino IDE. I have the ESP Open SDK up and running and all, but find it rather annoying having to be flashing every time I want to deploy. Takes about 30 seconds getting both images across. This is a horrific feedback loop for me. Before I head off writing my own Socket server that can take binaries and reflash while running or similar.. This must be a solved problem.. ??
PlatformIO, which bills itself as an "an open source ecosystem for IoT development" has integration with VS Code. Instructions for VS Code are at:http://platformio.org/get-started/ide?install=vscode You can use this instead of the Arduino IDE.
I have following program in C: ``` #include<stdio.h> int main() { printf("Normal.\n"); return 0; } int fff() { printf("Fun!\n"); return 0; } ``` I wanted to compile it so that when I run the program, it gives me "Fun!". I used following line to compile my program: ``` gcc deneme.c -e fff -o deneme ``` When I run program named "deneme", i got : ``` Fun! Segmentation fault (core dumped) ``` As you can see, i got what I want, but do not understand "segmentation fault" part. What is the reason?
You're trying to specifyfff()as an entry function, but the-eflag replaces the function_start, not main. You'll want to change the return type offfftovoidand call_exitat the end of the function. ``` void fff() { printf("Fun!\n"); _exit(0); } ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I have an input number that it's value is not always consistent, i mean the value change plus 1 or minus 1 and etc. So, i want to compare it with a const but have a small range value, for example a const int Dist that have value between 14 to 16. Is that possible to implement it on C programming? Please help me.
You can set constant for lower bound, and constant for upper bound and check if the value falls within the range. Pseudocode: ``` int const LOWER_BOUND = 14; int const UPPER_BOUND = 16; if (input <= UPPER_BOUND && input >= LOWER_BOUND) ... logic here ... ```
I know that arrays are passed by reference in a function call, but what if you only pass an array element, e.g.func(ar[0]). Doesarg[0]get passed by value or by reference?
Arrays are not passed by reference, theydecayas pointers when used as function arguments or in a expression, except as an operand to thesizeofoperator. Hence a function receives a pointer to the first element of the array, regardless of how the argument is defined in the function prototype, as a pointer or an array. If you pass an array element, it is passed by value, unless this array element is an array itself, in which case a pointer to the first element is passed.
In the stack frame of the main function of a C\C++ program, is there a saved return adress and a saved stack pointer (ebp)? If so, where do they point to, since there was no previous stack frame to record?
C\C++ binaries created by gcc, MSVC and probably other compilers as well have an entry point_startwhich is part of the library and gets statically linked into the executable. The ELF/PE loader of the operating system sets up a stack for the program to run and upon scheduling, the CPUreturnsto_startwhich then does some library specific setup and callsmain. So upon invocation ofmain, there is a stored return address which goes back to the clib function which then uses a system call to notify the OS to terminate the program. However, as pointed out by the comments, this is not defined by the language standard itself, just the way it is most commonly implemented in existing systems.
If I open a text file withopen("file.txt",O_RDONLY), do I need to close it withclose()? Silly question, I know, but I am not entirely sure if the end of a process leaves open files open.
The file will remain open until you close it or your process terminates. The process terminating will invalidate the file descriptors for that process, and so in essence "close" the files. I would always close them explicitly, and as early as reasonable.
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed7 years ago.Improve this question I tried using the rand() function with min = 4 and max = 10: ``` s = rand() % 10 + 4; ``` and some of the results were above 10.How is this possible?
The solution you look for isrand() % 7 + 4which will give you results from range [4, 10]. More general, for givenminandmaxto obtain random value from [min, max] you go forrand() % (max - min + 1) + min
I have a two-dimensionalintarray allocated as follows: ``` int **matrix = (int**)malloc(x * sizeof(int)); for (i = 0; i < x; i++) matrix[i] = (int*)malloc(y * sizeof(int)); ``` If I doreallocthis array by the following code ``` int **matrix = (int**)realloc(matrix, x * sizeof(int)); for (i = 0; i < x; i++) matrix[i] = (int*)malloc((y) * sizeof(int)); ``` will there be any leftover "tails" of second dimension of the array and should I usefree()function for them before reallocating, or they will go away themselves?
You will completely lose data in yourmatrix, so this is not reallyreallocing anything; you could just as wellfreeandmallocthe top-level array, getting possibly better performance. Furthermore your code would leak memory, because the 2nd level allocations are notfreed.
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I have written a code which includes the Windows.h header, and compiled it using Visual Studio. I have then tried to run the EXE file alone on my other computer, which appears to lack the specified header. How can I run it on the other computer without having to install VS?
Executable file does not need header. It needs for dynamic libraries. They are distrubuted with Visual Studio or with Visual Studio Redistributable Package. You can distribute your program with that package. Another option - using static linking. With static linking executable will have all needed data and code.
I am trying to split up a string into 3 variables of type int,char,int. I have the following string to split 1000P3. I have the following code to do this but the char variable is containg the P3 instead of just the P. ``` int num1; char type [10]; int num2 =0; sscanf("1000P3","%d %c %d",&num1,type,&num2); ``` Any assistance would be grateful.
%creads a single character, not a character string. That you saw 3 was just a coincidence from undefined behaviour. Try ``` int num1; char type; int num2; sscanf("1000P3","%d %c %d", &num1, &type, &num2); ``` And remember to printf the character also with%c. Also you should check the return value ofsscanf; if it is not 3 (as we wanted to parse 3 items), then your input is incorrect.
I'm trying to printf unsigned short in hex, e.g. 0XFFFF. The problem is that I want a lowercase x not X. I have no idea how to do this. ``` fprintf(c,"%#06X,\n\t", pixel[i])); ```
Change the %X specifier to %x and you should get lower case: ``` fprintf(c, "%#06x\n", pixel[i]); ``` Outputs the number as0xffff. If pixel is an array of unsigned shorts and you want the format to match the data, you can do: ``` fprintf(c, "%#06hx\n", pixel[i]); ``` If you really want0xFFFF, then that's trivial: ``` fprintf(c, "0x%04hX\n", pixel[i]); ```
I am writing a helper library for threading in C, based on the pthread API. There are many pthread functions that are nonstandard GNU extensions, such aspthread_set_affinity_np,pthread_clear_exit_np,pthread_set_qos_class_self_np, etc. Is there any way I can use macros to test whether these non portable functions are available without looking up which operating systems define what?
This is exactly the kind of problem that people use Autoconf to solve. Eg a sinppet like this in yourconfigure.acfile: ``` AC_CHECK_DECLS( [pthread_attr_setaffinity_np, pthread_clear_exit_np, pthread_set_qos_class_self_np], [], [], [[#include <pthread.h>]]) ``` will define macrosHAVE_DECL_PTHREAD_ATTR_SETAFFINITY_NP,HAVE_DECL_PTHREAD_CLEAR_EXIT_NPandHAVE_DECL_PTHREAD_SET_QOS_CLASS_SELF_NP, defined to0if the declaration is not present or1if it is.
I want to get a integer from to user. But I wonder what is the difference betweenfscanf(stdin, "%d", &x);andscanf("%d", &x);?
What is the difference between stdin with fscanf and scanf? Thescanffunction is equivalent tofscanfwith the argumentstdininterposed before the arguments toscanf. C11 §7.21.6.4 2 So aside from a different amount of typing the code, they are the same.
I am currently working on a C program where I am trying to pass an pointer as an argument into ascanf. Example: ``` int main() { int *num; scanf("%d", num); printf("%d", *num); } ``` Considering that the typicalscanfpasses in an address to store a value I don't see why it cannot store the address a pointer holds. I receive a memory error when I try to run this block of code. What could possibly be the issue?
You can do that only ifnumpoints to valid memory. ``` // Not OK // Leads to undefined behavior since num does not point // to anything valid. int* num; scanf("%d",num); ``` ``` // OK int* num = malloc(sizeof(*num)); scanf("%d",num); ``` ``` // Also OK int i; int* num = &i; scanf("%d",num); ```
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question I have written a code which includes the Windows.h header, and compiled it using Visual Studio. I have then tried to run the EXE file alone on my other computer, which appears to lack the specified header. How can I run it on the other computer without having to install VS?
Executable file does not need header. It needs for dynamic libraries. They are distrubuted with Visual Studio or with Visual Studio Redistributable Package. You can distribute your program with that package. Another option - using static linking. With static linking executable will have all needed data and code.
I am trying to split up a string into 3 variables of type int,char,int. I have the following string to split 1000P3. I have the following code to do this but the char variable is containg the P3 instead of just the P. ``` int num1; char type [10]; int num2 =0; sscanf("1000P3","%d %c %d",&num1,type,&num2); ``` Any assistance would be grateful.
%creads a single character, not a character string. That you saw 3 was just a coincidence from undefined behaviour. Try ``` int num1; char type; int num2; sscanf("1000P3","%d %c %d", &num1, &type, &num2); ``` And remember to printf the character also with%c. Also you should check the return value ofsscanf; if it is not 3 (as we wanted to parse 3 items), then your input is incorrect.
I was wondering how to access individual elements in the below case: ``` char *three=(char*){'2','5','8','\0'}; ``` If the assignment were like this: ``` char *three="258"; ``` it can be accessed with three[0],three[1].....etc. How to access in the first case? Thanks in advance...
First of allchar *three=(char*){'2','5','8','\0'};is not valid C. To make a compound literal you must do like this: ``` char *three=(char[]){'2','5','8','\0'}; ``` When that is fixed, then there is no difference in how you access the data. In both cases you can use the [] operator to access data, it can be used on any pointer type. Where the pointer points at doesn't matter.
Ada's strings are NOT null terminated like C's. I have a requirement in a C-Ada binding application where I need to pass a string that is allocated in Ada code to a C function. How will C recognize Ada strings in here as strings in C are usually simple char array terminated by a null char while this is not the case in Ada? Any examples would be appreciated!
Expanding on @manuBriot'sanswerto your previousquestionon this topic, note that the convenient wrapperprocedure FoocallsNew_Stringon the incoming AdaStringto obtain achars_ptr. ``` procedure Foo (C : String) is S : Interfaces.C.Strings.chars_ptr := New_String (C); begin … end Foo; ``` Note also thatNew_String"is equivalent toNew_Char_Array(To_C(Str))." When passed an AdaString,To_CsetsAppend_NultoTrueby default. As a result, AdaFoocalls Cfoowith a properlynullterminated C string.
I can list available function names and enumerator names by ``` lib = ffi.dlopen(...) print dir(lib) ``` Howerver, dir(lib) doesn't return defined typedefs and structs. When I tried to load an arbitrary module with an arbitrary c header file using cffi, I had to parse the header file to get the list of typedefs and structs. Is there a better way to do the same thing?
It's not possible so far to enumerate the types. You could file an enhancement request athttps://bitbucket.org/cffi/cffi/issues.
Ada's strings are NOT null terminated like C's. I have a requirement in a C-Ada binding application where I need to pass a string that is allocated in Ada code to a C function. How will C recognize Ada strings in here as strings in C are usually simple char array terminated by a null char while this is not the case in Ada? Any examples would be appreciated!
Expanding on @manuBriot'sanswerto your previousquestionon this topic, note that the convenient wrapperprocedure FoocallsNew_Stringon the incoming AdaStringto obtain achars_ptr. ``` procedure Foo (C : String) is S : Interfaces.C.Strings.chars_ptr := New_String (C); begin … end Foo; ``` Note also thatNew_String"is equivalent toNew_Char_Array(To_C(Str))." When passed an AdaString,To_CsetsAppend_NultoTrueby default. As a result, AdaFoocalls Cfoowith a properlynullterminated C string.
I can list available function names and enumerator names by ``` lib = ffi.dlopen(...) print dir(lib) ``` Howerver, dir(lib) doesn't return defined typedefs and structs. When I tried to load an arbitrary module with an arbitrary c header file using cffi, I had to parse the header file to get the list of typedefs and structs. Is there a better way to do the same thing?
It's not possible so far to enumerate the types. You could file an enhancement request athttps://bitbucket.org/cffi/cffi/issues.
I have an array ``` char msgID[16]; ``` How do I increment this by 1? I read the high and low 8 bytes into 2 differentuint64_tintegers ``` uint64_t high, low; memcpy(&low, msgID, sizeof(uint64_t)); memcpy(&high, msgID + sizeof(uint64_t) , sizeof(uint64_t)); ``` If I do ``` low += 1; ``` How do I account for overflow? Thanks for any help provided.
It's quite simple, actually: ``` if(++low == 0) ++high; ```
If you usegetc()orscanf(), you only know what button the user pressed after he pressed enter. Is there a way to get direct keyboard input in the C language? Also, I'm using gcc on Linux (Raspberry pi).
It is OS specific (the C99 or C11 standard does not know about the keyboard). On Linux (which I am focusing on in my answer) and Unix,terminalsare -for legacy and historical reasons- complex beasts (the kernel is implementing theline discipline), seetty demystifiedpage. For gory details, see alsotermios(3)(the raw and noncanonical modes will give you a headache) &tty(4)&stty(1) (you could spend months in learning the gory details; I forgot most of them) Istronglyrecommend coding with a library such asncursesorreadline(ortermcap, if you are masochistic enough) If using a GUI, better use some toolkit likeQt. To poll a set of file descriptors, usepoll(2). See alsosyscalls(2)andAdvanced Linux Programming.
In C, can local variables of an inline function conflict with local variables from the function in which it is called? For example: ``` inline void func1() { int i; for(i = 0; i < 10; i++){ // Some code } } void func2() { int i; for(i = 0; i < 5; i++) { func1(); } } ``` Would the iterator infunc1conflict with the iterator infunc2?
Theinlinespecifier is mostly just a hint to the compiler. It doesn't make the function any different. The variables declared in the function still have block scope and don't interfere with other variables.
If you usegetc()orscanf(), you only know what button the user pressed after he pressed enter. Is there a way to get direct keyboard input in the C language? Also, I'm using gcc on Linux (Raspberry pi).
It is OS specific (the C99 or C11 standard does not know about the keyboard). On Linux (which I am focusing on in my answer) and Unix,terminalsare -for legacy and historical reasons- complex beasts (the kernel is implementing theline discipline), seetty demystifiedpage. For gory details, see alsotermios(3)(the raw and noncanonical modes will give you a headache) &tty(4)&stty(1) (you could spend months in learning the gory details; I forgot most of them) Istronglyrecommend coding with a library such asncursesorreadline(ortermcap, if you are masochistic enough) If using a GUI, better use some toolkit likeQt. To poll a set of file descriptors, usepoll(2). See alsosyscalls(2)andAdvanced Linux Programming.
In C, can local variables of an inline function conflict with local variables from the function in which it is called? For example: ``` inline void func1() { int i; for(i = 0; i < 10; i++){ // Some code } } void func2() { int i; for(i = 0; i < 5; i++) { func1(); } } ``` Would the iterator infunc1conflict with the iterator infunc2?
Theinlinespecifier is mostly just a hint to the compiler. It doesn't make the function any different. The variables declared in the function still have block scope and don't interfere with other variables.
I have three individual characters,int x,y,z, and want to construct the character which has the octal representation\xyzfrom them. How can I achieve this? I assume I need to use one of the many*printfvariants, but unfortunately my own attempts didn't work and I couldn't find any other question on SO answering this.
``` // 145 octal int x = '1'; int y = '4'; int z = '5'; int octal = (x - '0') * 64 + (y - '0') * 8 + (z - '0'); ``` If you have the value of the digits, do not subtract'0' ``` // 145 octal int x = 1; int y = 4; int z = 5; int octal = x * 64 + y * 8 + z; ```
Since Lua 5.3, inegers are supported. But how can I do : ``` if type( 123 ) == "integer" then end ``` Or ``` switch( lua_type( L, -1 ) ) { case LUA_TINTEGER: break; } ``` Sincetype()is still going to return"number"for both integer and reals, andLUA_TINTEGERdoes not exist ? Thanks.
usemath.typefor Lua 5.3 Returns "integer" if x is an integer, "float" if it is a float, or nil if x is not a number.
I want ask some questions 1) I want get string yyyymmdd of system date using linux c how should I do it ? And I want use this string do some arithmetic, like I have "20160317" I want do 20160317 - 90 get a new date,pls help 2) ``` int n; int m; n = (m%10 = 0)?(m/10):(m/10+1); ``` is there some cleaner way to do this? like if m = 11 n will get 2, m = 10 n will get 1.
You can convert from a string to a time structure usingstrptime(Linux only). This will set the time on a tm struct that is passed to it. You can then use thectimelibrary. It will let you usedifftimewhich will give you get the difference between two times.
This question already has answers here:Shouldn't an int pointer in Turbo C be of size 4 bytes?(5 answers)Closed7 years ago. I have created a node in C using the struct: ``` struct node{ int data; struct node* left; struct node* right; } ``` Now i am calculating the size of the node using the following code ``` printf("%d", size of(struct node)); ``` The output is 6, I am using the Turbo c++ compiler. Kindly clear me why the size of node is 6?
"Classic" Turbo C++ targets 16 bit DOS (later versions support 16 bit Windows), so near pointers andintare 2 bytes each; being them all the same, no padding is required for alignment, and the total size amounts to the plain sum of its elements (2+2+2=6 bytes). The fact that such pointers point to othernodestructures doesn't affect their size (why should it?).
I code in C and I am little weak in C++, in my research I came across many methods to read XML from URL for my win32 application. I found cURL andXmlTextReaderbut it's in C++. Is there any function or other ways, where I can download XML from the URL and parse that XML using only C language and not C++? I can work with C++ as well, but I want to avoid it as it's not I am comfortable with.
Libcurlhas pure C API.Expatandlibxmlare written in pure C too.
I just came through the following statement: ``` printf("%d days total: %.1f%% were below freezing.\n",all_days, 100.0 * (float) cold_days / all_days); ``` I need an explanation over using(float)insideprintfexpression in the above statement. If you have any reference please link it.
It is also worth noting that this cast is likelyunneccesary.100.0 * (float) cold_days / all_dayswill be executed left to right, and since100.0is already floating-point number (double), result of100.0 * cold_dayswill also bedouble. And sincefloatis upgraded todoublefor printf (as well as any other variadic argument function), the cast is redundant.
I stumbled upon this weird behaviour when compiling C programs usinggcc. Let's say we have these two simple source files: fun.c ``` #include <stdio.h> // int var = 10; Results in Gcc compiler error if global variable is initialized int var; void fun(void) { printf("Fun: %d\n", var); } ``` main.c ``` #include <stdio.h> int var = 10; int main(void) { fun(); printf("Main: %d\n", var); } ``` Surprisingly, when compiled asgcc main.c fun.c -o main.outthis doesn't producemultiple definition linker error. One would expectmultiple definition linker errorto occur just the same, regardless of global variable initialization. Does it mean that compiler makes uninitialized global variables extern by default?
A global variable can have any number ofdeclarations, but only onedefinition. An initializer makes it a definition, so it will complain about having two of those (even if they agree).
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed7 years ago.Improve this question For Example: ``` #define MY_TEST_FUNCTION #ifdef MY_TEST_FUNCTION void __MACRO_NAME##_TEST (void *) { } #endif ``` This should produce: ``` #ifdef MY_TEST_FUNCTION void MY_TEST_FUNCTION_TEST (void *) { } #endif ``` This is something likefunc, where we get the function name inside a function. Is this possible?
There is no such placeholder defined in the language standard. Youknowthe macro you just checked, though, so I do not see how such a placeholder would be useful even if it existed. Also consider... ``` #if defined( FOO ) || defined( BAR ) ``` ...what should the "context" be named as?
This question already has answers here:What is the purpose of a zero length array in a struct? [duplicate](2 answers)Closed7 years ago. I have an array of zero cell and i want to dispay his size. my code is: ``` #include <stdio.h> #include <string.h> #include <stdint.h> typedef struct ts_ff { uint8_t reserved[0]; } TS_fact; int main(void) { TS_fact ts_factory; printf("size of reserved is %zu Bytes\n",sizeof(ts_factory)); return 0; } ``` But the return of this code return 0 Bytes not 1 Byte for this array cell. ``` size of reserved is 0 Bytes ``` Why the compiler do this ?
uint8_t reserved[0];It is an array of size0 so the sizeof will be zero.
I would like to know how Lua handles the number to string conversions using thetostring()function. It is going to convert to an int (as string) if the number is round (i.e ifnumber == (int) number) or is it always going to output a real (as string) like10.0? I need to mimic the exact behaviour of Lua'stostringin C, without using the Lua C API since, in this case, I'm not using alua_State.
In Lua 5.2 or earlier, bothtostring(10)andtostring(10.0)result as the string"10". In Lua 5.3, this has changed: ``` print(tostring(10)) -- "10" print(tostring(10.0)) -- "10.0" ``` That's because Lua 5.3 introduced the integer subtype. FromChanges in the Language: The conversion of a float to a string now adds a.0suffix to the result if it looks like an integer. (For instance, the float2.0will be printed as2.0, not as2.) You should always use an explicit format when you need a specific format for numbers.
I'm very new at C and I'm having a problem using functionstrstr. Make gives me a warning that I do not understand, anybody can explain ? warning:comparison between pointer and integer (char *andint)if (strstr(reference, number_start) == 1)warning generated. My code: ``` #include <stdio.h> #include <string.h> int main (void) { char reference[] = "34,37"; char number[] = "34567890123456"; char number_start[] = {number[0], number[1], '\0'}; if (strstr(reference, number_start) == 1) { printf("Yup, iit's workin'\n"); } else { printf("Try again, wookie\n"); } return 0; } ```
strstr()return a pointer to the first substring if found, andNULLif not found. Replace ``` if (strstr(reference, number_start) == 1) { ``` with ``` if (strstr(reference, number_start) != NULL) { ``` to check ifnumber_startis inreference.
I'll need to store keywords in my C project. Now I'd have to write ``` const char firstThingKeyword[] = "foofoofoofoo" const char secondThingKeyword[] = "barbarbarbar" ``` The names are long, so I'd rather reference them ``` keywords.firstThing ``` Is there any way to do this in plain C? (possibly GCC extension) I thought about using a struct, but I have trouble doing anything with it, having left the C++ comfort zone.
Here's a quick example of how to accomplish this using astruct: ``` #include <stdio.h> #include <stdlib.h> struct _keywords { const char *first; const char *second; }; const struct _keywords Keywords = { .first = "AAA", .second = "BBB" }; int main(void) { printf("first: %s\n", Keywords.first); printf("second: %s\n", Keywords.second); return 0; } ```
I successfully run my code in small data but when i tried large scaled data, it gives me "corrupted double-linked list:" In small data, if I delete free() functions, error is disappeared and code works, but in large data whether i put free or not, code gives this error. Creation of malloc and using free in my code as follows, ``` int **msgcount = malloc(partnum*sizeof(int*)); for(i=0; i<partnum; i++) msgcount[i] = malloc( partnum*sizeof(int)); ...lots of code for(i=0;i<partnum;i++) { free(msgcount[i]); } ```
This message comes from glibc and means that you faced a memory corruption or you doubly freed the same pointer. Try to run under valgrind and find where's the corruption occurred.
``` struct store { ... struct item { ... }it[]; struct employee { ... }e[]; }s[]; ``` Here I want to know how many items was stored after gets input for structure item
C doesn't have a concept of "array size" for a non-bounded array. In fact, its concept of arrays is shaky at best. The two options that are generally used are: Have a "length" attribute stored alongside the arrayZero-terminate the array, i.e. the pointer after the last element is zero For your case, I'd recommend the first of the two: ``` struct mydatastruct { int store_length; struct store { ... int item_length; struct item { ... } it[]; int employee_length; struct employee { ... } e[]; } s[]; } mystruct; ```
This is the code ``` #include<stdio.h> int main() { int a=1; switch(a) { case 1: printf("Case A"); default: printf("Default"); } } ``` Output: Case A Default Why is it printing even the Default case?
There is no break statement aftercase 1therefore control goes to executedefaultstatement. ``` switch(a) { case 1: printf("Case A"); break; default: printf("Default"); } ```
``` int i1 = 0, i2 = 0; float f = 2.8f; i1 += f; i2 += (int)f; f += 0.1; i1 += f; i2 += (int)f; f += 0.1; i1 += f; i2 += (int)f; printf("%d %d\n", i1, i2); ``` Output: ``` 7 6 ``` Why would implicit and explicit conversion results be different?I would like results to be like the ones for implicit conversion, but without compilation warning. Is it possible? Platform is Windows7, VS2010 or 2013.
To analyse this, the first job is to rewritea += basa = a + b. i + (int)fwill be computed in integer arithmetic due to the explicit cast. Buti + fwill be computed in floating point arithmetic due totype promotion. So the expressions have different types. Due to the way floating point works, the result, when converted back to anintcoulddiffer. The moral of the story is tonotuse+=for mixed types, and to not ignore helpful compiler warnings.
I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried: ``` char test[256] = {'N'}; ``` But this only initializes the first index to'N'and the rest to 0.
Usememset: ``` #include <string.h> char test[256]; memset(test, 'N', 256); ```
``` #include<conio.h> #include<stdio.h> main() { printf(" %d %f ",4.0,4.0); getch(); } ``` I am getting output as04.000000I want to know why4.0becomezeroas the integer specifier is used ? Why it is not truncated to4?
To convince your self try the following. There are few things to notice - implicit conversion of float to int, parameter access by printf() from stack, which determines the memory locations and size to obtain the value stored based on the format specifier. ``` printf(" %d %f ", (int)4.0, 4.0); printf(" %d %f ", (float)4, 4.0); printf(" %d %f ", (float)0, 4.0); ```
I have two header files that should use typedefs of each other. Here is the situation: For example: In header fileserver.h ``` typedef struct { int myint; }ServerSelfData; typedef struct { ServerSelfData servData; ClientSelfData clData; }SERVER_Data; ``` Into the second header file calledclient.hwe have: ``` typedef struct { int myint; }ClientSelfData; typedef struct { ClientSelfData clData; ServerSelfData servData; }CLIENT_Data; ``` So during the compilation there will be error in one of these definitions. In which one depends on which file is included first. Is there any workaround/solution of this problem?
Before these header files, you can declare the structs. Later complete the struct with a name. ``` typedef struct ServerSelfData ServerSelfData; typedef struct CLIENT_Data CLIENT_Data; typedef struct ServerSelfData { int myint; }ServerSelfData; ```
I am making something similar tocommit login database system. The system is able to handle ~ 20,000 events / sec. Each event occupies ~16 bytes. Roughly, the system will write tocommit logat a speed of ~312.5 kB / sec. Eachcommit logfile will contain at most of 500,000 events. I have a question that: Should I callfopen - fwrite - fclosefor each event, OR should I callfopenonce when creating a new file, then a series offwriteand finallyfclose?
In such cases, it might be even better to revert toopen/write/closeand get rid of C buffered output completely. Log files are typically consisting of a high volume of nearly identical (size-wise) writes and do not really gain much from C buffering. Low level, unbuffered I/O would also relieve you of calling fflush() and can guarantee to write every single log entry as atomic entity. Given the volume you mentioned, you should probablystillnot close and re-open the file between writes.
I thought this would be easy, but google searching isn't turning up what I'm looking for. In C, how do I initialize an entire char array to a particular char, say,'N'? This is what I tried: ``` char test[256] = {'N'}; ``` But this only initializes the first index to'N'and the rest to 0.
Usememset: ``` #include <string.h> char test[256]; memset(test, 'N', 256); ```
``` #include<conio.h> #include<stdio.h> main() { printf(" %d %f ",4.0,4.0); getch(); } ``` I am getting output as04.000000I want to know why4.0becomezeroas the integer specifier is used ? Why it is not truncated to4?
To convince your self try the following. There are few things to notice - implicit conversion of float to int, parameter access by printf() from stack, which determines the memory locations and size to obtain the value stored based on the format specifier. ``` printf(" %d %f ", (int)4.0, 4.0); printf(" %d %f ", (float)4, 4.0); printf(" %d %f ", (float)0, 4.0); ```
I'm writing a program in C. Due to the language's static typing, Its necessary to duplicate functions in the following way: ``` void foo_8(uint8_t thingy); void foo_16(uint16_t thingy); void foo_32(uint32_t thingy); ``` When it comes to doxygen comments, you're forced to copy-paste the same comment block several times. Does doxygen have facilities/tags to say "This function is the same as another focuntion"?
You can usecopydoc,copybrieforcopydetails: ``` \copydoc foo_8() ``` or ``` \brief \copybrief foo_8() \details \copydetails foo_8() ```
I got a question, at school we compile C with this command : ``` clang -o filename -O0 -g -std=c99 -Wall -Wextra filename.c ``` and I'd like to make an alias such asclang-cwhich contains all these options I tried alsoclang-c='clang -O0 -g -std=c99 -Wall -Wextra'but impossible like this to set the name of the output file.. Do you have any idea ?
I give you a Makefile example: ``` INCPATH = includes/ CC = gcc CFLAGS = -I $(INCPATH) -Wall -Wextra -pedantic -fPIC -O2 LDFLAGS = -shared TARGET = libmy_malloc_$(HOSTTYPE).so LINK_NAME = libmy_malloc.so SRC = malloc.c internal.c OBJ = $(SRC:.c=.o) RM = rm -vf LN = ln all: $(TARGET) $(TARGET): $(OBJ) $(CC) $(CFLAGS) -o $(TARGET) $(OBJ) $(LDFLAGS) $(LN) -s $(TARGET) $(LINK_NAME) clean: $(RM) $(OBJ) fclean: clean $(RM) $(TARGET) $(LINK_NAME) re: fclean all ``` You can set all of your flag on theCFLAGSline!
In C, If I have: ``` char *reg = "[R5]"; ``` and I want char *reg_alt = "R5"(equal to the same thing, but without the brackets), how do I do this? I tried ``` *char reg_alt = reg[1:2]; ``` but this doesn't work.
There is no built-in syntax for dealing with substrings like that, so you need to copy the content manually: ``` char res[3]; memcpy(res, &reg[1], 2); res[2] = '\0'; ```
From the custom memory allocator for malloc, consider this two macros: ``` #define GET_HDR(bp) (*(int *)((int *)(bp) – 1)) #define GET_HDR(bp) (*(int *)((char **)(bp) – 1)) ``` Herebpis avoidpointer. GET_HDR(bp)is used to get the content of theHEADERwhich is a 4-byte block stored just before void pointerbp. Here the 1st macro takes void pointerbp, typecasts it into int and subtract 1 to take pointer 4-bytes back so that it points to theHEADERblock and then dereference the pointer to give value ofHEADERblock. But how does the 2nd macro do it? How pointer are manipulated to reachHEADERblock?
The macro likely assumes the size of achar *is the same as anint. ``` ( *(int *)( /* Treat result as pointer to int and dereference */ (char **)(bp) /* bp is cast to a pointer to (char *) */ – 1 /* take bp back sizeof(char *) bytes (presumably also 4) */ ) ) ```
Why I shouldn't add a null character to the end of a non null-terminated string like in thisanswer? I mean if I have a non null-terminated string and add null character to the end of the string, I now have a null-terminated string which should be good, right? Is there any security problem I don't see? Here's the code in case the answer gets deleted: ``` char letters[SIZE + 1]; // Leave room for the null-terminator. // ... // Populate letters[]. // ... letters[SIZE] = '\0'; // Null-terminate the array. ```
to know the end of the string you must have a null terminated string, otherwise there is no way to know the end of the string
How do you advance the pointer position for a file without actually reading them. I ran into the situation in which I needed to discard the first X bytes in the file and then start reading. (In case, you are curious, WAV file discard the header of 44 bytes). I ended up reading them just to advance the pointer. ``` int input_fd; input_fd = open("sample.wav", O_RDONLY); assert(input_fd !=-1 ); int dummy[44]; read(input_fd,dummy,44); ``` Is there a less expensive way of doing this?
You can uselseek()system call. ``` lseek(input_fd, 44, SEEK_CUR); ```
``` int r = 50; int *p; int **k; int ***m; printf( "r: %d ", r ); p = &r; k = &p; m = &k; ***m = 100; //line 9 printf( "r: %d\n", r ); ``` When there is only one pointer, I can understand that we take 100 and we assign it to the variable at the address which is being held by the pointer. But what exactly is happening step by step when we do this with more than one pointer level? (line 9)
int *p=&r:pis apointer-to-int, and it takes theaddress of r. int **k=&p:kis apointer-to-( pointer-to-int ), and it takes theaddress of p. int ***m=&k:mis apointer-to-( pointer-to-( pointer-to-int ) ), and it takes theaddress of k. When you do***m = 100, you are "unwrapping" the pointers, and finally you end up with justint.
I want to create a button with a down arrow icon that displays a menu when clicked. I have found the following button type: But this button can be pressed in two places (on the left of the vertical line and on the right of the vertical line), also I don't want the button to have a vertical line, I want it to be something like this: Can this be done in Windows API?
What you are looking for can be done using either: a standardCOMBOBOX controlwith theCBS_DROPDOWNLISTwindow style: (source:s-msft.com) AMenu button: (source:s-msft.com) However, this is not a standard Win32 control. MFC has aCMFCMenuButtonclass for it, but in Win32 you have to owner-draw a standardBUTTON controlto achieve the same effect: Menu button arrow with raw Win32 When the button is pushed, you can display your pop-up menu as needed, usingTrackPopupMenu()or equivalent.
I implemented a blurring algorithm and it works. The result is a blurred image but if a pass multiple times the algorithm to my image the image remains unchanged. It's like the extra (more than 1) passings are not having any effect. ``` for (f=0; f<100; f++) { for (y = 0; y < image->h; y++) { for (x = 0; x < image->w; x++) { int SUM = 0; imageBlur->pixels[y * imageBlur->w + x] = SUM / 9; } } } ``` It doesn't matter if f is 1 or 500 it's still the same result as one pass blur.
Each pass you are reading the sameimageagain without having replaced it with the blurred one:imageBlurYou need to do the assignment somehow - some thing like ``` image->pixels[y * imageBlur->w + x] = SUM / 9; ```
Why I shouldn't add a null character to the end of a non null-terminated string like in thisanswer? I mean if I have a non null-terminated string and add null character to the end of the string, I now have a null-terminated string which should be good, right? Is there any security problem I don't see? Here's the code in case the answer gets deleted: ``` char letters[SIZE + 1]; // Leave room for the null-terminator. // ... // Populate letters[]. // ... letters[SIZE] = '\0'; // Null-terminate the array. ```
to know the end of the string you must have a null terminated string, otherwise there is no way to know the end of the string
I try to run this code: ``` #include <stdio.h> int main() { char str1[20], str2[30]; printf("Enter name: "); scanf("%s", str1); getc(stdin); printf("Enter your website name: "); scanf("%s", str2); getc(stdin); printf("Entered Name: %s\n", str1); printf("Entered Website:%s", str2); return(0); } ``` fromhttp://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm so I expected to get this in the console: ``` Enter name: admin Enter your website name: admin.com Entered Name: admin Entered Website: admin.com ``` but actually I got this in my console: ``` admin admin.com Enter name: Enter your website name: Entered Name: admin Entered Website:admin.com ``` so I would like to know why the scanf executed before the print. maybe its related to using eclipse as IDE?
Try addingfflush(stdout);between your printf and scanf.
I have a char array contains string separated by null. I have the indexes for the strings present in the char aarray. How to read string from this char array using index and are separated by null. e.g. I have following char array, ``` char *buf = ['\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0']; ``` I have the indexes for these strings e.g index 1 forbcsstring index 5 fornewstring index 9 fornxtstring How read these string using index from this char array?
Sorry for the simple question, I got the answer, We can get string from char array as follows: - Get the address of index of which string you want to get - Print the string ``` char* str = &buf[index]; if(str) printf("string is : %s\n", str); ```
I've got this code: ``` char level; printf("Please choose a level!\nEasy\nMedium\nHard\n\n"); scanf("%s", &level); do{ if((level=="easy") || (level=="Easy")) { printf("You have choosen the easy level, so you have 2 powerups per time. If you want to use them, please type P or p!\n"); break; } ``` and this warning:17 15 C:\Users\katerina\Desktop\levels.c [Warning] comparison between pointer and integer What can I do?
In C, there is no string comparison operator==. You have to use thestrncmpfunction: ``` if (strncmp("easy", level, 4) == 0) { } ``` Also, your variablelevelis incorrectly defined. It should be achar *(don't forget to allocate memory) orchar[].
I don't know why my approach does not work for the given problem. Here is the code: ``` void last_to_n(struct node*head,int n) { struct node *temp = head; struct node *temp2 = head; int len1=0,len2=0; while(temp!=NULL) { len1++; temp=temp->next; } while(temp2!=NULL) { if(len2==len1-n+1)printf("%d",temp2->data); else { len2++; temp2=temp2->next; } } } ``` Is anything wrong with the code?
You should put break in 2nd while loop, otherwise it won't terminate and will lead to a crash.if(len2==len1-n+1)condition is wrong. It should beif(len2==len1-n).
This question already has answers here:In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*?(5 answers)Closed7 years ago. How cancharpointer be initialized with a string (Array of characters) but anintpointer not with a array of integer? When I tried this ``` int* a={1,2,3,4,5}; ``` It gives an error saying error: scalar object ‘a’ requires one element in initializer But, ``` char* name="mikhil" ``` works perfectly.
Because these are the rules (standards) of the language. There's nothing telling you it's possible to initialize a pointer with an array like this, for example, the following is also illegal: ``` char* name={'m', 'i', 'k', 'h', 'i', 'l', 0}; ``` A literal string gets its own treatment and is not defined just as an array of characters.
I'm mallocing a string ``` int main(){ int buf = 1024; char *input = malloc(sizeof(char*) * buf); //CODE scanf("%s", input); //MORE CODE free(input); } ``` If I don't set the input string to anything it works however, it crashes when its set to something. ``` malloc: *** error for object 0x100f01efa: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Abort trap: 6 ``` I think I'm doing it correctly but not really sure why it crashes.
You need tomalloccharacters not character pointers. i.e. change ``` sizeof(char*) ``` to ``` 1 ``` Or just put ``` char *input = malloc(buf); ```
Is there a way to read user input until the ESC key(or any other key) is pressed? I've seen forums about it but they've all been for C++. I need to make one that works for C. Thanks
Let's check 'esc' character in ascii table: ``` $ man ascii | grep -i ESC 033 27 1B ESC (escape) $ ``` Therefore, it's ascii value is: '033' - Octal Value'27' - Integer Value'1B' - Hexadecimal Value'ESC' - Character Value Asample programusing integer value of 'ESC': ``` #include <stdio.h> int main (void) { int c; while (1) { c = getchar(); // Get one character from the input if (c == 27) { break; } // Exit the loop if we receive ESC putchar(c); // Put the character to the output } return 0; } ``` Hope that helps!
I am currently creating threads and I would like to print out the "thread number" of each thread I make. For example: ``` void* thread_function(void* arg){ printf("This is thread # %d\n", *(int*)arg); return NULL; } pthread_t id; int main() for(int i = 0; i< 5; i++){ pthread_create(&id, NULL, thread_function, &i); } //do some other stuff return 0; } ``` So basically, for the first thread, I want it to say: ``` This is thread # 0 ``` However, for some reason it gives me random numbers like ``` This is thread # -56465645645 ``` How do I fix this problem?
You pasedpointer toithat will vanish after exiting theforloop instead ofvalue ofi. Try using(void*)iinstead of&iin functionmain()and passing(int)arginstead of*(int*)argin functionthread_function(). (conversion between pointers and intergers is implementation-defined)
In this struct I want to initialize an array but Visual Studio marks an error right afterrulesRefIndex[3] expected a ';' ``` struct Fact{ char name[4]; char value[6]; int rulesRefIndex[3] = { -1 }; }; ``` Error occurs even withint rulesRefIndex[3] = { -1,-1,-1 };andint rulesRefIndex[3] = {[0...3]= -1 };as statedhere. What am I doing wrong?
You can initialize only when defining a variable, not when defining a structure(datatype) in c. Check the following post for details. Why can't we initialize members inside a structure? Moreover your question is related to partial initialization. Please check this post. C and C++ : Partial initialization of automatic structure
I try to run this code: ``` #include <stdio.h> int main() { char str1[20], str2[30]; printf("Enter name: "); scanf("%s", str1); getc(stdin); printf("Enter your website name: "); scanf("%s", str2); getc(stdin); printf("Entered Name: %s\n", str1); printf("Entered Website:%s", str2); return(0); } ``` fromhttp://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm so I expected to get this in the console: ``` Enter name: admin Enter your website name: admin.com Entered Name: admin Entered Website: admin.com ``` but actually I got this in my console: ``` admin admin.com Enter name: Enter your website name: Entered Name: admin Entered Website:admin.com ``` so I would like to know why the scanf executed before the print. maybe its related to using eclipse as IDE?
Try addingfflush(stdout);between your printf and scanf.
I have a char array contains string separated by null. I have the indexes for the strings present in the char aarray. How to read string from this char array using index and are separated by null. e.g. I have following char array, ``` char *buf = ['\0', 'b', 'c', 's', '\0', 'n', 'e', 'w', '\0', 'n', 'x', 't', '\0']; ``` I have the indexes for these strings e.g index 1 forbcsstring index 5 fornewstring index 9 fornxtstring How read these string using index from this char array?
Sorry for the simple question, I got the answer, We can get string from char array as follows: - Get the address of index of which string you want to get - Print the string ``` char* str = &buf[index]; if(str) printf("string is : %s\n", str); ```
I've got this code: ``` char level; printf("Please choose a level!\nEasy\nMedium\nHard\n\n"); scanf("%s", &level); do{ if((level=="easy") || (level=="Easy")) { printf("You have choosen the easy level, so you have 2 powerups per time. If you want to use them, please type P or p!\n"); break; } ``` and this warning:17 15 C:\Users\katerina\Desktop\levels.c [Warning] comparison between pointer and integer What can I do?
In C, there is no string comparison operator==. You have to use thestrncmpfunction: ``` if (strncmp("easy", level, 4) == 0) { } ``` Also, your variablelevelis incorrectly defined. It should be achar *(don't forget to allocate memory) orchar[].
I don't know why my approach does not work for the given problem. Here is the code: ``` void last_to_n(struct node*head,int n) { struct node *temp = head; struct node *temp2 = head; int len1=0,len2=0; while(temp!=NULL) { len1++; temp=temp->next; } while(temp2!=NULL) { if(len2==len1-n+1)printf("%d",temp2->data); else { len2++; temp2=temp2->next; } } } ``` Is anything wrong with the code?
You should put break in 2nd while loop, otherwise it won't terminate and will lead to a crash.if(len2==len1-n+1)condition is wrong. It should beif(len2==len1-n).
This question already has answers here:In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*?(5 answers)Closed7 years ago. How cancharpointer be initialized with a string (Array of characters) but anintpointer not with a array of integer? When I tried this ``` int* a={1,2,3,4,5}; ``` It gives an error saying error: scalar object ‘a’ requires one element in initializer But, ``` char* name="mikhil" ``` works perfectly.
Because these are the rules (standards) of the language. There's nothing telling you it's possible to initialize a pointer with an array like this, for example, the following is also illegal: ``` char* name={'m', 'i', 'k', 'h', 'i', 'l', 0}; ``` A literal string gets its own treatment and is not defined just as an array of characters.
I'm mallocing a string ``` int main(){ int buf = 1024; char *input = malloc(sizeof(char*) * buf); //CODE scanf("%s", input); //MORE CODE free(input); } ``` If I don't set the input string to anything it works however, it crashes when its set to something. ``` malloc: *** error for object 0x100f01efa: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Abort trap: 6 ``` I think I'm doing it correctly but not really sure why it crashes.
You need tomalloccharacters not character pointers. i.e. change ``` sizeof(char*) ``` to ``` 1 ``` Or just put ``` char *input = malloc(buf); ```
Is there a way to read user input until the ESC key(or any other key) is pressed? I've seen forums about it but they've all been for C++. I need to make one that works for C. Thanks
Let's check 'esc' character in ascii table: ``` $ man ascii | grep -i ESC 033 27 1B ESC (escape) $ ``` Therefore, it's ascii value is: '033' - Octal Value'27' - Integer Value'1B' - Hexadecimal Value'ESC' - Character Value Asample programusing integer value of 'ESC': ``` #include <stdio.h> int main (void) { int c; while (1) { c = getchar(); // Get one character from the input if (c == 27) { break; } // Exit the loop if we receive ESC putchar(c); // Put the character to the output } return 0; } ``` Hope that helps!
I am currently creating threads and I would like to print out the "thread number" of each thread I make. For example: ``` void* thread_function(void* arg){ printf("This is thread # %d\n", *(int*)arg); return NULL; } pthread_t id; int main() for(int i = 0; i< 5; i++){ pthread_create(&id, NULL, thread_function, &i); } //do some other stuff return 0; } ``` So basically, for the first thread, I want it to say: ``` This is thread # 0 ``` However, for some reason it gives me random numbers like ``` This is thread # -56465645645 ``` How do I fix this problem?
You pasedpointer toithat will vanish after exiting theforloop instead ofvalue ofi. Try using(void*)iinstead of&iin functionmain()and passing(int)arginstead of*(int*)argin functionthread_function(). (conversion between pointers and intergers is implementation-defined)
In this struct I want to initialize an array but Visual Studio marks an error right afterrulesRefIndex[3] expected a ';' ``` struct Fact{ char name[4]; char value[6]; int rulesRefIndex[3] = { -1 }; }; ``` Error occurs even withint rulesRefIndex[3] = { -1,-1,-1 };andint rulesRefIndex[3] = {[0...3]= -1 };as statedhere. What am I doing wrong?
You can initialize only when defining a variable, not when defining a structure(datatype) in c. Check the following post for details. Why can't we initialize members inside a structure? Moreover your question is related to partial initialization. Please check this post. C and C++ : Partial initialization of automatic structure
In the following code when the function print_uart transfer the string "Hello world" whats exactly received in *s?Is it the character H or the address of the memory where the string "Hello World" is stored?? ``` volatile unsigned int * const UART0DR = (unsigned int *)0x101f1000; void print_uart0(const char *s) { while(*s != '\0') { /* Loop until end of string */ *UART0DR = (unsigned int)(*s); /* Transmit char */ s++; /* Next char */ } } void c_entry() { print_uart0("Hello world!\n"); } ```
sis a pointer to the memory where the string "Hello World" is stored.*sis the first character,'H'.
i am trying to get all the tokens in my input string ``` #include <stdio.h> #include <unistd.h> #define MAX_LINE 80 int main(void) { char *args[MAX_LINE/2+1]; char *tokens[MAX_LINE/2+1]; int should_run = 1; char *split; int i = 0; int concurrent = 0; printf("osh>"); fflush(stdout); scanf("%s", args); split = strtok(args," "); while(split!=NULL) { printf(split); tokens[i]=strdup(split); split = strtok(NULL, " "); i++; } } ``` why does the above code not print all of the tokens in my string for example if my input is "ls -l &" it only prints ls? Thanks for your time
The problem is with linescanf("%s", args);. It reads string up to whitespace. You can instead usescanf("%[^\n]", args);. And also changechar* args[MAX_LINE/2+1];tochar args[MAX_LINE/2+1];
The people over atcplusplus.comgive the reference for printf as so:printf("%[flags][width][.precision][length]specifier", "Message");but if I wanted to to prepend some spaces, I would have to use%[number of spaces]s, "" ...etcis there a clearer way to prepend spaces, without clunkily prepending empty strings?
Use*to specify the total width. No prepended empty strings. ``` const char *message = "Message"; int number_of_spaces = 3; int width = number_of_spaces + strlen(message); printf("<%*s>\n", width, message); ``` Output ``` < Message> ```
I need to import readline.h library to Windows. I have already tried to import folder with libraries here: C:\Qt\Tools\mingw492_32\i686-w64-mingw32\include It is a library with history.h, chardefs.h, keymaps.h, readline.h, etc.. But when i try to compile program like this: ``` if ((line= readline("my_prompt$ ")) == NULL) exit(0); add_history(line); ``` I recieve this message: ``` error: undefined reference to `add_history' error: undefined reference to `impl__readline' ``` I really need it to run that library on my machine. Thanks you very much for helping!
You need to add the library path to your .pro file (notyour Makefile - this will be rewritten everytime you change anything in your project configuration): ``` LIBS += -lreadline ```
``` #include <stdio.h> int main(int argc, const char * argv[]) { int *pi = NULL; void *voidptr = pi; int num = 100; pi = &num; printf("%p\n",pi); printf("%p\n", voidptr); return 0; } ``` Why would second printf give 0x0 but not same address as first ?
Because assignment to one object won't affect another object in C andvoidptrisn't updated sincepi, whose value isNULLat that time, is assigned to it. By the way, you invokedundefined behaviorby passing data having wrong type toprintf(): You passedint*while%pexpectsvoid*.
I need to copy a file (the name of the file is entered via the keyboard) inside a folder (called backup) using execpl ``` printf("File name to copy? "); scanf(" %99[^\n]", str); char *args[] = { "cp", str,"/backup" }; p = fork(); // Fork validations + Dad wait for child execlp(args[0],args[0], args[1], args[2], NULL); exit(1); ```
The first argument toexeclpis the command to run, and the arguments that follow are the command line arguments to the command. The first of these arguments is always the program being run. So you need to duplicate the first element in the array: ``` execlp(args[0], args[0], args[1], args[2], NULL); ```
Why does the (admittedly esoteric) pointer manipulation below cause the following error: *** Error in /home/ubuntu/workspace/Project 3/Debug/Project 3': double free or corruption (out): 0x00007fffffffd7c0 *** ``` int *intPointer = malloc(sizeof(int)); *intPointer = 1; int intArray[] = { *intPointer }; int *intPointer2 = &intArray[0]; free(intPointer2); ```
The value assigned tointPointer2is a pointer to the first element inintArray. This array was allocated on the stack, so attempting tofreeit isundefined behavior. You can onlyfreememory that was returned bymalloc/realloc/calloc. The fact that the first (and only) element in this array contains a copy ofthe value pointed to byintPointer(not a copy of the value ofintPointer) doesn't matter. Only callingfree(intPointer)would work.
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed7 years ago. i wanted to find someone that can explain this to me. I have this program: ``` int main(int argc, char *argv[]){ printf("P "); if(fork()==0) printf("C "); return 0; } ``` The result of this program is: P P C What's the reason for that second "P" ?
IO buffering is the reason.printfis not printing the text right away, but waiting for newline,fflushor the end of the program to actually print it. But the buffer for the "future-to-print" text is in the memory that is getting duplicated byfork, so both processes receive it. And in the end both are printing it.
I have two openmpi programs which I start like this ``` mpirun -n 4 ./prog1 : -n 2 ./prog2 ``` Now how do I useMPI_Comm_size(MPI_COMM_WORLD, &size)such that i get size values as ``` prog1 size=4 prog2 size=2. ``` As of now I get "6" in both programs.
I know the question is outdated but I wanted to add to the answer by Hristo Lliev to make it work not just for OpenMPI: you can use the value of an MPI parameter MPI_APPNUM which will be different for each executable as "color" and split the MPI_COMM_WORLD into separate communicators, then print the size of those sub-communicators. Use MPI_Comm_get_attr(MPI_COMM_WORLD, MPI_APPNUM, &val, &flag ); to get the value of MPI_APPNUM.
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 can leave a comment to explain where the question may be able to be answered.Closed7 years ago.Improve this question I know how to do it to a remote server, it would be like: ``` telnet www.esqsoft.globalservers.com 80 ``` But I don't know to a local server (written in C).
Simply substitute the hostname into the url, for example for a computer on your network with the hostname "LivingRoom", use the commandtelnet LivingRoom 80. For a server on own computer, simply usetelnet localhost 80.
``` #include <stdio.h> int main(int argc, const char * argv[]) { int *pi = NULL; void *voidptr = pi; int num = 100; pi = &num; printf("%p\n",pi); printf("%p\n", voidptr); return 0; } ``` Why would second printf give 0x0 but not same address as first ?
Because assignment to one object won't affect another object in C andvoidptrisn't updated sincepi, whose value isNULLat that time, is assigned to it. By the way, you invokedundefined behaviorby passing data having wrong type toprintf(): You passedint*while%pexpectsvoid*.
I need to copy a file (the name of the file is entered via the keyboard) inside a folder (called backup) using execpl ``` printf("File name to copy? "); scanf(" %99[^\n]", str); char *args[] = { "cp", str,"/backup" }; p = fork(); // Fork validations + Dad wait for child execlp(args[0],args[0], args[1], args[2], NULL); exit(1); ```
The first argument toexeclpis the command to run, and the arguments that follow are the command line arguments to the command. The first of these arguments is always the program being run. So you need to duplicate the first element in the array: ``` execlp(args[0], args[0], args[1], args[2], NULL); ```
Why does the (admittedly esoteric) pointer manipulation below cause the following error: *** Error in /home/ubuntu/workspace/Project 3/Debug/Project 3': double free or corruption (out): 0x00007fffffffd7c0 *** ``` int *intPointer = malloc(sizeof(int)); *intPointer = 1; int intArray[] = { *intPointer }; int *intPointer2 = &intArray[0]; free(intPointer2); ```
The value assigned tointPointer2is a pointer to the first element inintArray. This array was allocated on the stack, so attempting tofreeit isundefined behavior. You can onlyfreememory that was returned bymalloc/realloc/calloc. The fact that the first (and only) element in this array contains a copy ofthe value pointed to byintPointer(not a copy of the value ofintPointer) doesn't matter. Only callingfree(intPointer)would work.
This question already has answers here:printf anomaly after "fork()"(3 answers)Closed7 years ago. i wanted to find someone that can explain this to me. I have this program: ``` int main(int argc, char *argv[]){ printf("P "); if(fork()==0) printf("C "); return 0; } ``` The result of this program is: P P C What's the reason for that second "P" ?
IO buffering is the reason.printfis not printing the text right away, but waiting for newline,fflushor the end of the program to actually print it. But the buffer for the "future-to-print" text is in the memory that is getting duplicated byfork, so both processes receive it. And in the end both are printing it.
I have two openmpi programs which I start like this ``` mpirun -n 4 ./prog1 : -n 2 ./prog2 ``` Now how do I useMPI_Comm_size(MPI_COMM_WORLD, &size)such that i get size values as ``` prog1 size=4 prog2 size=2. ``` As of now I get "6" in both programs.
I know the question is outdated but I wanted to add to the answer by Hristo Lliev to make it work not just for OpenMPI: you can use the value of an MPI parameter MPI_APPNUM which will be different for each executable as "color" and split the MPI_COMM_WORLD into separate communicators, then print the size of those sub-communicators. Use MPI_Comm_get_attr(MPI_COMM_WORLD, MPI_APPNUM, &val, &flag ); to get the value of MPI_APPNUM.
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 can leave a comment to explain where the question may be able to be answered.Closed7 years ago.Improve this question I know how to do it to a remote server, it would be like: ``` telnet www.esqsoft.globalservers.com 80 ``` But I don't know to a local server (written in C).
Simply substitute the hostname into the url, for example for a computer on your network with the hostname "LivingRoom", use the commandtelnet LivingRoom 80. For a server on own computer, simply usetelnet localhost 80.
Is there a way to know whether CPU is 32 bit or 64 bit without the use of sizeOf operator? Can any other code be written for this?
In this questionHow to determine whether a given Linux is 32 bit or 64 bit? To check if system is 32 or 64 bit kernel, you can call ``` system("getconf LONG_BIT") ``` And check it's return. If it says 64 it's a 64bit kernel, if it's 32 it's 32bit one. To check if the cpu supports 64bits, you can check it in the file /proc/cpuinfo if it has the flag "lm" (Long Mode) ``` system("grep flags /proc/cpuinfo | grep -c lm") ``` If the return is 1 then lm flag is present (64 bit), if it's 0 it's not (32 bit) This is linux only though. Other options are in the question linked at the begining. Some includes checkinglimits.hfor example.
What is Linux or POSIX equivalent ofVirtualAllocwith MEM_TOP_DOWN, if there's any?
POSIX does not seem to have anything when it comes tommap. The GNU C Library version ofmmap(BSD libc also has these flags) extends its functionality though, with aMAP_FIXED(allocate at specific address) andMAP_GROWSDOWN(which is named similarly butMEM_TOP_DOWNactually has nothing to do with this option). Both GNU and BSD's manpages discourage use of these functions, because of portability issues (you're bound to the specific C library, and not fully OS independent anymore). You'd need to determine a way to find the topmost address. I suggest trying to allocate at the top, and moving the passed address down until it does succeed. The step size and "search" algorithm will depend on your need of precision and performance.