question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to profile some difficult code in Instruments and need to see both assembly and the source code lines. Is there any way to switch views? The only way I know of is to not compile the program with-gso that there are no debug tables.. but it'd be extremely useful to see both on one screen where each set of assembly instructions are also marked as what line they actually implement in the source code. How can I do this?
In the version of Instruments that comes with Xcode 6, when you are in the source view, there is a set of five small buttons above the source code you are viewing. Click the second button to show both the source code and disassembly views.
I'm trying to define a macro. The idea is that when it expands, it'll include a header. For example: ``` #define function() \ include <CustomHeader.h> ``` Thanks a lot.
As others have pointed out, you cannot produce a directive from a macro. You can however produce theargument toa directive from a macro: ``` #define INCF(F) INCF_(F) #define INCF_(F) #F #define BAR foo.h #include INCF(BAR) // same as #include "foo.h" ``` But you can't get rid of that explicit#include, or insert it into the middle of a different line, or anything like that.
I tried includingstring.handstdlib.h, but still get undefined reference compile errors. This leads me to conclude that it is in a different library that I didn't include. Where is it? I am using gcc compiler - the code is written in Windows, but is going to be compiled and run on a unix server.
strcat_scan be found instring.has of C 2011. Generally speaking, only microsoft has implemented these alternative functions.
I use windows 8, and Code::Block 13.12. I have code C language like that: ``` #include <stdio.h> #include <conio.h> main() { while (!kbhit()) printf("You haven't pressed a key.\n"); return 0; } ``` When I press a key, It not Stop, i don't think my code wrong, have any suggest for me to fix this? And this is my Screen:https://i.stack.imgur.com/xHDVe.png Update: I tested on some another computer, It work! (same code)
Fromkbhit() Explanation: This function is not defined as part of the ANSI C/C++ standard. It is generally used by Borland's family of compilers. It returns a non-zero integer if a key is in the keyboard buffer.It will not wait for a key to be pressed.
The code here is a typical example for shallow copy, it ought to got the warning when running, but on my Xcode, it's running well and result is hi,hihi,hi why? The code: ``` struct pc { char *p; }; int main() { struct pc pc1; pc1.p = malloc(100); strcpy(pc1.p, "hi"); struct pc pc2 = pc1; // shallow copy printf("%s,%s\n", pc1.p, pc2.p); free(pc1.p); printf("%s,%s", pc1.p, pc2.p); return 0; } ```
Accessing memory after you'vefree()d it invokesundefined behaviour. You shouldnotbe using theprintf()with thefree()d memory after you call ``` free(pc1.p); ```
it is my first type to encounter this type of code. I am having a hard time understanding it. ``` #ifndef A #define A #endif #ifndef B #define B #endif void funct (structA* A paramA, structB* B paramB){}; ``` What is the purpose of preprocessor A and B in the parameter?
For: ``` #define A this_is_a ``` The preprocessor will replaceAwiththis_is_a. For: ``` #define A ``` The preprocessor will replaceAwith nothing. So in your example code,AandBsymbols are just discarded. People use this technique to annotate code sometimes, for example: ``` #define IN #define OUT ``` Now you can annotate function parameters showing whether they are "in" or "out" parameters: ``` void my_function(IN int i, OUT int& x) { ... } ```
Sorry if this is too stupid but I couldn't resist asking.I wish to create a C application with an embedded MYSQL database(libmysqld)in it. What I am confused about is the size of the application.Since the application itself embeds a mysql db in it, would the size of the application be the size of the binary(excluding db) + size of the embedded db?If this is the case wouldn't it be difficult run standalone applications which deals with large volumes of mysql data as they would consume a lot of RAM? Am I missing the concept here?
Embedding mysql means embedding the "server" code, not data. Database tables will be stored in configured datadir.
On the CPU, I have an array of positions and colors: ``` [ x0, y0, z0, col0, x1, y1, z1, col1 ...] ``` On the device, I have a 3D texture. Is there any efficient way to modify that texture so that positionx0, y0, z0's color becomes col0 and so on?
glTexSubimage3d will work if you can arrange your data into cubes. Doing it one texel at a time would be miserable though. https://www.opengl.org/sdk/docs/man3/xhtml/glTexSubImage3D.xml
for example : ``` void size(int a, int array[a][a]){ .......... } ``` (I mean is it ok to pass int a and also have varaible a as size of an array im also passing to the same function? I would also like to ask if is it possible to pass 2D array using a double pointer for e.g: void smthn(int **array){...}?)
This declaration ``` void size(int a, int array[a][a]); ``` is equivalent to ``` void size(int a, int ( *array )[a] ); ``` wherearrayis a pointer to a Variable Length Array withaelements. It is a valid syntax in C99. Here is a demonstrative program ``` #include <stdio.h> void f( size_t n, int a[n][n] ) { printf( "%zu\n", sizeof( *a ) / sizeof( **a ) ); } int main(void) { int a[3][3]; int b[10][10]; f( 3, a ); f( 10, b ); return 0; } ``` The program output is ``` 3 10 ```
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question Is there a way to convertcdatatouserdata? How can I use the C api to push/retrievecdatato/from the stack? Edit:The original title mentioned luajit but not Torch. In that context the other answers beside the one I finally had submitted myself (e.gwolfgang's) made perfect sense.
There is no extension to the Lua C API to access cdata objects as created by LuaJIT's FFI library. So, the simple and recommended way is to do your marshalling from the Lua side if you're dealing with cdata. So, call a C function from Lua and pass thatcdataas a parameter.
I'm trying to profile some difficult code in Instruments and need to see both assembly and the source code lines. Is there any way to switch views? The only way I know of is to not compile the program with-gso that there are no debug tables.. but it'd be extremely useful to see both on one screen where each set of assembly instructions are also marked as what line they actually implement in the source code. How can I do this?
In the version of Instruments that comes with Xcode 6, when you are in the source view, there is a set of five small buttons above the source code you are viewing. Click the second button to show both the source code and disassembly views.
I'm trying to define a macro. The idea is that when it expands, it'll include a header. For example: ``` #define function() \ include <CustomHeader.h> ``` Thanks a lot.
As others have pointed out, you cannot produce a directive from a macro. You can however produce theargument toa directive from a macro: ``` #define INCF(F) INCF_(F) #define INCF_(F) #F #define BAR foo.h #include INCF(BAR) // same as #include "foo.h" ``` But you can't get rid of that explicit#include, or insert it into the middle of a different line, or anything like that.
I tried includingstring.handstdlib.h, but still get undefined reference compile errors. This leads me to conclude that it is in a different library that I didn't include. Where is it? I am using gcc compiler - the code is written in Windows, but is going to be compiled and run on a unix server.
strcat_scan be found instring.has of C 2011. Generally speaking, only microsoft has implemented these alternative functions.
I use windows 8, and Code::Block 13.12. I have code C language like that: ``` #include <stdio.h> #include <conio.h> main() { while (!kbhit()) printf("You haven't pressed a key.\n"); return 0; } ``` When I press a key, It not Stop, i don't think my code wrong, have any suggest for me to fix this? And this is my Screen:https://i.stack.imgur.com/xHDVe.png Update: I tested on some another computer, It work! (same code)
Fromkbhit() Explanation: This function is not defined as part of the ANSI C/C++ standard. It is generally used by Borland's family of compilers. It returns a non-zero integer if a key is in the keyboard buffer.It will not wait for a key to be pressed.
I was joking around with bitwise operations, and I notice that ``` int y = 0x7fffffff; printf("%x",-~y); ``` prints ``` 80000000 ``` but if I do ``` printf("%x",-~0x7fffffff); ``` it gives me an error of overflow: ``` main.c:65:17: error: integer overflow in expression [-Werror=overflow] printf("%x",-~0x7fffffff); ``` Does anyone know why-~ydoesn't have the same behavior?
The-~ydoes have the same issue, the compiler just doesn't detect it statically and therefore doesn't warn you about it. When using the integer literal directly, the compiler does the calculation at compile time and realizes that there is an overflow.
I have a dynamic .txt file calledlibrary.txt, which has only one line of data. It is exactly this one: ``` 63Book Title1|Book Author 1|Book Editor 1|2014|English|255|99.989998| ``` I'm trying to read the first integer on the file (in this case, the number "63") using thevoid readInteger()function that I created: ``` void readInteger(){ FILE *arq = fopen("library.txt", "r+"); if(arq == NULL){ printf("ERROR WHILE OPENING FILE!!!"); return; } int x; fread(&x, sizeof(int), 1, arq); printf("%d", x); return; } ``` But the function always keep printing the crazy number "1866609462".Does anyone know what is wrong with my code? Can you guys help me please?
freadis not the right function to use to read formatted data. Usefscanfinstead. ``` fscanf(arq, "%d", &x); ```
I found this piece of code, and I don't understand what it means. Do we have the right to use the array notation like here? ``` double *myList = malloc(3 * sizeof(double)); myList[0] = 1.2; myList[1] = 2.3; myList[2] = 3.4; ``` EDIT : I think this notation uses the fact that the memory address of myList[0],myList[1],myList[2] are consecutive. malloc() doesn't guarantee that the addresses are allocated consecutively.
``` double *myList = malloc(3 * sizeof(double)); ``` It is allocating memory for 3doubletyped data in pointer myList. Following lines assigningdoubletyped data on those locations. ``` myList[0] = 1.2; myList[1] = 2.3; myList[2] = 3.4; ``` myList[2]is equivalent*(myList+2). You need to deallocate this memory usingfreeas follows after its usage: ``` free(myList); ``` mallocallocates consecutive locations in memory.
file.h ``` typedef struct xyz{ unsigned int a; }__attribute__ ((packed,aligned(1))) abc,*ptr; ``` file.c ``` volatile unsigned int *add; add = &abc; ``` ERROR : Expected Expression before 'abc' Can anybody help with this?
You're attempting to take an address of a type, not a variable.&doesn't make much sense with typenames. abcis a typename, not a variable. The compiler is telling you that if you use&then it is expecting to see a variable name next to it so that it can indeed take it's address. If I understood your intentions correctly, in file.c you can try something like this: ``` abc variable; volatile unsigned int *add; add = &variable; ```
``` #include<stdio.h> int main() { int k=35; int a=k==35; printf("%d %dn", k==35, k=50); printf("%d %dn", a,k=50); return 0; } ``` In the firstprintfstatement, whyk==35evaluates to0? I assume this may be because of the fact thatk=50assignment happens beforek==35evaluation. However, I do not understand why theprintfparameters are not evaluated in order ?
``` printf("%d %dn", k==35, k=50); ``` It's unspecified whetherk=50ork==35is evaluated first, so this code has undefined behavior.
``` Struct { int a; struct sample *b; } test; int func(struct test *t1) { if (!t1 || !t1->b) { // Is this statement ok? return _EINVAL } ... } ``` Is it ok to NULL check for nested pointers in a single if-statement? Can I always assume that the left check(!t1 in my example) will be performed first?
Yes, the language rules of C guarantee that if the expressionaina || bis true, thenbis never evaluated. (A similar rule exists fora && bifaevaluates to false.) This is calledshort-circuit evaluation.
I am having trouble parsing this in my head and am totally confused regarding how to parse this declaration: The typedef is something I added to confirm that this declaration does in fact compile. ``` typedef int Display; int (*XSynchronize(Display*,int))(Display*); ```
XSynchronize is a function that takes two arguments: (pointer to Display, int). It returns a pointer to a function that takes one argument: (pointer to Display), and returns an int. Useful link:http://cdecl.org/
I want to get access to the register key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL I can see it in the regedit.exe (I copied above path from there). But code: ``` HKEY hKey; DWORD err = RegOpenKeyExW( HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL", 0, KEY_READ, &hKey ); ``` returns an error 2 (0x2): The system cannot find the file specified .
A 32-bit application running under a 64 - bit system, the registry may be redirected. I don't know whether related to this? Can be added when the first RegOpen KEY_WOW64_64KEY parameters. Or use RegDisableReflectionKey disable redirection.
``` int maxInd (int v[], int N) { int max, ind; for (i = 0; i < N; i++) { if (v[i] > v[i + 1]) { ind = i; } } return ind; } int main() { int v[10] = {1,2,3,4,5,3,7,6,8}; return maxInd(v, 8); } ``` I have this function, where I'm supposed to return the index of the highest int. I think it's correct given that it runs with no errors, but it just doesn't return the index. What am I doing wrong? Sorry for beginner question. Thanks!
sample to fix ``` int maxInd (int v[], int N){ int ind = 0; for(int i=0;i<N;i++){ if(v[i]>v[ind]){ ind=i; } } return ind; } ```
So I want to check if my struct is empty or not. I declare my struct as a variable but DO not allocate memory. text* t; Later on I want to check with an if statement whether my struct is empty or not.if (t!=NULL)does not seem to work asthas an address. Also doing something likeif (t->head != NULL)gives me a segfault as I haven't allocated any memory for the struct. I don't want tomallocas soon as I declaret. Is there a way to check if my struct is empty? Thanks in advance!
Just make sure you initialise the pointer toNULL: ``` text* t = NULL; ``` then later you canmallocon demand, e.g.: ``` if (t == NULL) { t = malloc(sizeof *t); // NB: check for error here - malloc can fail! } t->head = foo; ```
can the fopen() name your own file? For example ``` printf("Enter the name of the file you want to create"); scanf("%s", &name); ``` Then I want the scanned name to be the name of the file I want to create. Is there any way to do this? I know that you can just ``` fp = fopen("name of file.txt","w or a") ``` but what if the user asks for the name of the file itself?
Use the variable as an argument tofopen() ``` fgets(name, sizeof name, stdin); name[strlen(name) - 1] = 0; // remove ENTER from name fp = fopen(name, "w"); // error checking ommited for brevity ``` If you want to add a ".txt" extension to the input, usestrcat()for example ``` fgets(name, sizeof name - 4, stdin); // save space for extension (thanks Cool Guy) name[strlen(name) - 1] = 0; // remove ENTER from name strcat(name, ".txt"); // add extension fp = fopen(name, "w"); // error checking ommited for brevity ```
I see functions likethisthroughout thetorch library's C code: ``` long THTensor_(storageOffset)(const THTensor *self) { return self->storageOffset; } ``` Is this a preprocessor thing, or something lua specific? The idea, I think has something to do with the fact thatstorageOffsetis a method of sorts on theTHTensor"class", but I've never seen this kind of syntax.
It is a preprocessor macro ``` lib/TH/THTensor.h: #define THTensor_(NAME) TH_CONCAT_4(TH,Real,Tensor_,NAME) ``` which leads to... ``` lib/TH/THGeneral.h.in: #define TH_CONCAT_4(x,y,z,w) TH_CONCAT_4_EXPAND(x,y,z,w) ``` and finally... ``` lib/TH/THGeneral.h.in: #define TH_CONCAT_4_EXPAND(x,y,z,w) x ## y ## z ## w ``` Therefore, ``` long THTensor_(storageOffset)(const THTensor *self) ``` ultimately becomes this: ``` long THRealTensor_storageOffset(const THTensor *self) ``` Aren't preprocessors justgrand?
I am attempting to capture input from the user via scanf: ``` char numStrings[5000]; printf("Enter string of numbers:\n\n"); scanf("%s", numStrings); ``` However, the length of the string that is inputted is 5000 characters. The translation limit in c99 is 4095 characters. Do I need to instruct the user to break their input in half or is there a better work around that I cannot think of?
You can input a string a lot larger than that, the stack is at least 1MB in common OS's, it's 8MB's on Linux, so that's the actual limit, 1M is 1024KB so you could for example try with 512KB which is 524288B ``` char string[524288]; scanf("%524287s", string); ``` will be most likely ok, if it's still too small, then usemalloc().
Is it possible to convert a Swift class into C void* pointer? ``` // swift class class MyClass { } var myClass = MyClass() var p: UnsafeMutablePointer<Void> = myClass //<- failed //c function void someSwiftClass(void *context); ``` Thanks
I had similar problem, you can convert this as below. ``` var myClass = MyClass() var classPtr = unsafeBitCast(myClass, UnsafePointer<Void>.self) ``` and your function, ``` func someSwiftClass(voidPointer: UnsafeMutablePointer<Void>) { } ``` If you want to declare constant pointer useUnsafePointer<T>and when your pointer is not constant useUnsafeMutablePointer<T> In C constant pointer -const int *myCpointer Corresponding swift pointer -let mySwiftPointer: UnsafePointer<Int32>
Does anybody know how this works? C Program Source: ``` int main () { float b[] = {1.143139e+27}; puts(b); return 0; } ``` Output: ``` Fell ``` Why would this program display "Fell"?
It has to do with the byte representation of1.143139e+27, which is exactlyFell, but without the terminatingnulbyte. You can do the reverse process, like ``` #include <stdio.h> int main() { char b[] = {'F', 'e', 'l', 'l'}; fprintf(stdout, "%g\n", *(float *)b); return 0; } ``` and even add a terminatingnulbyte, ``` #include <stdio.h> int main() { char b[] = {'F', 'e', 'l', 'l', '\0'}; fprintf(stdout, "%g\n", *(float *)b); return 0; } ``` which means that changingfloat b[] = {1.143139e+27};, tofloat b[] = {1.14314e+27};
I am working on a project which needs to access "Sim Based Menu", I've read several documents listed with SIM Alliance websites, but I couldn't find any way to do that. Please help me if you know that how to access the SIM based menu(Service menu) usingAT commandor any other way. I useSIM900module for this task. Service menu EZ BillEZ Pay
You should take a look at USSD specific AT commands for this. It's not really something to do with your SIM and more to do with your mobile operator. If you know the USSD commands that your operator supports you can send commands like: ``` AT+CUSD=1,"*111*#" ``` You will get then responses from the mobile operator which may or may not include a menu.
Is it possible to convert a Swift class into C void* pointer? ``` // swift class class MyClass { } var myClass = MyClass() var p: UnsafeMutablePointer<Void> = myClass //<- failed //c function void someSwiftClass(void *context); ``` Thanks
I had similar problem, you can convert this as below. ``` var myClass = MyClass() var classPtr = unsafeBitCast(myClass, UnsafePointer<Void>.self) ``` and your function, ``` func someSwiftClass(voidPointer: UnsafeMutablePointer<Void>) { } ``` If you want to declare constant pointer useUnsafePointer<T>and when your pointer is not constant useUnsafeMutablePointer<T> In C constant pointer -const int *myCpointer Corresponding swift pointer -let mySwiftPointer: UnsafePointer<Int32>
Does anybody know how this works? C Program Source: ``` int main () { float b[] = {1.143139e+27}; puts(b); return 0; } ``` Output: ``` Fell ``` Why would this program display "Fell"?
It has to do with the byte representation of1.143139e+27, which is exactlyFell, but without the terminatingnulbyte. You can do the reverse process, like ``` #include <stdio.h> int main() { char b[] = {'F', 'e', 'l', 'l'}; fprintf(stdout, "%g\n", *(float *)b); return 0; } ``` and even add a terminatingnulbyte, ``` #include <stdio.h> int main() { char b[] = {'F', 'e', 'l', 'l', '\0'}; fprintf(stdout, "%g\n", *(float *)b); return 0; } ``` which means that changingfloat b[] = {1.143139e+27};, tofloat b[] = {1.14314e+27};
I am working on a project which needs to access "Sim Based Menu", I've read several documents listed with SIM Alliance websites, but I couldn't find any way to do that. Please help me if you know that how to access the SIM based menu(Service menu) usingAT commandor any other way. I useSIM900module for this task. Service menu EZ BillEZ Pay
You should take a look at USSD specific AT commands for this. It's not really something to do with your SIM and more to do with your mobile operator. If you know the USSD commands that your operator supports you can send commands like: ``` AT+CUSD=1,"*111*#" ``` You will get then responses from the mobile operator which may or may not include a menu.
This is the code I am trying to understand: ``` #include <unistd.h> #include <fcntl.h> #include <stdio.h> int main(void){ unsigned long word; ssize_t nr; int file = open("koray.txt",O_RDONLY); nr = read(file,&word,sizeof(unsigned long)); printf("%li\n",word); } ``` koray.txthas only 1 character that isk. When I run the program I see: ``` koray@koray-VirtualBox:~$ ./a.out 4195435 ``` What is this large value?
There will be random garbage in thewordvariable because you never initialized it. Thenreadwill only be able to get one byte from the file (nrprobably returned 1, you should check that!) which saves one byte, but thewordvariable still has 3-7 bytes of uninitialized junk in it that gets printed.
``` #include <stdio.h> #include <conio.h> void main () { double d,a,b; printf ("Enter number"); scanf ("%d%d",&a,&b); d=b/a; printf ("\n %lf",d); getch(); } ``` I don't know what is wrong . It doesn't give answer in float or double. Please suggest changes in c only because i am currently learning programming. When it divides 2/1 gives 2 but 1/2 gives 0.000000
Use%lfin thescanfsinceaandbare of typedouble. %dis for integer input.
I am trying to read in from stdin and then print each char from each string but it will not print anything for some reason... ``` #include <stdio.h> #include <string.h> int main(void){ int i; char string[10]; while (fgets(string,10,stdin)!=NULL){ for(i=0;i<strlen(string);i++);{ printf("%c",string[i]); } strcpy(string,""); } return 0; } ```
You have an extraneous semicolon. Try this: ``` ... for(i=0;i<strlen(string);i++){ for... ``` Notice the lack of a ";" before the body of the loop. The body of the loop in your code is empty because it's just a semicolon. The part that you intend as the body of the loop is only executed once afterwards. During that one execution you're just printing the null character at the end of string.
I have these macros: ``` #define TRUE 1; #define FALSE 0; ``` I want to use them in an if condition, for example: ``` if (functionThatReturnsIntZeroOrOne() == FALSE) do_something(); ``` but I get such an error message: ``` "Expected expression". ``` What do I do wrong?
You definedFALSEto be0;, define it to be0(#define FALSE 0, without a semicolon). The semicolon is included in the define, soFALSEgets replaced with0;which puts a semicolon in your if conditional.
data |= (1 << 3)sets bit (3) without disrupting other bits.data &= ~(1 << 4)resets bit (4) without disrupting other bits. How can I accomplish both tasks in a single instruction? (As this is really only for readability, I plan on#defineing this in a cute way like#define gpioHigh(x) <insert code>. The alternative is to figure out how to correctly pass a gpio pointer into functions that I write expressly for this purpose, but eff that) Thanks! Mike
It's not possible in a single instruction. This is because there are 3 possible operations you need to do on the different bits: Set them (bit 3)Clear them (bit 4)Leave them alone (all the other bits) How can you select from one of three possibilities with a bitmask made up of binary digits? Of course, you can do it with one line e.g: ``` data = (data | (1 << 3)) & ~(1 << 4) ```
Can we understand if there is a variable mentioned/created/exists ?I mean something like that: ``` //..Some codes int main(){ int var1; float var2; char var3; cout << isExist("var1") << endl;//Or isExist(/*Something related with var1*/) cout << isExist("var2") << endl; cout << isExist("var3") << endl; cout << isExist("var456") << endl;//There is no variable named with var456 return 0; } ``` Output: ``` true true true false ```
No. C and C++ do not supportreflection.
A.while (*t) *s++ = *t++;B.do { *s = *t++; } while (*s++);C.while (*s) *s++ = *t++;D.do { *s++ = *t++; } while (*t); The answer is B, why others are wrong?
A.) vs. B.) B will always copy the first value before checking if the result is 0.A will do the test first, and if the result is 0, it will stop before ever copying the first value. C.) vs. B.) Similar to A, C does the test first, and will never copy a value if the first value is 0. D.) vs. B.) After copying a value, T is incremented, then the test is done against T (the next value), instead of the previous T.
I am a newbie and learning the pointer now. I encountered this problem: function 1: ``` void swap(int *x, int *y) { int *p; *p=*x;*x=*y;*y=*p; } ``` function 2: ``` void swap(int *x, int *y){ *x=*x+*y;*y=*x-*y;*x=*x-*y; } ``` I know the function 2 can work well to swap two variables but function 1 cannot. Why? Thanks for your answer. :)
In function1, you are using a pointerpthat isn't pointing to a valid address. You don't need a pointer here: ``` void swap(int *x, int *y) { int p; p=*x;*x=*y;*y=p; } ```
I need a single recursive function to compute the seriesS=1! + 2! + 3! + ...+n!. I've done it using 2 functions. ``` void main() { int terms=4; printf(sum(terms)); //outputs 33 /* terms is the number of terms in the series e.g. terms=3 outputs 9, 4 outputs 33 */ } int fac(int n) { return n<2 ? 1 : n * fac(n-1) ; } int sum(int terms) { return terms>0 ? (fac(terms) + sum(terms-1)):0 ; } ```
This is the simplest I could get it: ``` int sum_fac(int target, int counter) { return (target == counter) ? target : counter * (1 + sum_fac(target, counter + 1)); } ``` Which when called like this: ``` int main() { for (int i = 1; i < 10; i++) { printf("%d: %d\n", i, sum_fac(i, 1)); } } ``` Outputs this: ``` 1: 1 2: 3 3: 9 4: 33 5: 153 6: 873 7: 5913 8: 46233 9: 409113 ```
This question already has answers here:Difference between int* p and int *p declaration [duplicate](3 answers)Closed8 years ago. I am learning graph (Adjacency List) from geeks to geeks and I see this code: ``` // A structure to represent an adjacency list node struct AdjListNode { int dest; struct AdjListNode* next; }; // A structure to represent an adjacency liat struct AdjList { struct AdjListNode *head; // pointer to head node of list }; // A structure to represent a graph. A graph is an array of adjacency lists. // Size of array will be V (number of vertices in graph) struct Graph { int V; struct AdjList* array; }; ``` I would like to know the difference betwee: struct AdjListNode* next;andstruct AdjListNode *head;andstruct AdjListNode * head;
They are the same, only different styles of writing "a pointer to a struct AdjListNode".
I'm new to arduino and it's programing language. I learnt that we can't have methods returning arrays, but we can use pointers as an alternative. So I have this method: ``` byte SUM(byte A, byte B, bool Cyi, byte *sum, bool *Cyo) { bool d0; bool d1; for(int i = 0; i < 8; ++i) { d0 = bitRead(A,i); d1 = bitRead(B,i); bitWrite(*sum,i,d0 ^ d1 ^ Cyi); *Cyo = d0 && d1 || Cyi && (d0 ^ d1); Cyi = Cyo; } } ``` I'am new to pointers but I guess the problem here is that bitWrite method does not accept a pointer? I don't know what do to next and I need some help. Thanks in advance.
Adruino is not a programming language but a microcontroler platform for which you could write code in c. you wrote in your code: ``` Cyi = Cyo; ``` but Cyi is of type "bool" and Cyo a type of "bool *" correct it with ``` Cyi = *Cyo; ```
Consider the C code below: ``` #include <stdio.h> int main() { int i = 012; printf("%d", i); } ``` On O/P the value ofiis printed as 10. I know (012)8= (10)10. But I'm confused about how C storesintvariable values. Can anybody explain it to me?
They are stored in binary, you can use many representations to define them, but in the end it's the binary representation that is used.
``` int random; random=rand(); if(random<90) var[x][y]=2; else var[x][y]=4; ``` How can I generate 2 at a percentage of 90% and 4 at 10 %?
Your basic idea is right, but you got the values wrong.rand()yields a non-negative pseudo-random number smaller thenRAND_MAX, which is a high number and guaranteed to be at least 65535. You can get a random floating-point number between 0 and 1 with: ``` rand() / (RAND_MAX + 1.0) ``` If that is below 90% or 0.9, you want 2, otherwise 4. So: ``` var[x][y] = (rand() / (RAND_MAX + 1.0) < 0.9) ? 2 : 4; ```
I'm readinga journal article about Real-Time Concurrent C, and it mentions in the abstract (so any of you can see the context through that link as well) that "Concurrent C, is a parallel superset of C (and of C++)". Now I know what a superset is, but what do they mean by a "parallel superset" when referring to programming languages?
They're claiming two things, not one thing that is "modified". It's like saying "a quick red car"; the car is quickandred, it's not having a fast color. It's parallel, because it supports parallel programmingIt's a super-set, because every valid C or C++ program is also a valid Concurrent C program. That's a bit weird too, since not every valid C program is a valid C++ program.
I'm changing a program written in C. For these changes I need a counter (variable int). When the run stops, I need the value of this counter in the following run of the program. (even if the pc is restarted in between). What is the best way to store this value? I was thinking about the following : storing it as a registry-value, writing it to a file (not preferred, somebody might delete this file), using persistent variables (but I can't find many information on these). Or, are there other ways to keep this variable? The program has to run in a Windows environment and in a Linux environment (as it does now).
Store it in a file. If you want to protect the file from accidental deletion, have its name start with a period on Linux (.myfile) or mark it as "hidden" on Windows. If you want to protect it against more than just accidental deletion, the registry is no better than a file.
I am trying to divide two numbers from an integer(out of a array). The problem is that array must be integers! And I am trying to show a percentage. And as you all know C rounds down so all my answers are zero. ``` float response; float response1= a[0][1]; float response2= a[0][0];; response = response1/response2*100 ; ``` This is my solution. Any good idea's on how to improve it ?
You could cast the values: ``` response = (float)(a[0][1]) / (float)(a[0][0]) * 100 ``` This accomplishes the same thing as your explicitly introduced variables (and if you need an intergral response, you can wrap this in another layer of casting).
I have 3 different algorithms which all calculate the same stuff. My goal is to compare all three algorithms, i.e. clock cycles, "how intensive it is for the processor", time needed to get the final result, the overall performance etc... How can I see/get/analyze all of this information? I am programming in Matlab and in C-language in code composer studio for an embedded system. EDIT: memory usage/management would be usefull as well for the embedded system especially
First you can compare the size of your Output-files. Most times the bigger one is slower. Get the exactly clock cycles is not easy. you must know how many clock cycles your Assembler command Needs and calculate it for your code. If you are running it directly on your Hardware, you can toggle a port at the start and end Point and do a Timing measurement. (Regard there are may Interrupts, that can slow you down)
I'm changing a program written in C. For these changes I need a counter (variable int). When the run stops, I need the value of this counter in the following run of the program. (even if the pc is restarted in between). What is the best way to store this value? I was thinking about the following : storing it as a registry-value, writing it to a file (not preferred, somebody might delete this file), using persistent variables (but I can't find many information on these). Or, are there other ways to keep this variable? The program has to run in a Windows environment and in a Linux environment (as it does now).
Store it in a file. If you want to protect the file from accidental deletion, have its name start with a period on Linux (.myfile) or mark it as "hidden" on Windows. If you want to protect it against more than just accidental deletion, the registry is no better than a file.
I am trying to divide two numbers from an integer(out of a array). The problem is that array must be integers! And I am trying to show a percentage. And as you all know C rounds down so all my answers are zero. ``` float response; float response1= a[0][1]; float response2= a[0][0];; response = response1/response2*100 ; ``` This is my solution. Any good idea's on how to improve it ?
You could cast the values: ``` response = (float)(a[0][1]) / (float)(a[0][0]) * 100 ``` This accomplishes the same thing as your explicitly introduced variables (and if you need an intergral response, you can wrap this in another layer of casting).
I have 3 different algorithms which all calculate the same stuff. My goal is to compare all three algorithms, i.e. clock cycles, "how intensive it is for the processor", time needed to get the final result, the overall performance etc... How can I see/get/analyze all of this information? I am programming in Matlab and in C-language in code composer studio for an embedded system. EDIT: memory usage/management would be usefull as well for the embedded system especially
First you can compare the size of your Output-files. Most times the bigger one is slower. Get the exactly clock cycles is not easy. you must know how many clock cycles your Assembler command Needs and calculate it for your code. If you are running it directly on your Hardware, you can toggle a port at the start and end Point and do a Timing measurement. (Regard there are may Interrupts, that can slow you down)
This code searches for a set of numbers in a file; if it finds it, it displays the line where it found it. I want this code to search into more than 1 file. After it finished searching in the 1st file, it'll start searching in the second one and so on. This is the output: ``` #include <stdio.h> #include <string.h> #include <stdlib.h> int busca(char *str, char *archNom); void archivo(char *nomArchivo); int main(int argc, char *argv[]) { int result, errno; if(argc < 3 || argc > 3) { archivo(argv[0]); exit(1); } result = busca(argv[1], argv[2]); ```
You could iterate overargv, from1toargc - 2(excluding the first and last elements), and then just runbusca(argv[n], argv[argc - 1])once for each item in theargvarray. You'd have to keep track of the result to determine wether an error occurred, perhaps usingmin()ormax().
Why does arithmetic in C saturate float but not integers? Is it the underlying processor itself?
It doesn't. From 6.5/5: If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined. So, doing a float calculation that would result in a value larger thanFLT_MAXcauses undefined behaviour. When the behaviour is undefined, anything can happen. What you are seeing is your compiler generating a CPU or FPU instruction that works for well-defined sums and does not care about overflows.
This is my JNI C code: ``` JNIEXPORT jint JNICALL Java_org_avuna_httpd_util_CLibJNI_bind(JNIEnv * this, jclass cls, jint sockfd, jint family, jstring path, jint len) { struct sockaddr_un sun; sun.sun_family = family; const char *npath = (*this)->GetStringUTFChars(this, path, 0); sun.sun_path = npath; return bind(sockfd, sun, sizeof(&npath)); } ``` I just guessed unsuccessfully (sizeof(&npath)) how to get the length. I'm not well versed in C, but I figure there is a way to get a length out of a jstring. Google yields nothing, what basic thing am I missing?
Since the type of the variable isconst char *it suggests that it's anulterminated string, hence ``` size_t length = strlen(npath); ``` should be enough. Although, your call tobind()is wrong, you shold pass the size of the address structure, for which ``` return bind(sockfd, sun, sizeof(sun)); ``` should be correct.
I am trying to use_crtBreakAllocin the Watch window as suggested inthislink, but the value line says that 'identifier "_crtBreakAlloc" is unidentified' and it simply does not work. What am I doing wrong? I'm using Visual Studio by the way. An example of code: ``` #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include <malloc.h> int main() { int *arr = (int*)malloc(10 * sizeof(int)); //breakpoint here free(arr); return 0; } ``` I then write _crtBreakAlloc into the Name field of the Watch window and hit enter when encountering the breakpoint.
_crtBreakAlloc will be reported as unidentified if the ucrtbased.dll symbols are not loaded. I had this problem because I do not automatically load my symbols. You can go in your module list and manually Load symbols for ucrtbased.dll and then _crtBreakAlloc should show up and work.
Why does arithmetic in C saturate float but not integers? Is it the underlying processor itself?
It doesn't. From 6.5/5: If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined. So, doing a float calculation that would result in a value larger thanFLT_MAXcauses undefined behaviour. When the behaviour is undefined, anything can happen. What you are seeing is your compiler generating a CPU or FPU instruction that works for well-defined sums and does not care about overflows.
This is my JNI C code: ``` JNIEXPORT jint JNICALL Java_org_avuna_httpd_util_CLibJNI_bind(JNIEnv * this, jclass cls, jint sockfd, jint family, jstring path, jint len) { struct sockaddr_un sun; sun.sun_family = family; const char *npath = (*this)->GetStringUTFChars(this, path, 0); sun.sun_path = npath; return bind(sockfd, sun, sizeof(&npath)); } ``` I just guessed unsuccessfully (sizeof(&npath)) how to get the length. I'm not well versed in C, but I figure there is a way to get a length out of a jstring. Google yields nothing, what basic thing am I missing?
Since the type of the variable isconst char *it suggests that it's anulterminated string, hence ``` size_t length = strlen(npath); ``` should be enough. Although, your call tobind()is wrong, you shold pass the size of the address structure, for which ``` return bind(sockfd, sun, sizeof(sun)); ``` should be correct.
I am trying to use_crtBreakAllocin the Watch window as suggested inthislink, but the value line says that 'identifier "_crtBreakAlloc" is unidentified' and it simply does not work. What am I doing wrong? I'm using Visual Studio by the way. An example of code: ``` #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include <malloc.h> int main() { int *arr = (int*)malloc(10 * sizeof(int)); //breakpoint here free(arr); return 0; } ``` I then write _crtBreakAlloc into the Name field of the Watch window and hit enter when encountering the breakpoint.
_crtBreakAlloc will be reported as unidentified if the ucrtbased.dll symbols are not loaded. I had this problem because I do not automatically load my symbols. You can go in your module list and manually Load symbols for ucrtbased.dll and then _crtBreakAlloc should show up and work.
I wrote this simple and short code in C and can't get it to work properly: ``` #include <stdio.h> int main(void) { char var1[2]; int var2, var3; unsigned char var4; scanf("%s %d %d %d", var1, &var2, &var3, &var4); printf("%s %d %d %d\n", var1, var2, var3, var4); return 0; } ``` If I inputP2 45 45 200, I getP2 45 0 200, I can't understand whyvar3does not receive its assigned value. Input:P2 45 45 200 Expected output:P2 45 45 200 Output:P2 45 0 200
Forvar4, you declare it asunsigned char, but read it using a%dformat specifier, which invokes undefined behavior. I would recommend using%hhuas the format specifier for that field, if your compiler supports it. Or you could declarevar4as anint, and then assign it to anunsigned charvariable after thescanf()call.
In the following segment of code: ``` if (buffer + strlen(buffer) >= len -1) beep(); ``` note:lenis anint,bufferis a pointer tochar. I don't understand how would someone add buffer (a pointer) to thestrlen()of a string and compare it tolen. Can any one please help me. note: the actual code link ishttp://www.finseth.com/craft/#intro.1.4any help will be greatly appreciated.
This code is illegal. A pointer may not be compared to an integer (other than a constant0). The compiler should have generated an error message. Some compilers may generate "only" a warning in the default configuration, and perform a nonsensical comparison at runtime, but you should treat this as an error. You could report this bug to the author of this page; although if basic compilation errors get through their QA process I hate to think what other mistakes might also be present.
Is it possible to usefgets()to save different words divided by whitespace and then find each word? For example let's say I have this: ``` char words[100]; fgets(words,100,stdin); ``` and then I have to find each word to use it in the rest of my program. How can I do that?
You can usestrtok_ror you could use thepcrelibrary if you want to do things with regex. ``` char *save_ptr; char *word = strtok_r(words, " \t", save_ptr); ``` and then repeated other calls to ``` word = strtok_r(words, " \t", save_ptr); ``` untilword == NULL
Consider the following code ``` #include<stdio.h> int main() { int a[5]; int *ptr=a; printf("\n%u", &ptr); ++ptr; printf("\n%u", &ptr); } ``` On Output I'm getting same address value, Why pointer address is not incrementing.
The pointer is being incremented. The problem is that you are looking at theaddressof the pointer itself. The address of a variable cannot change. You mean to look at thevalueof the pointer, that is, the address it stores: ``` printf("\n%p", ptr); ```
I have a text file that I want to read using C. It contains lines in this format:%d %d (%d or %lf). An example of 3 lines: ``` 1 0 44 2 0 84.13 3 1 15.07 ``` But the last number can be eitherintordouble, arbitrary. How can I read from the text file regardless of the data type?
Since float can hold an integer but not vice versa. Just read the data like a float and check if it is an integer using something like ``` if(ceilf(f) == f) { i=(int)f; } //Here i is an integer and f is the float you read using %f ``` To see more methods on how to check if a float is int see Checking if float is an integer
I m using many times ``` curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg_out); ``` in my code before I m cleaning withcurl_easy_cleanup()functions. Does CURL make a memory copy (dynamic memory) of themsg_outin his environment ?
No, it does not make a copy by default, and this is stated in theCURLOPT_POSTFIELDSdocumentation: The data pointed to is NOT copied by the library: as a consequence, it must be preserved by the calling application until the associated transfer finishes. This behaviour can be changed (so libcurl does copy the data) by setting theCURLOPT_COPYPOSTFIELDSoption.
I'm learning C and I don't understand why I get a buffer overflow copying the string. ``` pathValue = getenv("PATH"); pathlength = strlen(pathValue); pathValue2 = malloc(sizeof(pathValue)); strncpy(pathValue2, pathValue, pathlength); ``` Can you tell me how it should be done?
``` pathlength = strlen(pathValue); pathValue2 = malloc(sizeof(pathValue)); strncpy(pathValue2, pathValue, pathlength); ``` Firstly this: ``` pathValue2 = malloc(sizeof(pathValue)); ``` sizeof may or may not be what you're after, we need to see pathValue to be sure. You may mean this: ``` pathValue2 = malloc(strlen(pathValue)+1); ``` Also note the +1, this adds space for the NULL terminator. Lastly: ``` strncpy(pathValue2, pathValue, pathlength); ``` Just use this: ``` strcpy(pathValue2, pathValue); ```
How would I be able to add data from different nodes together?Inserttotree()just creates a new node and enters thedatavalue specified. So basically I'm just trying to add2and3together in thecountquantity()function. ``` typedef struct tree_s tree_t; typedef int data_t; struct tree_s { data_t data; tree_t *left; tree_t *right; }; int main(int argc, char **argv){ tree_t *tree; tree = NULL; tree = insertToTree(tree, 3); tree = insertToTree(tree, 2); printf("Total: %d\n", countQuantity(tree)); return 0; } int countQuanity(tree_t *tree){ int i = 0; if(tree == NULL){ return i; } i = tree->data + countQuantity(tree->left); i = tree->data + countQuantity(tree->right); return i; } ```
The result is a sum of the node's value and the computed values of both subtrees: ``` i=tree->data + countQuantity(tree->left) + countQuantity(tree->right) ```
I'm currently coding a Python C-Extension to perform some calculations in C instead of Python. It works just fine, I already got some nice results, but the point is, I get the following error: ``` NULL result without error in PyObject_Call ``` It occurs sometimes, not always, when I want to create an instance of the "C Python Object" I created. The call looks something like the following: ``` import c_class obj = c_class.dummy(arg1, arg2, arg3); ``` Does anyone have any suggestions? I don't know where this error comes from, since it works from time to time.. I'm kind of lost here.
When you returnNULLfrom a c function exposed to python you must set the error message before, since returningNULLmeans an error happened. If an error happened and you are returningNULLbecause of that then, usePyErr_SetString(), if no error happened, then use ``` Py_RETURN_NONE; ```
I would like to execute some assembly instructions based on a define from a header file. Let's say intest.hI have#define DEBUG. Intest.asmI want to check somehow like#ifdef DEBUGdo something... Is such thing possible? I was not able to find something helpful in the similar questions or online.
Yes, you can run the C preprocessor on your asm file. Depends on your build environment how to do this.gcc, for example, automatically runs it for files with extension.S(capital). Note that whatever you include, should be asm compatible. It is common practice to conditionally include part of the header, using#ifndef ASSEMBLYor similar constructs, so you can have C and ASM parts in the same header.
I encountered code that is not clear for me. Therefore I am asking for help. Can anyone please explain me what the following code means: ``` typedef void (* __data16 functionpointer)(void); const functionpointer bsloader = (functionpointer)(0x1000); ``` I am not asking about __data16, this is the memory type specifier which informs the compiler that the functionpointer resides in 16bit memory space.
In the first line, you are establishing thatfunctionpointeris a pointer to afunctiontaking no arguments, returning avoid.__data16is some specifier as you already know. In the second line, you arecasting0x1000to the typefunctionpointer.bsloaderis the name you're giving that pointer. It's your job to check that this cast is valid. If it isn't then the behaviour of your program is undefined. You could then writebsloader();. That would invoke the function at address0x1000.
I have a set of points in a 2D plane. I need to detect only the points that belong to the shape that borns from the union of this subset of points in order to cover the largest area: that is, the boundary points. The following figure is an example: The red points are those ones I need to detect.
What you need is calledConvex hull.A lot of algorithms existto calculate it.
I have got the following compile error while compiling theFFmpeg-Vitamio. My OS isMac OS X 10.10.9 NDK version:android-ndk-r10d Gcc version: ``` $gcc --version Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.1.1 Thread model: posix ``` Error message: ``` libavformat/fd.c:59:9: error: implicit declaration of function 'lseek64' is invalid in C99 [-Werror,-Wimplicit-function-declaration] return lseek64(fd, pos, whence); ```
for a linux system, use: ``` #define _LARGEFILE64_SOURCE /* See feature_test_macros(7) */ #include <sys/types.h> #include <unistd.h> ``` to have a proper prototype for lseek64 I'm not sure how this will relate to the mac OS and using the arm-linux-antroideabi-gcc tool
I have seen a separation ofheader filesin two Visual Studio folders,Include FilesandHeader files, where headers with public API have been in Include Files folder and others in Header files folder. Is the term "include file" used and recognized this way? What I have seen is just the local project agreement or common practise?
There is no real distinction between the two. They're called include files almost certainly because you include them. They're called header files because they contain cut-down (header) information about the things they describe. Either term will do, and seasoned C (and C++) coders should understand what you mean. For what it's worth, the C standard uses "header names" or "headers" to describe them, since they're not required to be in files at all.
I would like to ask what is the behaviour of the C language on the following: ``` int n = 0; . . // n in this block may change value to something else but a (positive) number . . if(n) { // do something } . . ``` So what theif(n)means when thenis an integer?
As per theC11standard document, chapter 6.8.4,Selection statements, if ( expression ) statementA selection statement selects among a set of statements depending on the value of a controlling expression. and from chapter 6.8.4.1,Theifstatement In both forms, the first substatement is executed if the expression compares unequal to 0. So, essentially, here,if(n)will Execute the next statement (block) ifif(n)results TRUE (nunequal to 0, includes both+veand-vevalues)Skip the the next statement (block) ifif(n)results FALSE (nequal to 0)
I m using many times ``` curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg_out); ``` in my code before I m cleaning withcurl_easy_cleanup()functions. Does CURL make a memory copy (dynamic memory) of themsg_outin his environment ?
No, it does not make a copy by default, and this is stated in theCURLOPT_POSTFIELDSdocumentation: The data pointed to is NOT copied by the library: as a consequence, it must be preserved by the calling application until the associated transfer finishes. This behaviour can be changed (so libcurl does copy the data) by setting theCURLOPT_COPYPOSTFIELDSoption.
I'm learning C and I don't understand why I get a buffer overflow copying the string. ``` pathValue = getenv("PATH"); pathlength = strlen(pathValue); pathValue2 = malloc(sizeof(pathValue)); strncpy(pathValue2, pathValue, pathlength); ``` Can you tell me how it should be done?
``` pathlength = strlen(pathValue); pathValue2 = malloc(sizeof(pathValue)); strncpy(pathValue2, pathValue, pathlength); ``` Firstly this: ``` pathValue2 = malloc(sizeof(pathValue)); ``` sizeof may or may not be what you're after, we need to see pathValue to be sure. You may mean this: ``` pathValue2 = malloc(strlen(pathValue)+1); ``` Also note the +1, this adds space for the NULL terminator. Lastly: ``` strncpy(pathValue2, pathValue, pathlength); ``` Just use this: ``` strcpy(pathValue2, pathValue); ```
How would I be able to add data from different nodes together?Inserttotree()just creates a new node and enters thedatavalue specified. So basically I'm just trying to add2and3together in thecountquantity()function. ``` typedef struct tree_s tree_t; typedef int data_t; struct tree_s { data_t data; tree_t *left; tree_t *right; }; int main(int argc, char **argv){ tree_t *tree; tree = NULL; tree = insertToTree(tree, 3); tree = insertToTree(tree, 2); printf("Total: %d\n", countQuantity(tree)); return 0; } int countQuanity(tree_t *tree){ int i = 0; if(tree == NULL){ return i; } i = tree->data + countQuantity(tree->left); i = tree->data + countQuantity(tree->right); return i; } ```
The result is a sum of the node's value and the computed values of both subtrees: ``` i=tree->data + countQuantity(tree->left) + countQuantity(tree->right) ```
I'm currently coding a Python C-Extension to perform some calculations in C instead of Python. It works just fine, I already got some nice results, but the point is, I get the following error: ``` NULL result without error in PyObject_Call ``` It occurs sometimes, not always, when I want to create an instance of the "C Python Object" I created. The call looks something like the following: ``` import c_class obj = c_class.dummy(arg1, arg2, arg3); ``` Does anyone have any suggestions? I don't know where this error comes from, since it works from time to time.. I'm kind of lost here.
When you returnNULLfrom a c function exposed to python you must set the error message before, since returningNULLmeans an error happened. If an error happened and you are returningNULLbecause of that then, usePyErr_SetString(), if no error happened, then use ``` Py_RETURN_NONE; ```
I would like to execute some assembly instructions based on a define from a header file. Let's say intest.hI have#define DEBUG. Intest.asmI want to check somehow like#ifdef DEBUGdo something... Is such thing possible? I was not able to find something helpful in the similar questions or online.
Yes, you can run the C preprocessor on your asm file. Depends on your build environment how to do this.gcc, for example, automatically runs it for files with extension.S(capital). Note that whatever you include, should be asm compatible. It is common practice to conditionally include part of the header, using#ifndef ASSEMBLYor similar constructs, so you can have C and ASM parts in the same header.
I encountered code that is not clear for me. Therefore I am asking for help. Can anyone please explain me what the following code means: ``` typedef void (* __data16 functionpointer)(void); const functionpointer bsloader = (functionpointer)(0x1000); ``` I am not asking about __data16, this is the memory type specifier which informs the compiler that the functionpointer resides in 16bit memory space.
In the first line, you are establishing thatfunctionpointeris a pointer to afunctiontaking no arguments, returning avoid.__data16is some specifier as you already know. In the second line, you arecasting0x1000to the typefunctionpointer.bsloaderis the name you're giving that pointer. It's your job to check that this cast is valid. If it isn't then the behaviour of your program is undefined. You could then writebsloader();. That would invoke the function at address0x1000.
I have a set of points in a 2D plane. I need to detect only the points that belong to the shape that borns from the union of this subset of points in order to cover the largest area: that is, the boundary points. The following figure is an example: The red points are those ones I need to detect.
What you need is calledConvex hull.A lot of algorithms existto calculate it.
I have got the following compile error while compiling theFFmpeg-Vitamio. My OS isMac OS X 10.10.9 NDK version:android-ndk-r10d Gcc version: ``` $gcc --version Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) Target: x86_64-apple-darwin14.1.1 Thread model: posix ``` Error message: ``` libavformat/fd.c:59:9: error: implicit declaration of function 'lseek64' is invalid in C99 [-Werror,-Wimplicit-function-declaration] return lseek64(fd, pos, whence); ```
for a linux system, use: ``` #define _LARGEFILE64_SOURCE /* See feature_test_macros(7) */ #include <sys/types.h> #include <unistd.h> ``` to have a proper prototype for lseek64 I'm not sure how this will relate to the mac OS and using the arm-linux-antroideabi-gcc tool
I have seen a separation ofheader filesin two Visual Studio folders,Include FilesandHeader files, where headers with public API have been in Include Files folder and others in Header files folder. Is the term "include file" used and recognized this way? What I have seen is just the local project agreement or common practise?
There is no real distinction between the two. They're called include files almost certainly because you include them. They're called header files because they contain cut-down (header) information about the things they describe. Either term will do, and seasoned C (and C++) coders should understand what you mean. For what it's worth, the C standard uses "header names" or "headers" to describe them, since they're not required to be in files at all.
I would like to ask what is the behaviour of the C language on the following: ``` int n = 0; . . // n in this block may change value to something else but a (positive) number . . if(n) { // do something } . . ``` So what theif(n)means when thenis an integer?
As per theC11standard document, chapter 6.8.4,Selection statements, if ( expression ) statementA selection statement selects among a set of statements depending on the value of a controlling expression. and from chapter 6.8.4.1,Theifstatement In both forms, the first substatement is executed if the expression compares unequal to 0. So, essentially, here,if(n)will Execute the next statement (block) ifif(n)results TRUE (nunequal to 0, includes both+veand-vevalues)Skip the the next statement (block) ifif(n)results FALSE (nequal to 0)
This code is working good. ``` #include<stdio.h> #include<conio.h> void show() { printf("Show function"); } void main() { show(); } ``` but this requires some more. ``` #include<stdio.h> #include<conio.h> void main() { show(); } void show() { printf("Show function"); } ``` That is.. I have to declare a "Show" function in main. why i need to do this?
You need to declareshowbeforemainbecausemaincallsshowbefore it is defined. You can do this with a function prototype as shown below ``` #include <stdio.h> // You reference show in main but the compiler will see main before show // This is required to let the compiler know show will later be defined void show(); void main() { show(); } void show() { printf("Show function"); } ```
I would like the following behavior without the use ofsystem ``` int ret = system("less -V > /dev/null 2>&1"); if (ret == 0) { printf("The less executable was found.\n"); } ``` I need the variableretto be 0 if less is installed on the system, but without using the call tosystem. Can it be done withexecor similar?
You can usesystem("which less")to determine whetherlessis installed. This avoids attempting to invokelessif it isn't installed. If you don't want to usesystemat all, you'll have to re-implement the functionality ofwhichin your program: i.e., usegetenvto get thePATHvariable and try appending/lessto each path and invokingstaton the resulting file to determine if it exists and is executable.
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.Closed8 years ago.Improve this question I am working on a school project. Unfortunately, I just ran a compile like so: gcc -o file.c file.o I forgot to put the output executable name, and now my previous C file is gone. Is there a way to get this file back? I wrote a lot of code that is gone. Program was written on a Unix server in C. Thank you!
Is there a way to get this file back? There is if you were using a version control system or made a backup. If not, you're likely out of luck.
I want to assign the first two values from the hash array to the salt array. ``` char hash[] = {"HAodcdZseTJTc"}; char salt[] = {hash[0], hash[1]}; printf("%s", salt); ``` However, when I attempt this, the first two values are assigned and then all thirteen values are also assigned to the salt array. So my output here is not: ``` HA ``` but instead: ``` HAHAodcdZseTJTC ```
saltis not null-terminated. Try: ``` char salt[] = {hash[0], hash[1], '\0'}; ```
I disassembled the following C call ``` exit(EXIT_SUCCESS); ``` and found out that it calls the exit procedure at an assembly level ``` call exit ``` Where can I find the source code for this procedure so that I can study it and find out exactly what is happening?
In theC library of your system. Which then eventually invokes youroperating system. The links are for linux with glibc, you forgot to mention your environment.
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.Closed8 years ago.Improve this question The C standard library for example has some standard functions likeprintf,. What exactly the relation between the standard library and the run time library ? Is the run time library just the dll's (under windows) part of the standard library? so when I call theprintfin my program , the compiler links my program "dynamically" to the dll file(MSVCR100D.dll) that exports theprintfso both my program and that dll are loaded in memory at loading time ? is that dll (MSVCR100D.dll) that has the exportedprintfis exactly the C run time library or the run time library is something else???
In the case of MSVC, the runtime library MSVCRxxx.DLL contains all of the code for the C/C++ standard library.
I disassembled the following C call ``` exit(EXIT_SUCCESS); ``` and found out that it calls the exit procedure at an assembly level ``` call exit ``` Where can I find the source code for this procedure so that I can study it and find out exactly what is happening?
In theC library of your system. Which then eventually invokes youroperating system. The links are for linux with glibc, you forgot to mention your environment.
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.Closed8 years ago.Improve this question The C standard library for example has some standard functions likeprintf,. What exactly the relation between the standard library and the run time library ? Is the run time library just the dll's (under windows) part of the standard library? so when I call theprintfin my program , the compiler links my program "dynamically" to the dll file(MSVCR100D.dll) that exports theprintfso both my program and that dll are loaded in memory at loading time ? is that dll (MSVCR100D.dll) that has the exportedprintfis exactly the C run time library or the run time library is something else???
In the case of MSVC, the runtime library MSVCRxxx.DLL contains all of the code for the C/C++ standard library.
I would like to count the number of lines in an ASCII text file. I thought the best way to do this would be by counting the newlines in the file: ``` for (int c = fgetc(fp); c != EOF; c = fgetc(fp)) { /* Count word line endings. */ if (c == '\n') ++lines; } ``` However, I'm not sure if this would account for the last line on all both MS Windows and Linux. That is if my text file finishes as below, without an explicit newline, is there one encoded there anyway or should I add an extra++lines;after the for loop? ``` cat dog ``` Then what about if thereisan explicit newline at the end of the file? Or do I just need to test for this case by keeping track of the previously read value?
If there is no newline, one won't be generated. C tells you exactly what's there.
my problem is I have to free a double pointer. I already tried it: ``` char** files = malloc(sizeof(char*) * files_int); for( i=1; i <= files_int ; i++) { files[i] = malloc(500); //fill with data... } //call function with needs the double pointer functionA(files); //free first array for(x=1; x <= max_files ; x++){ free(files[x]); } //free second array free(files); ``` I am always getting a glibc detected double free or corruption (out) error. What am I doing wrong?
Arrays in C are0based: ``` for( i=1; i <= files_int ; i++) files[i] = malloc(500); ``` causes a buffer overflow, possibly corrupting the memory allocation system, and you do not allocatefiles[0].
I got a problem when I want to use make, containing a variable linking to my folder. Like this : ``` DIR_ST = I\ \:\ The\ Scared\ Stones SRC_ST = $(DIR_ST)/main.c OBJ_ST = $(SRC_ST:.c=.o) ``` But when I want to compile like this: ``` all : $(ST) $(ST) : $(OBJ_ST) $(CC) $(OBJ_ST) -o strategic ``` i got this error: ``` make: *** No rule to make target `I \: The Sacred Stones/main.o', needed by `binaries/strategic'. Stop. ``` How can I use this folder's name in a Makefile?
you could place a symbolic link in the current directory to the 'I:\ The Scared Stones directory suggest using a link name that does not have any spaces
Quick question: Since int is 2 bytes and char is 1 byte, I want to store an int variable in 2 char variables. (like bit 1 - 8 into the first char, bit 9-16 into second char). Using C as programming language. How can I achieve that? Will something like: ``` int i = 30543; char c1 = (char) i; char c2 = (char) (i>>8); ``` do the job? I couldn't find whether casting an int into a char will just drop the bits 9-16.
This was extracted from the c11 draft n1570 6.5.4 Cast operatorsIf the value of the expression is represented with greater range or precision than required by the type named by the cast (6.3.1.8), then the cast specifies a conversion even if the type of the expression is the same as the named type and removes any extra range and precision. So the cast will indeed remove the extra bits, but it's not needed anyway because the value will be implicitly converted tochar, and the above would apply anyway.
I have a matrix in the form below where the position is only given via one iterable (x). ``` A B 1 0 3 2 0 2 4 5 ``` where for matrixA[x] and matrixB[x] ``` matrixA[0] = 1, matrixA[1] = 0, matrixA[2] = 0, matrixA[3] = 2 matrixB[0] = 3, matrixB[1] = 2 etc. ``` What would be the best way to implement a multiplication of matrices A and B (preferably in C) when the only way to receive the position within a matrix is through variable x (also have the length of width and height)? (the examples I have gotten from google all use two variables - height and width to solve this however I'm only working with one)
I think matrix'swidthhad been given as input. If so, You can convertmatrix[x][y]tomatrix[x*width+y]and apply any ordinary multiplication algorithm.
I would like to count the number of lines in an ASCII text file. I thought the best way to do this would be by counting the newlines in the file: ``` for (int c = fgetc(fp); c != EOF; c = fgetc(fp)) { /* Count word line endings. */ if (c == '\n') ++lines; } ``` However, I'm not sure if this would account for the last line on all both MS Windows and Linux. That is if my text file finishes as below, without an explicit newline, is there one encoded there anyway or should I add an extra++lines;after the for loop? ``` cat dog ``` Then what about if thereisan explicit newline at the end of the file? Or do I just need to test for this case by keeping track of the previously read value?
If there is no newline, one won't be generated. C tells you exactly what's there.
my problem is I have to free a double pointer. I already tried it: ``` char** files = malloc(sizeof(char*) * files_int); for( i=1; i <= files_int ; i++) { files[i] = malloc(500); //fill with data... } //call function with needs the double pointer functionA(files); //free first array for(x=1; x <= max_files ; x++){ free(files[x]); } //free second array free(files); ``` I am always getting a glibc detected double free or corruption (out) error. What am I doing wrong?
Arrays in C are0based: ``` for( i=1; i <= files_int ; i++) files[i] = malloc(500); ``` causes a buffer overflow, possibly corrupting the memory allocation system, and you do not allocatefiles[0].