question
stringlengths
25
894
answer
stringlengths
4
863
It seems that not all Windows event message expansion strings are specified in the "EventMessageFile" registry values. For example, for "Microsoft-Windows-TerminalServices-RemoteConnectionManager" on Windows 2008 server, the EventMessageFile DLL %SystemRoot%\system32\termsrv.dll" does not contain a message table: ...
Windows PE files with aMUI resourcestore the language specific resources in a external PE file with a .MUI extension. In this case the file would be%SystemRoot%\system32\en-us\termsrv.dll.muifor English resources. Most Windows APIs automatically follow the MUI redirection when loading resources...
I am trying to include a *.can file in a CAPL, but I have to set the absolute path ``` C:\Users\myuser\canoe\simulations\projectX\Function Test\playground.can ``` I want to use a relative path to include it, but I am not sure what is the correct convention or if it is even posible. I have tried this so far (my CAPL ...
Yes, it is possible. You need to specify the path relative to your projects CANoe configuration (*.cfg) file. For example: ``` includes { #include "Function Test\playground.can" } ``` if your CANoe project is inC:\Users\myuser\canoe\simulations\projectX\
For some reason, my yum installer does not link library files. For example, I am trying to include in a c file, so I run sudo yum install c-ares. Everything installs, but when I run the program, I get the error: fatal error: ares.h: No such file or directory The same thing happens when I try to include other packag...
There are usually two packages - one containing the library so you can run existing programs and another for development that contains the headers that has the name with "-devel" appended to it. So in this case you need to also install "c-ares-devel"
Just a general question about programming: When you define a value in C (or any language I suppose), How does the compiler known how to treat the value? For example: ``` #define CountCycle 100000 ``` I would assumeCountCycleis a "long integer" data type, but that's just an assumption. I suppose it could also be afl...
Thecompilerdoes no such thing. Thepreprocessorsubstitues100000forCountCycle. Once that substitution has been completed, the compiler can take over.100000has the typeintif it can fit in that range, alongif it can't. See aC++ Referenceand aC Reference.
I have a question to the conversion ofintarray tochar*. The following code has the output23. But I don't really understand why. Can someone explain it to me? ``` #include <stdio.h> #include <stdint.h> #include <stdlib.h> int main(){ uint32_t x; uint32_t* p = (uint32_t*) malloc(sizeof(uint32_t)); uint...
The size of a uint32 is 32 bits, or 4 bytes. When you do(char*)array+8, you cast the array into an array of char, and take the eighth character. Here, the eighth character contains the beginning of the integer23, which fits into a char.
``` #include <stdio.h> #include <time.h> int main() { time_t startTime, endTime; while(1) { startTime = clock(); /* Some processing */ endTime = clock(); gap = (int)((endTime - startTime) / (CLOCKS_PER_SEC)); printf("StartTime: %d, EndTime: %d\n", (int)startTime, (int)endTime); ...
The problem is thatendTime,startTimeandCLOCKS_PER_SECare allintegers. You need to cast at least one of the values to a floating point type.Anduse a floating point type for destination. E.g. ``` double gap = (double) (endTime - startTime) / CLOCKS_PER_SEC; printf("RunningTime: %f sec", gap); ```
The function in dll has the prototype below ``` void Foo(int arg1, int& arg2); ``` The question is, how to declare the function prototype in C? Is the declaration legal? ``` void Foo(int, int*); ```
Is the declaration legal? It is, but it doesn't declare the same function. If you need a C API, you cannot use a reference. Stick to a pointer, and make sure the function has C linkage: ``` extern "C" void Foo(int, int*) { // Function body } ``` If you cannot modify the DLL code, you need to write a C++ wrapper ...
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.Closed6 years ago.Improve this question I have twocfiles: main.c ``` int main() { foo(); return 0; } ``` foo.c ``` void foo(void); voi...
C source files are compiled independently. E.g. when the compiler is working onmain.c, it knows nothing about what is infoo.cor any other file, unless you actually reference some other file.
We are usingchar *and the lib we use is usingconst unsigned char *, so we convert toconst unsigned char * ``` // lib int asdf(const unsigned char *vv); //ours char *str = "somestring"; asdf((const unsigned char*)str); ``` Is it safe? any pitfall?
it is safe. ``` char *str = "somestring"; ``` str is a constant,you could change str point to another string: ``` str = "some";//right ``` but you can't change the string which str is pointing now ``` str[0]='q';//wrong ``` so it is safe to use const to convert a constant to constant if the asdf() only use to s...
I have implemented the following function for detecting whether or not a multiplication overflows: ``` bool IsSafeMul(uint32_t x, uint32_t y) { uint32_t z = x * y; return (z >= x && z >= y); } ``` I have verified it empirically, but would like to ensure that: Is it 100% guaranteed to work correctly (i.e., n...
No, it is not guaranteed to work correctly. For example, ``` 0x000FFFFF * 0x000FFFFF = 0xFFFFE00001 ``` It produces0xFFE00001after truncation to 32 bits, which passes your test. But multiplication overflows. To test for overflow on multiplication you can simply checkz / x == yprovidedxis not zero.
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.Closed6 years ago.Improve...
You don't want the &n in the printf(), you want n. You are displaying the memory location n is stored in
I have seen several C code examples which utilise the(*p)->some_var way of working with pointers (using parens around the pointer). My question is, is there any functional difference between the two methods of working with C pointers, and if so, how did this difference come about?
Those do not do the same thing at all. Compare: ``` (*p)->some_var // aka (*(*p)).some_var ``` This means "p is a pointer, which we dereference, then dereference again to access a field." ``` *p->some_var // aka *((*p).some_var) ``` This means "p is a pointer, which we dereference to access a field, which is a po...
I need to find out the mask value with respect to the number provided by the user. For example. If user provides input as 22 (in binary 10110) and then I need to find the mask value by changing the high bit of the input as1and rest to0. So in this case it should be: 16 (in binary 10000) Is there any inbuilt metho...
you could compute the position of the highest bit Once you have it, just shift left to get the proper mask value: ``` unsigned int x = 22; int result = 0; if (x != 0) { unsigned int y = x; int bit_pos=-1; while (y != 0) { y >>= 1; bit_pos++; } result = 1<<bit_pos...
I have a question to the conversion ofintarray tochar*. The following code has the output23. But I don't really understand why. Can someone explain it to me? ``` #include <stdio.h> #include <stdint.h> #include <stdlib.h> int main(){ uint32_t x; uint32_t* p = (uint32_t*) malloc(sizeof(uint32_t)); uint...
The size of a uint32 is 32 bits, or 4 bytes. When you do(char*)array+8, you cast the array into an array of char, and take the eighth character. Here, the eighth character contains the beginning of the integer23, which fits into a char.
``` #include <stdio.h> #include <time.h> int main() { time_t startTime, endTime; while(1) { startTime = clock(); /* Some processing */ endTime = clock(); gap = (int)((endTime - startTime) / (CLOCKS_PER_SEC)); printf("StartTime: %d, EndTime: %d\n", (int)startTime, (int)endTime); ...
The problem is thatendTime,startTimeandCLOCKS_PER_SECare allintegers. You need to cast at least one of the values to a floating point type.Anduse a floating point type for destination. E.g. ``` double gap = (double) (endTime - startTime) / CLOCKS_PER_SEC; printf("RunningTime: %f sec", gap); ```
The function in dll has the prototype below ``` void Foo(int arg1, int& arg2); ``` The question is, how to declare the function prototype in C? Is the declaration legal? ``` void Foo(int, int*); ```
Is the declaration legal? It is, but it doesn't declare the same function. If you need a C API, you cannot use a reference. Stick to a pointer, and make sure the function has C linkage: ``` extern "C" void Foo(int, int*) { // Function body } ``` If you cannot modify the DLL code, you need to write a C++ wrapper ...
I want to find which processes holds some file in C code (Linux). One way that comes to my mind is looking atproc/<PID>/fdfor all running processes. However, it would take so long time and because of sweeping all files under thefdfiles of all processes. Could you give another method that is more lightweight? Thank ...
Enumerating all the numerical pseudo-files under /proc, and then examining the fd/ directory for each one, is the standard way of doing this. It is the way that utilities like "lsof" are typically implemented. All this data is held in memory, so accessing it should be fast enough for most purposes.
I want to find which processes holds some file in C code (Linux). One way that comes to my mind is looking atproc/<PID>/fdfor all running processes. However, it would take so long time and because of sweeping all files under thefdfiles of all processes. Could you give another method that is more lightweight? Thank ...
Enumerating all the numerical pseudo-files under /proc, and then examining the fd/ directory for each one, is the standard way of doing this. It is the way that utilities like "lsof" are typically implemented. All this data is held in memory, so accessing it should be fast enough for most purposes.
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.Closed6 years ago.Improve this question ``` #include <stdio....
Its pretty clear, you have to set value bigger than 0 to-dargument. Change ``` system("... -d -1 ..."); ^ ``` to ``` system("... -d 1 ..."); ```
This question already has answers here:Beginner: syntax error before int main ()(2 answers)Closed6 years ago. Tish is the program: ``` #include <stdio.h> int main() { printf("77777"); return 0; } yaki@ubuntu:~/Desktop/yakima$ gcc yakima.c -o yakima.o yaki@ubuntu:~/Desktop/yakima$ ./yakima.c ``` This is ...
You are trying to execute source file. After you create object file you have to link object file(s) to binary like ``` gcc -c yakima.c -o yakima.o gcc yakima.o -o yakima ``` and execute binary ``` ./yakima ```
I want to store the HEX value into auint8_tarray. Below is the code that I am trying to use and pass it to set the resource value: ``` const static uint8_t PSK_KEY[] = "31383031"; security->set_resource_value(M2MSecurity::Secretkey, PSK_KEY, sizeof(PSK_KEY) - 1); ``` Or do I need to set thePSK_KEYin ASCII?
It depends on what you mean. "Store hex" (why do you write it in caps?) is a bit unclear. If the value of the PSK is the four bytes 0x31, 0x38, 0x30, 0x31 then you need to write it differently to get the proper result: ``` static const uint8_t PSK_KEY[] = { 0x31, 0x38, 0x30, 0x31 }; ``` of course those four are AS...
A routine in BLAS Level 2 for banded matrix vector product exists, both for general and symmetric cases (links for MKL implementation). cblas_?gbmv cblas_?sbmv Is there any way to use multiple vectors (without using an outside for-loop), to maximize performance in such cases?
I think that theSpike libraryis supposed to have such a routine for the symmetric case. I'm afraid I cannot be of any more help, though, as I have never used it. The algorithm and implementation of Spike (for system solving) is outlined in[Polizzi & Sameh, Comp. Fluids (36), 2007].
I am using NUMA api and I need to do what can be done by themmap()using theMAP_SHAREDflag, i.e: a process allocates memory and after that, it forks. I need that this allocated memory will be shared from the two processes. If P1 modify this memory region. this modification is seen by P2 and vice-versa. How can I do wit...
It's a two step process for setup: numa_alloc_onnode()- allocates the memory on the specified numa node.mmap()- maps the specified memory to a file, including the ability to share the memory between processes. In other words, mmap() will work the same with memory that was allocated viamallocas memory that was alloca...
This question already has answers here:Why does C++ allow us to surround the variable name in parentheses when declaring a variable?(2 answers)Closed6 years ago. I am new to C++, I see following syntax in c++ to initialize variable. ``` int(i)=1; ``` Then, I have compiled in G++ compiler and compiler did not give a...
It's basically a strange way to write ``` int i = 1; ``` Nothing to worry about. Sometimes, parenthesis around the variable name are necessary in defintions (eg. pointer to functions), and there is no reason to prohibit them for other cases, so it's allowed without any deeper reason.Maythe the author didn't like sp...
A routine in BLAS Level 2 for banded matrix vector product exists, both for general and symmetric cases (links for MKL implementation). cblas_?gbmv cblas_?sbmv Is there any way to use multiple vectors (without using an outside for-loop), to maximize performance in such cases?
I think that theSpike libraryis supposed to have such a routine for the symmetric case. I'm afraid I cannot be of any more help, though, as I have never used it. The algorithm and implementation of Spike (for system solving) is outlined in[Polizzi & Sameh, Comp. Fluids (36), 2007].
I am using NUMA api and I need to do what can be done by themmap()using theMAP_SHAREDflag, i.e: a process allocates memory and after that, it forks. I need that this allocated memory will be shared from the two processes. If P1 modify this memory region. this modification is seen by P2 and vice-versa. How can I do wit...
It's a two step process for setup: numa_alloc_onnode()- allocates the memory on the specified numa node.mmap()- maps the specified memory to a file, including the ability to share the memory between processes. In other words, mmap() will work the same with memory that was allocated viamallocas memory that was alloca...
This question already has answers here:Why does C++ allow us to surround the variable name in parentheses when declaring a variable?(2 answers)Closed6 years ago. I am new to C++, I see following syntax in c++ to initialize variable. ``` int(i)=1; ``` Then, I have compiled in G++ compiler and compiler did not give a...
It's basically a strange way to write ``` int i = 1; ``` Nothing to worry about. Sometimes, parenthesis around the variable name are necessary in defintions (eg. pointer to functions), and there is no reason to prohibit them for other cases, so it's allowed without any deeper reason.Maythe the author didn't like sp...
Why didn't I get a compile time error while accidentally printing only one dimension of a 2D array? ``` #include <stdio.h> void main() { int i; int arr[2][3] = { 1, 2, 3, 4, 5, 6 }; //<- Declared a 2D array for (i = 0; i < 6; i++) { printf("%d\n", arr[i]); // <- Accidently forgot a dimension ...
An expression witharray typeevaluates to apointer to the first array elementin most contexts (a notable exception, among others, is thesizeofoperator). In your example,arr[i]hasarray type. So it evaluates to a pointer of typeint (*)[](a pointer to an array). That's what's getting printed. Printing a pointer with%disu...
This question already has answers here:Why define a macro with the same name and content in C? [duplicate](2 answers)Closed6 years ago. In /usr/include/asm/swab.h I found following code: ``` static __inline__ __u32 __arch_swab32(__u32 val) { __asm__("bswapl %0" : "=r" (val) : "0" (val)); return val; } #defi...
This is calledself-referentitial macro: One common, useful use of self-reference is to create a macro which expands to itself. If you write#define EPERM EPERMthen the macroEPERMexpands toEPERM. Effectively, it is left alone by the preprocessor whenever it's used in running text. You can tell that it's a macro with#if...
I am encountering a problem while printing out a string using a while loop in a standalone function. I have the following code: ``` #include <stdio.h> int pword(char *); int main() { char s[] = "Alice"; pword(s); return 0; } int pword(char *s) { while(*s!='\0') { printf("%s", s); s++...
you're printing theoffsetedword each time, instead of the character. Try changing (for instance) ``` printf("%s", s); ``` by ``` printf("%c", *s); ``` or since you don't really need formatting, use ``` putchar(*s); ``` (all this means that you're basically rewritingputswith a loop. So if no further processing i...
If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?
Use this: #define DOSTUFF(X) dostuff_##X() The preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x(). On the other hand, consider renaming your methods to something meaningful.
I am trying the following:gcc -o foo foo.c -L /path/to/directory/containing/libimf.so -limfand I have used 'log2' function in foo.c. I want it to link with Intel optimized library function but I am getting the following error /usr/bin/ld: skipping /path/to/libimf.so when searching for -limf /usr/bin/ld: cannot find ...
I was using the wronglibimf.sofor the linking. There were two differentlibimf.soat two different locations corresponds toIntel MICand Intel IA64 architecture. It worked with correct one(IA-64).
I can't believe I'm stuck here but I can't seem to get over this. I want to put alonginteger in the middle of a sentence. I get this output; ``` Howdy, I am 166662 Process returned 0 (0x0) execution time : 0.019 s Press any key to continue ``` I am using codeblocks to run this. ``` #include <stdio.h> int main()...
Read the printf spec: First format string, then parameters. ``` #include <stdio.h> int main(){ long mn = 166662; printf("Howdy, I am %ld i hope that you had a better better day than I am having.\n", mn ); return 0; } ```
Is it ok to have an if condition with more than one "less than" (<) or "greater than" (>) symbol in it? For example, I usually see if conditions written like this:if( x > 7 && x < 14)but could you instead write it like this?if( 7 < x < 14 ) The second way compiles but I'm not sure if there are any drawbacks or unexp...
You can writeif( 7 < x < 14 ) something;but that's basically a long-winded way of sayingsomething. 7 < x < 14will be interpreted as(7<x) < 14, and7<xwill be either0or1, both of which are less than14, and therefore the condition will always be true.
How would you simplify the following if-else-if ladder such that the function call is made only once? ``` if (Condition A){ A(); } else { if (Condition B) { A(); } } ```
Change it to: ``` if ((Condition A) || (Condition B)) { A(); } ``` As you want the functionA()to run ifCondition Aistrueor ifCondition Bistrue, you can use the||(OR) operator. This returnstrueif either conditions aretrue.
This question already has an answer here:C: Expand Macro With Token Pasting(1 answer)Closed6 years ago. I have some macros in code ``` #define NUM_IN 3 #define NUM_1 1 #define NUM_2 2 #define NUM_3 3 #define MY(NUMBER) NUM_##NUMBER ``` so if I'm calling the macro ``` MY(NUM_IN) ``` I'm expecting after preproces...
Add one layer of indirection: ``` #define CAT_(a, b) a ## b /* Pastes */ #define CAT(a, b) CAT_(a, b) /* Expands */ #define MY(NUMBER) CAT(NUM_, NUMBER) ```
This question already has answers here:Why define a macro with the same name and content in C? [duplicate](2 answers)Closed6 years ago. In /usr/include/asm/swab.h I found following code: ``` static __inline__ __u32 __arch_swab32(__u32 val) { __asm__("bswapl %0" : "=r" (val) : "0" (val)); return val; } #defi...
This is calledself-referentitial macro: One common, useful use of self-reference is to create a macro which expands to itself. If you write#define EPERM EPERMthen the macroEPERMexpands toEPERM. Effectively, it is left alone by the preprocessor whenever it's used in running text. You can tell that it's a macro with#if...
I am encountering a problem while printing out a string using a while loop in a standalone function. I have the following code: ``` #include <stdio.h> int pword(char *); int main() { char s[] = "Alice"; pword(s); return 0; } int pword(char *s) { while(*s!='\0') { printf("%s", s); s++...
you're printing theoffsetedword each time, instead of the character. Try changing (for instance) ``` printf("%s", s); ``` by ``` printf("%c", *s); ``` or since you don't really need formatting, use ``` putchar(*s); ``` (all this means that you're basically rewritingputswith a loop. So if no further processing i...
If I have a functiondostuff_1and another function,dostuff_2and N other functionsdostuff_N, is there a way I can make a macro like#define DOSTUFF(X) ...so thatDOSTUFF(5)gives medostuff_5?
Use this: #define DOSTUFF(X) dostuff_##X() The preprocessor willreplaceevery existence ofDOSTUFF(X)in your code todostuff_x(). On the other hand, consider renaming your methods to something meaningful.
I would like to construnct the following string using defines ``` #define LOG_FLOAT_MARKER "%s%d.%010d" ``` So far I have ``` #define EXP (10) #define LOG_FLOAT "%s%d.%0" #define D "d" ``` I am trying to create a string like this ``` #define LOG_FLOAT_MARKER LOG_FLOAT EXP D ``` but not getting the expected o...
You can't have(10)forEXP, since you don't want the parentheses to be part of the result. You must use stringification, and some hoop-jumping: ``` #define EXP 10 #define JOIN(a, b, c) a #b c #define JOIN2(a, b, c) JOIN(a, b, c) #define LOG_FLOAT_MARKER JOIN2(LOG_FLOAT, EXP, D) ``` Also, I think using a p...
I know that is a simple question but I couldn't find the answer. I have this string: ``` "M1[r2][r3]" ``` I want to get only the"M1", I'm looking for something likestrchr()a function that get the string and acharto stop at.
What about usingstrtokand"["as a delimiter? ``` #include <string.h> /* for strtok */ #include <stdio.h> /* for printf */ int main() { char str[] = "M1[r2][r3]"; // str will be modified by strtok const char deli[] = "["; // deli could also be declared as [2] or as const char *. Take your pick... char *t...
I have a function where i pass to it an array of pointers to structure as an argumentvoid BubbleSort_ArrayOfEmployees(struct employee* emp_arr[],int size);why i can't De-referencing any pointer of the array using this form(*(emp_arr[i]).id)the compiler state this error//error: request for member 'id' in something not ...
The.operator has higher precedence than*, so you need to change your parentheses. ``` (*emp_arr[i]).id ```
I should implement these function-like macros, but I'm not sure I understand the syntax. Could somebody explain me how to read them? ``` #define msgsend(dest, payload) (SYSCALL(SYS_SEND,(unsigned int) (dest), (unsigned int) (payload),0)) #define msgrecv(source, reply) (((struct tcb_t *) SYSCALL(SYS_RECV, (unsigned i...
You define a macromsgsend(dest, payload)which will be expanded to ``` (SYSCALL(SYS_SEND,(unsigned int) (dest), (unsigned int) (payload),0)) ``` Simplifying the above line ``` SYSCALL(SYS_SEND, (unsigned int) (dest), (unsigned int) (payload), 0) ```
In Windows, I can useGetAPCfunction to get the local codepage. But how should I do to get local codepage in Linux? Thanks.
Linux does not use code page identifiers. It haslocaleidentifiers, but different processes can have different locales and a process may be using different locales indifferent categoriesat once. Every C program starts off in the "C" locale, but can easily setchange to locales specified by the environment. Note thatloca...
Simple question. I seem to get the impression thatCoreFoundationisn't really designed for handling, for example, pointers to structs (containing CF objects).CFArrayAppendValuewill take any pointer value to append, but I get segfaults if I try andCFShowit. I also note that there's noCFTypeIDfor a bare pointer, though ...
I don't believe CoreFoundation containers are intended to be used to store anything but CoreFoundation objects. Any bridging between regular C structs could potentially be done via CFData objects and wrapper methods (see alsohttp://www.cocoabuilder.com/archive/cocoa/22246-implementing-new-corefoundation-types.html).
Using gcc compiler, why is thisuint32_t-2147483648 when I set the MSB? It's unsigned - shouldn't it be positive? ``` #include <stdio.h> #include <stdint.h> #define BIT_SET(a,b) ((a) |= (1<<(b))) int main() { uint32_t var = 0; BIT_SET(var, 31); printf("%d\n", var); //prints -2147483648 return 0; }...
%dis forsignedintegers. What you want is%uwhich is forunsignedintegers.printfis notsmartenough to guess the type of your data. Source
I need an explanation on this piece of code ! I know a little about it but not enough ``` #if defined ( __ICCARM__ ) #pragma location="ExtQSPIFlashSection" #else __attribute__((section(".ExtQSPIFlashSection"))) #endif ``` It's in IAR Thank you anyway:)
#pragmaand__attribute__(......are just specific for the the particular compiler. With them you do exactly the same - place the object into the particular section in the memory. The sections are defined in the linker script
Using gcc compiler, why is thisuint32_t-2147483648 when I set the MSB? It's unsigned - shouldn't it be positive? ``` #include <stdio.h> #include <stdint.h> #define BIT_SET(a,b) ((a) |= (1<<(b))) int main() { uint32_t var = 0; BIT_SET(var, 31); printf("%d\n", var); //prints -2147483648 return 0; }...
%dis forsignedintegers. What you want is%uwhich is forunsignedintegers.printfis notsmartenough to guess the type of your data. Source
I need an explanation on this piece of code ! I know a little about it but not enough ``` #if defined ( __ICCARM__ ) #pragma location="ExtQSPIFlashSection" #else __attribute__((section(".ExtQSPIFlashSection"))) #endif ``` It's in IAR Thank you anyway:)
#pragmaand__attribute__(......are just specific for the the particular compiler. With them you do exactly the same - place the object into the particular section in the memory. The sections are defined in the linker script
This question already has answers here:why sizeof(13.33) is 8 bytes?(5 answers)Why floating point value such as 3.14 are considered as double by default in MSVC?(5 answers)Closed6 years ago. Why doessizeof(5.0)return 8 as its output rather than 4 as my machine allocates 4 bytes for afloatdata type? Does it by default...
Yes. N1570 (latest C11 draft),§6.4.4.2 p4: An unsuffixed floating constant has typedouble. If suffixed by the letterforF, it has typefloat. If suffixed by the letterlorL, it has typelong double. As for your "why" question, in practice,floatis rarely useful due to its very limited precision, so this default "mak...
This question already has answers here:Why does putting parentheses around a list of comma separated values change the assignment? [duplicate](4 answers)Closed6 years ago. Suppose I a couple of expression in C. Different outputs are provided. ``` int i =2,j; j= i + (2,3,4,5); printf("%d %d", i,j); //Output= 2 7 j=...
Commaoperator works by evaluating all expressions and returning the last expression. ``` j= i + (2,3,4,5); ``` becomes ``` j= i + (5); //j=7 ``` In the second expression assignment operator takes precedence over comma operator,so ``` j= i + 2,3,4,5; ``` becomes ``` (j= i + 2),3,4,5; //j=4 ```
When I try to compile this code ``` int main() { int i = 0; ++(++i); } ``` I get this error message. test.c:3:5: error: lvalue required as increment operand ++(++i); ^ What is the error message saying? Is this something that gets picked up by the parser, or is it only discovered during semantic a...
++iwill give an rvalue1after the evaluation and you can't apply++on an rvalue. §6.5.3.1 (p1): The operand of the prefix increment or decrement operatorshall have atomic, qualified, or unqualified real or pointer type, andshall be a modifiable lvalue. 1. What is sometimes called "rvalue" is in this International S...
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question If I create an array of size 10 and only 2 elements are stored in array so remaining spac...
You would use a simple linked list instead of an array, or if you would need to use an array, then you should userealloc(), which would shrink the array to use only 2 cells, instead of 10. , like this: ``` #include <stdio.h> #include <stdlib.h> int main(void) { int* ptr = malloc(10 * sizeof(int)); ptr[0] = 4...
If I decided to use an enum, such as this one: ``` typedef enum { FALSE, TRUE = !FALSE } bool; ``` as a parameter, and a return type in this function: ``` bool foo(bool param) { <do something> return TRUE; } ``` Would it cause any problems? for example, across compilers. PS: I don't intend to use#incl...
Since you don't intend to#include <stdbool.h>(which might cause conflicts), there should not be a problem with your approach. However, if this is a big project, where others contribute too, then I wouldn't recommend you to go on with your approach, because they might include that header. Moreover, if you decide to ...
I am trying to get the call stack, for some reason the following code returns a wrong stack pointer: ``` unsigned int stack_pointer = 0; __asm("la $26, %[spAddr]\n\t" "or $27, $0, $sp\n\t" "sw $27, 0($26)\n\t" "nop"::[spAddr] "m" (stack_pointer)); retur...
To get the stack pointer use the proper output constraint like so: ``` register unsigned sp asm("29"); asm("" : "=r" (sp)); ``` Note that mips uses a register for the return address, but of course non-leaf functions might store it on the stack. To implement a backtrace, you can however use the builtins__builtin_ret...
I have a local device connected to the router and I can access its Mac address through already existing code. How can I find the IP address of the device using this Mac address in c? "arp" might be providing the details, but I need it IP address independent from that protocol.
If your requirements allow you to make use of ARPindirectly(that is, by relying on standard networking behavior rather than coding ARP queries yourself)... Your best answer is probably to find the MAC address in your local ARP cache, as exposed in/proc/net/arp. Of course, there's only going to be data there for your...
``` #include<stdio.h> #include<conio.h> void main() { int a[3][2]={{4,7},{6,5},{9,1}}; int i,j; clrscr(); for(i=0;i<2;i++) for(j=0;j<3;j++) { printf("%d ",*(a[j]+i)); } getch(); } ``` Herea[i]is of type int(*)[2]. So when we do*(a[0]+1), it should go to next row and print 6 right? Why is it print...
a[0]is an array of 2 ints with values{4,7}. It has the typeint[2]. When used in most expressions, this automatically decays to a pointer to its first element, i.e. typeint*which points to the4. Incrementing this by one makes it point to the nextint, which is 7. A much clearer way to write*(a[j]+i)isa[j][i]. This doe...
I want to write code in C to generate the pattern: ``` 1 22 22 333 333 333 ``` ..and I need help. Thank you! :) This is what I've tried: ``` int n,i,j; scanf("%d",&n); for(i=1;i<=n;i++) { printf("\n"); for(j=1;j<=i;j++) { printf("%d",i); } } ```
The code in the original question is pretty close - you just needed one more loop inside to iterate and print the numbers X times. If you want your output to look like ``` 1 22 22 333 333 333 ``` then this will do it ``` int main() { int n,i,j,k; scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1...
``` #include<stdio.h> #include<stdlib.h> void memory_allocate(int *ptr) { ptr=(int*)malloc(sizeof(int)*100); } int main() { int *ptr1; memory_allocate(ptr1); *ptr1=12; } ``` My code causes a segmentation fault. Can anybody explain why?
The issue is that, when the function setsptr, the new pointer value isn't passed back toptr1. One way to make this work is by using a pointer to pointer: ``` void memory_allocate(int** ptr) { (*ptr) = (int*)malloc(sizeof(int)*100); } int main() { int *ptr1; memory_allocate(&ptr1); *ptr1=12; /* TODO: ...
Since addresses are numbers and can be assigned to a pointer variable, can I assign any integer value to a pointer variable directly, like this: ``` int *pPtr = 60000; ```
You can, but unless you're developing for an embedded device with known memory addresses with a compiler that explicitly allows it, attempting to dereference such a pointer will invoke undefined behavior. You should only assign the address of a variable or the result of a memory allocation function such asmalloc, orN...
Here's the code ``` void test(char *bar) { printf("%s", bar); } int main(int x, char *argv[]) { test(argv[0]) return 0; } ``` argv[]is an array of pointers, andargv[0]gets the first pointer in the array. When used intest(char *whatever), because it's a pointer, I thought it would print the memory addre...
The%sformat specifier toprintfexpects a pointer to a string (i.e. the address of the first element of an array of characters ending with a null byte) and prints that string. If you want to print a pointer value, use the%pformat specifier. ``` printf("%p", (void *)bar); ``` Note that the cast tovoid *pointer is requ...
Since addresses are numbers and can be assigned to a pointer variable, can I assign any integer value to a pointer variable directly, like this: ``` int *pPtr = 60000; ```
You can, but unless you're developing for an embedded device with known memory addresses with a compiler that explicitly allows it, attempting to dereference such a pointer will invoke undefined behavior. You should only assign the address of a variable or the result of a memory allocation function such asmalloc, orN...
Here's the code ``` void test(char *bar) { printf("%s", bar); } int main(int x, char *argv[]) { test(argv[0]) return 0; } ``` argv[]is an array of pointers, andargv[0]gets the first pointer in the array. When used intest(char *whatever), because it's a pointer, I thought it would print the memory addre...
The%sformat specifier toprintfexpects a pointer to a string (i.e. the address of the first element of an array of characters ending with a null byte) and prints that string. If you want to print a pointer value, use the%pformat specifier. ``` printf("%p", (void *)bar); ``` Note that the cast tovoid *pointer is requ...
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed6 years ago.Improve this question During my programming exam in college I was told to write a program that can find th...
121 = 11 * 11 would be the first non-prime listed as prime by your code.So your code is only a solution up to n = 120. I.e.: No.
Shouldn't the return be of typesize_tinstead? Because the size of objects in C is of this type, including the string passed toprintf.
Why printf returns an int in C?Shouldn't be of typesize_tinstead? It could have been, but certainly an early design decision was to accommodate a return value of the negativeEOFto indicate error. size_twas something of an afterthought in early design choices. Many functions usedintwheresize_tis used now in thosepre...
This question already has answers here:How come an array's address is equal to its value in C?(6 answers)Closed6 years ago. Warning: assignment from incompatible pointer type [-Wincompatible-pointer-types] ``` #include <stdio.h> #include <string.h> int main() { char *p; char str[100]; p = &str; re...
&strof typechar (*)[100]which is incompatible with the typechar *. What you need is just assignstrtopas array decay to pointer to it's first element when used in an expression except when an operand ofsizeofand unary&operator.
Let's say we have compiled a C program that refer directly to a numeric address , and then executed two. So these two processes physically refer to the same place? If not, how can you refer to different physical spaces?
This depends on the actual platform. On many embedded systems this might be the case, but for example on x86 in protected mode each application gets its own address space and thevirtual memory managertranslates virtual addresses of each application into physical memory addresses. This way applications end up being iso...
This question already has answers here:What will happen if '&' is not put in a 'scanf' statement?(6 answers)Closed6 years ago. This is a program for checking the leap year. Could you kindly tell me why I'm getting this error? ``` #include <stdio.h> int main() { int year=0; printf("Enter the year to be Vali...
You have to pass pointer toscanf. ``` scanf("%d",year); ``` should be ``` scanf("%d", &year); ```
I saw the following code (Question 3 onPUZZLERSWORLD.COMsite): Code 1 : ``` for (i = 0; i < 1000; i++) for (j = 0; j < 100; j++) x = y; ``` Code 2 : ``` for (i = 0; i < 100; i++) for (j = 0; j < 1000; j++) x = y; ``` Which code will execute faster? Options: ``` a) Code 1 and Code 2 are o...
Unlessxoryor both are declared asvolatile, both codes can be reduced into: ``` x = y; ``` Example: ``` int f(int y) { int x; for (int i = 0; i < 1000; i++) for (int j = 0; j < 100; j++) x = y; return x; } ``` yields: ``` f(int): mov eax, edi ret ```
All I have found in C11 Standard for incomplete types are incomplete array types. I was wondering if there is a non-array incomplete type.
An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An "incomplete type" can be A structure type whose members you have not yet specified.A union type whose members you have not yet specified.An array type whose dimension you have not yet spe...
All I have found in C11 Standard for incomplete types are incomplete array types. I was wondering if there is a non-array incomplete type.
An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An "incomplete type" can be A structure type whose members you have not yet specified.A union type whose members you have not yet specified.An array type whose dimension you have not yet spe...
I am facing a problem working with cygwin and sockets under windows. The code is working normaly in Ubuntu but when I am running it under windows, the socket will not open (error 10093) because no WSAStartup call was made. But when I include winsock.h for WSAStartup i cant even compile because of an conflicting decla...
Don't mess up cygwin with windows libs an everything works fine! Since I am not including any windows lib, the UNIX sockets work fine. Thanks to user4581301.
This question already has answers here:Is free() zeroing out memory?(7 answers)Closed6 years ago. ``` int main() { int *p,*q; p=(int *)malloc(sizeof(int)); *p=5; free(p); } ``` When I examine the memory address allocated topafter the execution of thefree(p)statement, I observe that the me...
The content of*pafterfree(p)returns is undefined. It may be 0, 42 or anything else. ``` #include <stdlib.h> #include <stdio.h> int main(void) { int *p, *x; p = malloc(sizeof(int)); *p = 5; // the following will print "0x7fd0cac00350: 5" or similar printf("%p: ", p); printf("%d\n", *p); ...
From Kerrek SB's comment onWhy can't a modifiable lvalue have an array type? You can trivially assign arrays by making them members of a struct and then assigning those lvalues. What does it mean? Does it mean that if a structure has an array member, then the array member can be modifiable? But the following exampl...
No, it means that if you assign an instance of astructlike the one in your example to anotherstructyou are effectively assigning arrays. ``` struct Array { int array[3]; }; struct Array A; struct Array B = {{0, 1, 2}}; // by Chris Dodd // This is valid! A = B; ```
I wonder to know is it possible to send a parameter to a#definemacro for selecting different output For example: ``` #define Row(1) LPC_GPIO0 #define Row(2) LPC_GPIO3 #define Row(3) LPC_GPIO2 ``` Then in my code I create a loop for sending the parameter ``` Row(x) ```
This macro syntax doesn't exist. Moreover, itcan't possibly exist, because macros are expandedbeforethe compiler compiles the code. If yourxisn't a compile time constant, there would never be a way to determine what to replace in the source code for the macro invocation. If you need to index some values, just use an...
We can provide an object as an initializer in another object's definition. It just copies and assigns the value of an object to another. Is it possible to provide a function name as an initializer in another function's definition? Where does the C standard say if it is allowed or not? I didn't find it, so I suppose ...
You probably want a function pointer (as a function doesn't really make sense in this context): ``` int (*h)() = f; ```
I wanted to debug printf function, so when I step inside the printf function (gdb debugger) it showed me this: ``` __printf (format=0x80484d0 " my name is Adam") at printf.c:28 28 printf.c: No such file or directory. ``` What is the meaning of this? And when I again started step then there are a lot more statement...
I think it's pretty clear. There is a place where thegdbexpects the source code to be, so downloadglibc's source code and put it there. I think the error message contains the full path. If it's a linux distro it's fairly simple in fact because usually source packages are shipped too. Otherwise you need to find the so...
A string literal is an lvalue. An lvalue can be used: as the operand of the address-of operator (except if the lvalue designates a bit field or was declared register).as the operand of the pre/post increment and decrement operators.as the left-hand operand of the member access (dot) operator.as the left-hand operand...
Your bullets 2 and 4 require amodifiable lvalue, which excludes arrays. String literals are arrays, so they are not modifiable lvalues. The first one is OK,&"hello"is allowed, although this would be an uncommon usage. The third one, the left-hand side of.must have struct type, which a string literal doesn't. However...
We can provide an object as an initializer in another object's definition. It just copies and assigns the value of an object to another. Is it possible to provide a function name as an initializer in another function's definition? Where does the C standard say if it is allowed or not? I didn't find it, so I suppose ...
You probably want a function pointer (as a function doesn't really make sense in this context): ``` int (*h)() = f; ```
I wanted to debug printf function, so when I step inside the printf function (gdb debugger) it showed me this: ``` __printf (format=0x80484d0 " my name is Adam") at printf.c:28 28 printf.c: No such file or directory. ``` What is the meaning of this? And when I again started step then there are a lot more statement...
I think it's pretty clear. There is a place where thegdbexpects the source code to be, so downloadglibc's source code and put it there. I think the error message contains the full path. If it's a linux distro it's fairly simple in fact because usually source packages are shipped too. Otherwise you need to find the so...
A string literal is an lvalue. An lvalue can be used: as the operand of the address-of operator (except if the lvalue designates a bit field or was declared register).as the operand of the pre/post increment and decrement operators.as the left-hand operand of the member access (dot) operator.as the left-hand operand...
Your bullets 2 and 4 require amodifiable lvalue, which excludes arrays. String literals are arrays, so they are not modifiable lvalues. The first one is OK,&"hello"is allowed, although this would be an uncommon usage. The third one, the left-hand side of.must have struct type, which a string literal doesn't. However...
What happens when in C I do something like: ``` char buf[50]=""; c = fgetc(file); buf[strlen(buf)] = c+'\0'; buf[0] = '\0'; ``` I'm using some this code in a loop and am finding old values in buf I just want to add c to buf I am aware that I can do: ``` char s=[5]; s[0]=c; s[1]='\0'; strcat(buf, s); ``` to add th...
Why would it work? char buf[50]="";initializes the first element to'\0',strlen(buf)is therefore0.'\0'is a fancy way of a saying0, soc+'\0'==c, so what you're doing is ``` buf[0]=c; buf[0]=0; ``` which doesn't make any sense. The compound effect of the last two lines in ``` char buf[50]=""; c = fgetc(file); buf[st...
``` void main () { int i; if (i < 0) { i = -i; }; } ``` Can anyone help me to understand why an overflow may occur in the above program?
An overflow may occur because the range of integer representation in two's complement is not symmetric: the magnitude of the smallest negative number that can be represented is the magnitude of the highest positive number that can be represented, plus one. For example, on a 32-bit system the values are-2,147,483,648an...
I have only a compiled binary code (.hex) of pic microcontroller,how can i convert it to code line in mikroc in order to see the instruction of program?
When it's compiled, it ismachine codeand there's no (automatic) way of translating machine code to C. Youcanget a readable version of the code,assembly, using adisassemblerfor your target CPU. This of course requires you learning your CPU's assembly language.
From C in a Nutshell: the compiler implicitly converts a pointer to a given type T into amore qualifiedversion of the type T . If you want to convert a pointer into a pointer to aless-qualifiedtype, you must use an explicit type conversion. The type qualifiers in C areconst,volatile,restrictand_Atomic. I was wo...
There is no hierarchy among the qualifiers, each qualifier specifies a property for the object it is applied to.More qualifiedmeans having more qualifiers and converting frommore qualifiedtoless qualifiedmeans stripping qualifiers from the type of the object. charis less qualified thanconst charandvolatile charwhich ...
Thislinksays that the second and third operands in a conditional expression must be of compatible types. It also says that one of the second and third pointer operands might beNULL. So does that mean the unevaluated pointer turnsNULL? Example:a == a? pointer1 : pointer2; Heara == ais true sopointer1gets evaluated an...
So does that mean the unevaluated pointer turns NULL? No it explains exception where second and third operands can have different types. One of them can beNULL. ``` int * pointer = (1 == 1) ? NULL : &intvar; ``` or ``` int * pointer = (1 == 1) ? &intvar : NULL; ``` Becouse one of them isint*and secondvoid*. Yo...
I want to merge two single character constants into one like '1'+'2'='12'.So that I can add an integer value to this single character. I have tried a lot of things like used their ASCII values.Also the substring functions doesn't seem to work in this context.Help!
If you want to compute the number from 2 digit characters, the formula is very simple: ``` char c1 = '1'; char c2 = '2'; int value = (c1 - '0') * 10 + (c2 - '0'); // value is 12 ``` c1 - '0'evaluates to the number represented by the digitc1. It works because the digits are guaranteed to be consecutive from'0'to'9'i...
I have to make functions similar (but more complex) than these. We aren't running them, just ensuring these pointers are receiving the values given. Are there any quick and easy ways to test and make sure we are doing these types of problems correct? My issue is, what kind of parameter could I pass into this function ...
Try passing an address in to the function: ``` int storeThree(int *p) { *p = 3; } // Test function void test() { int x = 5; //any integer other than what storeThree is going to fill storeThree(&x); assert(x == 3); } ```
Suppose I have a C struct like this ``` struct foo { int sz; struct bar **arr; }; ``` In my SWIG file, I use "carrays.i" to give me control of the array inside this struct. Here I use ``` %module mdl %include "carrays.i" %array_functions(struct bar*, barArray) ``` Then I allocate memory for this array in p...
You have to call delete when the array is no longer needed. If you don't do it before thefooobject reference count goes to zero and is destroyed, you have a memory leak.
Suppose I have a C struct like this ``` struct foo { int sz; struct bar **arr; }; ``` In my SWIG file, I use "carrays.i" to give me control of the array inside this struct. Here I use ``` %module mdl %include "carrays.i" %array_functions(struct bar*, barArray) ``` Then I allocate memory for this array in p...
You have to call delete when the array is no longer needed. If you don't do it before thefooobject reference count goes to zero and is destroyed, you have a memory leak.
I was experimenting the behaviors of pointer in C. I wrote the following program: ``` #include <stdio.h> main(){ int a = 1; printf("%p\n", &&a); } ``` I knew that this program would give error. Because an address of address would be ambiguous and this would become extremely recursive. But when I tried to com...
&&is realgccextension, but not for variables. Its for labels. &&ais used toget the address of a label defined in the current function. In your case compiler deduced thata, followed by&&operator, islabel, but you haven't anylabeladefined in your code, so that is the error.
see the ouput image What's the output of following code and why? I am curious to know why c compiler shows the unusual output. What happens behind the scene? ``` #include<stdio.h> int main() { char a,b,c; printf("Enter First char:"); scanf("%c",&a); printf("Enter Second char:"); scanf("%c",&b...
First time you type1and hitEnter(Enteris interpreted as newline character) The first scanf reads'1'. The second scanf reads'\n'. Then you type2and clickEnter. The third scanf reads'2'. Probably you need to read"%c "or" %c", since' 'in format string skips all whitespaces.
Is it bad practice to directly pass strings into functions? Will it cause memory errors? ``` func(char *x) { //do stuff } func("String"); ``` Or is it safer to do this? ``` char *s = "string"; func(s); ```
Will it cause memory errors? It might if you try to modify this string. To be safe declare your function ``` func(const char *x) { ``` But there is nothing wrong in passing string literals to the functions. Otherwise 99.99 of programs are badly written. Or is it safer to do this?char *s = "string"; func(s); It d...
I need to access a value of a constant exported from C in Rust. I want to read the value from the actual symbol, and not just copy'n'paste the value to Rust (in my case the value is a pointer, and C checks for pointer equality). ``` extern void *magic; ``` What's the syntax to getmagic: *const c_voidreadable in Rus...
``` use std::os::raw::c_void; extern "C" { #[no_mangle] static magic: *const c_void; } ``` Optionally, before theexternthere can be#[link(kind="static", name="<c library name>")]to get the symbol actually linked. Externally linkable items, even if constant, need be declared withstatic, not justconstkeyword ...
I'm studying arrays on C. Currently, I'm running this code ``` #include <stdio.h> signed char cData[][2][3] = {1,2,3,4,5,6}; int main() { printf("%d\n", cData[0][0]); return 0; } ``` And the answer is4210700.I want to know how doescdetermine the first bound? And how come I get the number4210700instead of1...
cData[0][0]is basically a pointer (signed char *type) and you need%pspecifier. ``` printf("%p\n", (void *)cData[0][0]); ```
I have a string"2017-07-30_00:00:00"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be help...
strptime()is suported by bionic (i.e. available in NDK).
Is it bad practice to directly pass strings into functions? Will it cause memory errors? ``` func(char *x) { //do stuff } func("String"); ``` Or is it safer to do this? ``` char *s = "string"; func(s); ```
Will it cause memory errors? It might if you try to modify this string. To be safe declare your function ``` func(const char *x) { ``` But there is nothing wrong in passing string literals to the functions. Otherwise 99.99 of programs are badly written. Or is it safer to do this?char *s = "string"; func(s); It d...
I need to access a value of a constant exported from C in Rust. I want to read the value from the actual symbol, and not just copy'n'paste the value to Rust (in my case the value is a pointer, and C checks for pointer equality). ``` extern void *magic; ``` What's the syntax to getmagic: *const c_voidreadable in Rus...
``` use std::os::raw::c_void; extern "C" { #[no_mangle] static magic: *const c_void; } ``` Optionally, before theexternthere can be#[link(kind="static", name="<c library name>")]to get the symbol actually linked. Externally linkable items, even if constant, need be declared withstatic, not justconstkeyword ...
I'm studying arrays on C. Currently, I'm running this code ``` #include <stdio.h> signed char cData[][2][3] = {1,2,3,4,5,6}; int main() { printf("%d\n", cData[0][0]); return 0; } ``` And the answer is4210700.I want to know how doescdetermine the first bound? And how come I get the number4210700instead of1...
cData[0][0]is basically a pointer (signed char *type) and you need%pspecifier. ``` printf("%p\n", (void *)cData[0][0]); ```
I have a string"2017-07-30_00:00:00"I want to convert this string into milliseconds in C/Android NDK. But did not find any function to do so. Some example which is in C++boost::and any other libs which don't work in Android NDK. So if there is any way to do this in C/C++ that can be run in Android NKD, it will be help...
strptime()is suported by bionic (i.e. available in NDK).