question
stringlengths
25
894
answer
stringlengths
4
863
I just ran into a smallish issue when working with size_t values in some code. First I wanted to use size_t because it's [guaranteed] to be the same size on most platforms, that way going from 32 to 64 bit shouldn't cause any issues. Then I negated the size_t value and got a really big number, looking back I realized that size_t is unsigned. There is intptr_t which is also signed but should be used for pointers and there's uintptr_t which is unsigned and also used for pointers. My eventual goal is to implement a simple set of fixed point math functions in c. My question iscan I use uintptr_t like an int in all my calculations? Could that cause any issues?
If you want to have exactly the same number of bits on all platforms, simply use for instance int32_t as defined instdint.h
``` #include<stdio.h> #include<conio.h> #include<math.h> int main() { int x,n; float sum=0; printf("Length and Value"); scanf("%d%d",&n,&x); for(int i=1;i<=n;i++) { sum+=(pow(x,2*i+1) * pow(-1,i+1)); } printf("%f",sum); return 0; } ``` I'm trying to solve this series in C language. Am I doing something wrong in the above code?
Yes, you're a bit wrong. In your code ``` printf("%f",sum); ``` sumis anintand using%fto print the value of anintisundefined behaviour. The functionpow()returns adouble. You may want to change yoursumto typedouble. If you don't mind using your own version, a better looking implementation, without usingpow()will be Store the existing value.Multiply byx * xon each iterationTake care of -ve sign for even numbered iteration.
``` #include <stdio.h> #define ABS(a) (a) < 0 ? -(a) : (a) int main(void) { printf("%d\n", ABS(-3) + 1); return 0; } ``` This code snippet, from Herbert Schildt's book, looks like it will produce the output4but it actually prints3. Why? How do I fix it?
The correct way is to use aninlinefunction, with a_Genericcase for each type you want to support. Otherwise you evaluateatwice. In lieu of that you can fix it by parenthesizing the expression in the macro. That is always a good idea to prevent exactly this sort of problem. ``` #define ABS(a) ((a) < 0 ? -(a) : (a)) ``` The problem comes about becauseX ? Y : Z + 1meansX ? Y : (Z + 1).
I was trying to implement the following code. ``` #include <stdio.h> #include <string.h> void abc(char *, char *); int main(int argc, char *argv[]) { char *p="Hello XYZ"; char *q="ABC"; abc(p,q); printf("%s", p); } void abc(char *p, char *q) { p+=6; p=q; } ``` I believe I am modifying the references and I was expecting the output "Hello ABC" but the output is "Hello XYZ". Can any one explain the error?
C uses pass-by-value for function argument passing. So, you cannot actually changeporqfromabc(). To actually changepandqthemselves, you'll be requiring to pass a pointer to each of them.p=q;is not the way to copy a string, anyway. You need to make use ofstrcpy()to copy a string.You're making the call toabc()with arguments which are the pointers to string literals. If you try to modify thevaluespointed to by those input arguments, you'll faceundefined behaviour.
Given a file descriptor, I need to get its absolute path whether it is a regular file or aAF_UNIXsocket. The code atHow can I get a filename from a file descriptor inside a kernel module?works for regular files but withAF_UNIXsockets I get something like this"socket:[12345]"instead of the absolute path "/tmp/.X11-unix/X0". ``` struct sockaddr_un { unsigned short sun_family; // AF_UNIX char sun_path[108]; // pathname }; ```
netstat -xshows the full pathnames for unix sockets, by consulting/proc/net/unix, which is populated byunix_seq_showinnet/unix/af_unix.c. See here how it is done: http://lxr.free-electrons.com/source/net/unix/af_unix.c?v=4.1#L2252
What is the difference when we declare variable before using in loop and when define variable in loop. I am talking about this situation ``` int i; for(i=0; i<100; i++); ``` and ``` for(int i=0; i<100; i++); ```
In the former case, you can accessioutside the for-loop. This can be advantageous if you have a conditional break in your loop, for example: ``` int i = 0; for (i = 0; i < 100; i++) { if (someUnexpectedConditionHappens()) { break; } // do something } printf("The loop has been executed %d times", i); ```
What is the difference when we declare variable before using in loop and when define variable in loop. I am talking about this situation ``` int i; for(i=0; i<100; i++); ``` and ``` for(int i=0; i<100; i++); ```
In the former case, you can accessioutside the for-loop. This can be advantageous if you have a conditional break in your loop, for example: ``` int i = 0; for (i = 0; i < 100; i++) { if (someUnexpectedConditionHappens()) { break; } // do something } printf("The loop has been executed %d times", i); ```
I am working on a google chrome extension wherein I am receiving an array of integers from the extension bypp::Var shared = dict_message.Get("shared_list");. Now I need to pass on this array to a C function, hence need to get the elements intoint*. How do I go about doing that ?
First, make sure thepp::Varis really an array. ``` if (shared.is_array()) { ``` Then, use the interfaces provided by classpp::VarArray. ``` pp::VarArray array(shared); int * carray = new int[array.GetLength()]; for (uint32_t i = 0; i < array.GetLength(); ++i) { pp::Var oneElem(array.Get(i)); assert(oneElem.is_number()); carray[i] = oneElem.AsInt(); } // carray is ready to use delete [] carray; } ```
In the lecture, we were told that there is at least one prime number between k³ and (k + 1)³ for all k > 1. I would now like to know how to find such a prime numberefficientlyin C. I know the Sieve of Eratosthenes yet I have no clue how to implement it without polluting memory. Thanks for your help.
Youneed topollute your memory to increase the speed of finding the prime number. There is a simple approach that is fast and simple to implement. ``` primes = list of prime number below sqrt( (k+1)^3 ) for i = k^3 + 1 to (k+1)^3 : is_prime = true for p in primes: if (i % p == 0) : is_prime = false break if (is_prime): print(i) ``` For generating the list of prime number below sqrt ( (k+1)^3 ), you can use Sieve of Eratosthenes. With this approach, you will only need to use at most (k+1)1.5of memory.
First, the char array is greater than 8 bytes, so we can't use it directly as a 64-bit integer. In this case "relative" is defined as: ``` x = char[16] y = char[16] r = x / y ax = approx_int64(char[16]) ay = approx_int64(char[16]) ar = ax / ay ar ~= r ``` With a char array greater than 8 bytes, how could I efficiently convert that array to a relatively sized 64-bit integer?
It's not entirely clear what you mean by "relatively sized 64-bit integer". However, I will assume you consider each char[] to represent some sort of ordered number. If that is the case, the best way to approximate relative size is simply to take the 8 most significant bytes in that representation, and convert those to a 64-bit integer.
In Unix, C. After afork(), usually followed by await()orwaitpid()to wait thechildterminate. But can thechildexecute thewait()? Thechilddoesn't have a_child_, so when it execute thewait(), what will happen?
There are no child proccess for the child proces sowait()will return -1. From the man page: wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.
This question already has answers here:Implicit int return value of C function(7 answers)Closed8 years ago. Can someone please explain the behavior of the following code. How come the function message() with return typeintis returning the no of characters printed by printf() function without any return statement ? ``` #include <stdio.h> int message(); int main() { int c; printf("C before:%d\n",c); c=message(); printf("C after:%d\n",c); return 0; } int message(){ printf("From the message"); } ```
This is caused by undefined behaviour.Here's asimilar question, and I couldn't put it any better than thesecond answerdoes: That's simply undefined behaviour; if you don't populate the return area [...], it'll have the value last set up through some side-effect in your function. ...which is the value returned byprintf.
This question already has answers here:Why doesn’t putchar require a header?(2 answers)Closed8 years ago. Why does this code work: ``` #include <stdio.h> int main() { int x = isspace(getchar()); printf("%d", x); return 0; } ``` Whenever I enter whitespaceisspace()returns 8 and when I don't, it gives 0. Shouldn't this produce an error at compile time? I didn't add#include <ctype.h>at the top. So why this is allowed?
You're seeing this because your compiler (sadly, still) supports implicit declaration of a function. If you enable strict checking, you compiler should refuse to compile the code. On and aboveC99, the implicit function declaration has been made non-standard. (To add, hopefully, future versions of compiler will strictly disallow this, by default.)
For some reason, whenever I use a numeric value in my compiler set-up (MinGW on Windows, using a CMD prompt to compile and run), it completely misreports numbers in the program. Code example: ``` //C hello world example #include <stdio.h> int main() { int value; value = 10; printf("The number is %d \n"), value; int value2; value2 = -100; printf("The number is %d \n"), value2; return 0; } ``` Cf.screenshot of output.
valueandvalue2have to be passed as arguments, i.e.within the parantheses. Change it to the following: ``` printf("The number is %d \n", value); ``` And do similarly withvalue2. Once again, this shows that compiling with-Walland-pedanticswitches on is useful. GCC most likely would have issued a warning message.
This question already has answers here:Implicit int return value of C function(7 answers)Closed8 years ago. Can someone please explain the behavior of the following code. How come the function message() with return typeintis returning the no of characters printed by printf() function without any return statement ? ``` #include <stdio.h> int message(); int main() { int c; printf("C before:%d\n",c); c=message(); printf("C after:%d\n",c); return 0; } int message(){ printf("From the message"); } ```
This is caused by undefined behaviour.Here's asimilar question, and I couldn't put it any better than thesecond answerdoes: That's simply undefined behaviour; if you don't populate the return area [...], it'll have the value last set up through some side-effect in your function. ...which is the value returned byprintf.
This question already has answers here:Why doesn’t putchar require a header?(2 answers)Closed8 years ago. Why does this code work: ``` #include <stdio.h> int main() { int x = isspace(getchar()); printf("%d", x); return 0; } ``` Whenever I enter whitespaceisspace()returns 8 and when I don't, it gives 0. Shouldn't this produce an error at compile time? I didn't add#include <ctype.h>at the top. So why this is allowed?
You're seeing this because your compiler (sadly, still) supports implicit declaration of a function. If you enable strict checking, you compiler should refuse to compile the code. On and aboveC99, the implicit function declaration has been made non-standard. (To add, hopefully, future versions of compiler will strictly disallow this, by default.)
For some reason, whenever I use a numeric value in my compiler set-up (MinGW on Windows, using a CMD prompt to compile and run), it completely misreports numbers in the program. Code example: ``` //C hello world example #include <stdio.h> int main() { int value; value = 10; printf("The number is %d \n"), value; int value2; value2 = -100; printf("The number is %d \n"), value2; return 0; } ``` Cf.screenshot of output.
valueandvalue2have to be passed as arguments, i.e.within the parantheses. Change it to the following: ``` printf("The number is %d \n", value); ``` And do similarly withvalue2. Once again, this shows that compiling with-Walland-pedanticswitches on is useful. GCC most likely would have issued a warning message.
I have a C function which returns a BSTR like "Hello world" and in Excel 11 I can call this function to print the string with the msgbox vba function. With Excel 16, I only have an returned empty string. If I am in debug with XCode, I can see my BSTR and it is not empty. Do you have any idea to get a BSTR, returned by a C function, with the VBA of Excel 16?
I used SysAllocString but this function return NULL pointer. To fix my problem, I need to create my BSTR byte by byte
Is there such thing as a standard file chooser (and file save) dialogs in X? If yes, what's the extension/request for invoking that? If no, does that mean that Qt, GTK, wxWidgets, etc. each implement their own with different look and behavior, so I must do the same? Thanks.
X11 does not have any standard widgets, graphics toolkits implement these features on top of the X display server. X is only responsible ofdisplaying, while toolkits are responsible fordrawing, two different responsibilities.
I know mach_timebase_info has a return type of kern_return_t, but I'm not able to locate documenation that specifies the possible return values. Where can I find this information?
According to the latest source for xnu-2782.1.97 (OS X 10.10.1) available athttp://www.opensource.apple.com/release/os-x-10101/, the only return value is KERN_SUCCESS: ``` /* * mach_timebase_info_trap: * * User trap returns timebase constant. */ kern_return_t mach_timebase_info_trap( struct mach_timebase_info_trap_args *args) { mach_vm_address_t out_info_addr = args->info; mach_timebase_info_data_t info; clock_timebase_info(&info); copyout((void *)&info, out_info_addr, sizeof (info)); return (KERN_SUCCESS); } ```
I'm trying to load a file which has couple of infor, and I want to add them into a binary tree. For sure there is no problem with addToTree and printPreOrder functions, but i don't know why I can only print ( or maybe add ) the last item in the file. Whats the problem? ``` newTree = createBinTree(&cmpInt, &destroyNode); newRes = createRes(); while (fgets(buffer, 100, fp) != NULL) { strcpy(newRes->name,strtok(buffer, ",")); strcpy(newRes->food,strtok(NULL, ",")); newRes->star = atoi(strtok(NULL, ",")); addToTree(newTree, newRes); } printPreOrder(newTree, &printNode); ```
You are always adding to the same pointer tonewRes. While reading you overwrite your previousnewResentries. You need to callcreateResfor each object you are reading.
I was trying to use a c library libwebsockets(https://github.com/warmcat/libwebsockets) for my c++ program. I followed the manual and it creates a visual studio solution and it works. Since I am not used to develop a program on a windows 7 visual studio environment, I am not sure how library works. It looks like solution contains some test codes and core libraries. In a windows7 environment, what is the best way to develop a C++ project using this this C library? I am considering two ways which are: Add the c projects on the c++ projectAdd the c++ project on the c projects
Create two different Projects: One for the C lib and the other for your C++ Code. Then build the C Code into a *.lib File and add it to your C++ Project using this Answer:How to include libraries in Visual Studio 2012? You can add both Projects into one Solution so they are easily accessible.
The extra Q at the end of rotor[0][0].order is from rotor[0][0].notch. What is the cause of this and what should be done to avoid this concatenation? ``` #include <stdio.h> struct rotor_wirings { char order[26]; char notch[2]; }; /* rotor[MODEL][ROTORNAME] */ struct rotor_wirings rotor[10][10] = { /* Commercial Enigma A, B */ { { "DMTWSILRUYQNKFEJCAZBPGXOHV", "Q" }, { "HQZGPJTMOBLNCIFDYAWVEUSRKX", "E" } } }; int main() { printf("First rotor is: %s\n", rotor[0][0].order); return 0; } ``` The output is: ``` First rotor is: DMTWSILRUYQNKFEJCAZBPGXOHVQ ```
You didn't leave room for the trailing null at the end of theorderstring. It should be ``` char order[27]; ```
I need to put 3 strings on anarray[3][3]. I tried to do it with pointers, but I only receive a single character. ``` #include <stdio.h> int array[3][3] char thing[5] = "thing"; main() { thing = array[0][0]; printf("%s", array[0][0]; } ```
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too. ``` #include <stdio.h> #include <string.h> char array[3][6]={0}; char *thing = "this"; main() { strcpy(array[0],thing); printf("%s\n", array[0]); } ```
I have a C program creating a detached thread as a child. Inside of the function I pass to pthread_create I use pthread_detach to detach the thread. At the end I call pthread_exit((void *) 0) I would like to know if it is normal behaviour that the memory consumption increases after the thread is created. I did a valgrind check and there are no leaks just 4 suppressed errors.
I would like to know if it is normal behaviour that the memory consumption increases after the thread is created. Yes, as each thread gets its own stack assigned. The size is OS setting dependend and could be around 1M.some system resource will be used to manage each thread itself. Both will be released if the thread ends for a detached thread or if the thread was joined for a joinable thread.
I am wondering if there is a graphical tool to decode data structures from multiple files? What I mean is, let us say we have the following ``` typedef struct herStruct; ... typedef struct myStruct { void* hisStruct; herStruct* ptr; }myStruct; ``` It would have been great if there was a tool where in, we pass the header files and c files and the tool would give a graphical representation of the various structures used. Wishful thinking I know. I am going through linux drivers (custom drivers) and it feels convoluted understanding the various structures. How does one understand someone else's code which has so many structures and is convoluted (and not many comments!). I tried to draw it myself, but did not go too far.
You can try using Doxygen/GraphViz to generate visualizations. Take a look atthis question.
I have a C function which returns a BSTR like "Hello world" and in Excel 11 I can call this function to print the string with the msgbox vba function. With Excel 16, I only have an returned empty string. If I am in debug with XCode, I can see my BSTR and it is not empty. Do you have any idea to get a BSTR, returned by a C function, with the VBA of Excel 16?
I used SysAllocString but this function return NULL pointer. To fix my problem, I need to create my BSTR byte by byte
Is there such thing as a standard file chooser (and file save) dialogs in X? If yes, what's the extension/request for invoking that? If no, does that mean that Qt, GTK, wxWidgets, etc. each implement their own with different look and behavior, so I must do the same? Thanks.
X11 does not have any standard widgets, graphics toolkits implement these features on top of the X display server. X is only responsible ofdisplaying, while toolkits are responsible fordrawing, two different responsibilities.
I know mach_timebase_info has a return type of kern_return_t, but I'm not able to locate documenation that specifies the possible return values. Where can I find this information?
According to the latest source for xnu-2782.1.97 (OS X 10.10.1) available athttp://www.opensource.apple.com/release/os-x-10101/, the only return value is KERN_SUCCESS: ``` /* * mach_timebase_info_trap: * * User trap returns timebase constant. */ kern_return_t mach_timebase_info_trap( struct mach_timebase_info_trap_args *args) { mach_vm_address_t out_info_addr = args->info; mach_timebase_info_data_t info; clock_timebase_info(&info); copyout((void *)&info, out_info_addr, sizeof (info)); return (KERN_SUCCESS); } ```
I'm trying to load a file which has couple of infor, and I want to add them into a binary tree. For sure there is no problem with addToTree and printPreOrder functions, but i don't know why I can only print ( or maybe add ) the last item in the file. Whats the problem? ``` newTree = createBinTree(&cmpInt, &destroyNode); newRes = createRes(); while (fgets(buffer, 100, fp) != NULL) { strcpy(newRes->name,strtok(buffer, ",")); strcpy(newRes->food,strtok(NULL, ",")); newRes->star = atoi(strtok(NULL, ",")); addToTree(newTree, newRes); } printPreOrder(newTree, &printNode); ```
You are always adding to the same pointer tonewRes. While reading you overwrite your previousnewResentries. You need to callcreateResfor each object you are reading.
I was trying to use a c library libwebsockets(https://github.com/warmcat/libwebsockets) for my c++ program. I followed the manual and it creates a visual studio solution and it works. Since I am not used to develop a program on a windows 7 visual studio environment, I am not sure how library works. It looks like solution contains some test codes and core libraries. In a windows7 environment, what is the best way to develop a C++ project using this this C library? I am considering two ways which are: Add the c projects on the c++ projectAdd the c++ project on the c projects
Create two different Projects: One for the C lib and the other for your C++ Code. Then build the C Code into a *.lib File and add it to your C++ Project using this Answer:How to include libraries in Visual Studio 2012? You can add both Projects into one Solution so they are easily accessible.
The extra Q at the end of rotor[0][0].order is from rotor[0][0].notch. What is the cause of this and what should be done to avoid this concatenation? ``` #include <stdio.h> struct rotor_wirings { char order[26]; char notch[2]; }; /* rotor[MODEL][ROTORNAME] */ struct rotor_wirings rotor[10][10] = { /* Commercial Enigma A, B */ { { "DMTWSILRUYQNKFEJCAZBPGXOHV", "Q" }, { "HQZGPJTMOBLNCIFDYAWVEUSRKX", "E" } } }; int main() { printf("First rotor is: %s\n", rotor[0][0].order); return 0; } ``` The output is: ``` First rotor is: DMTWSILRUYQNKFEJCAZBPGXOHVQ ```
You didn't leave room for the trailing null at the end of theorderstring. It should be ``` char order[27]; ```
I need to put 3 strings on anarray[3][3]. I tried to do it with pointers, but I only receive a single character. ``` #include <stdio.h> int array[3][3] char thing[5] = "thing"; main() { thing = array[0][0]; printf("%s", array[0][0]; } ```
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too. ``` #include <stdio.h> #include <string.h> char array[3][6]={0}; char *thing = "this"; main() { strcpy(array[0],thing); printf("%s\n", array[0]); } ```
I have a very simple macro for which I want to typecast its output tointonly. How to do that? ``` #define Numbits(A) (sizeof(A)*CHAR_BIT) ``` I tried: ``` #define int Numbits(A)({int val; val = sizeof(A)*CHAR_BIT; return val;}) ``` but it also doesn't work
Are you saying that#define Numbits(A) (int)(sizeof(A)*CHAR_BIT)didn't work?
I am trying to initalize a structure using braces, but i am really trying to initalize the structure that is pointed to by a pointer returned from a malloc call. ``` typedef struct foo{ int x; int y; } foo; foo bar = {5,6}; ``` I understand how to do that, but i need to do it in this context. ``` foo * bar = malloc(sizeof(foo)); *bar = {3,4}; ```
(This was answered in comments, so making it a CW). You need to cast the right-hand side of the assignment, like so: ``` *bar = (foo) {3,4}; ``` As pointed out by @cremno in the comment, this isn't a cast but rather an assignment of acompound literal The relevant section of the C99 standard is:6.5.2.5 Compound literalswhich says: A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list
If I have program with a main thread and a function running in a separated detached thread. If something in the detached thread is returning something > 0 will only the child thread exit or the main thread too?
A Posix thread returnsvoid *(ie. a pointer), so it cannot return anything less than zero since it's not an integer. In any case, the return value from a detached thread is always ignored, and the process will not exit whatever the value.
Suppose I am writing a sorting-array method. At the time I did not know pointer, I usually defined array as global so that it automatically change. Now I try to use it but it fails, basically it ends up with ``` int a[5]; sort(&a); // Calling sort ... // My method void sort(int *a[]) { int key = *a[1]; // I've got a bug right here ... } ``` I am still unfamiliar with using pointers. Moreover I can not use reference, either. Please suggest me some ways to do that. Thank you so much.
Change your function to just this ::void sort(int *a)or this ::void sort(int a[]) And when you callsortfrom the main, you need not callsort(&a),ais an array pointer itself, callingsort(a)will do it!
Doesalignof(N) == sizeof(N)where N is an integral type? I'm asking for both C and C++, hope this isn't a problem.
It's machine-specific. On a 32-bit machine,alignof(int64_t)could easily be 4. Too, assumptions that are widespread now won't be for so very long.
I don't understand the output of this code: ``` main() { int ret = ~(~0 <<5) << 2; printf("ret: %d, %u\n", ret, ret); } output: ret: 124, 124 ``` If I process mentally, I do this: resolving ~0 gives binary 1resolving ~0 << 5 gives binary 100000resolving ~(~0 << 5) gives binary 011111resolving ~(~0 << 5) << 2 gives binary 111100convert binary 111100 to decimal gives 60 What did I do wrong ?
Integral literals in C areints by default, andintis usually 4 bytes long (depending on the compiler). This means that~0is not1, it's 32 1s. ``` ~0 == 11111111111111111111111111111111 ~0 << 5 == 11111111111111111111111111100000 ~(~0 << 5) == 00000000000000000000000000011111 ~(~0 << 5) << 2 == 00000000000000000000000001111100 ```
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 At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. Can anyone explain these lines and related terminologies in a beginners words?
Expressions such asn++have side effects, i.e. they not only produce a result, but also modify a variable. The*operator doesnotintroduce a sequence point. Therefore, in the expressionn++ * n--it is not specified, whether the side effect ofn++(incrementingn) has already happened whenn--is evaluated. Depending on that,n++ * n--yields different results. ;introduces a sequence point. Ifn == 5, then aftern++; n--;,n == 5holds again.
I want to write a script (orccode) that canautomaticallyprint the list of supported sys calls (the full function signature; specially, their names, return type and argument list)? I have searched for the solutions for a while, and know syscall names are present in . But there is no argument list or return type? My target platform is Linux (specifically, Ubuntu) andc. PS: By syscall, I mean the libc wrapper functions for syscall...
Based on @knm241 's comments, this will work: ``` grep '^asmlinkage.*sys_' /usr/src/linux-headers-3.16.0-30/include/linux/syscalls.h ```
In the following code,how to create a pointer to the variabletriangle.pluto.mars.aso it becomes unnecessary in the printf line to repeat the whole path for membera. ``` #include <stdio.h> int main(){ struct euler { int a; int b; }; struct gauss { int f; int g; struct euler mars; }; struct aristotle{ int x; int y; struct gauss pluto; } triangle; triangle.pluto.mars.a = 151; printf("\nThe value is: %d\n\n",triangle.pluto.mars.a ); return 0; } ```
The band-aid solution: ``` int * someVariable = &(triangle.pluto.mars.a); ``` The long solution: Do a redesign.
This question already has answers here:Why is "a" != "a" in C?(11 answers)Closed8 years ago. Given below is a piece of code that does not do what I want ``` do { printf("inserisci un nome: "); scanf("%29s", s); } while (s!="*"); ``` My aim is to exit from the cycle if the string entered is "*". Why doesn't it work? What should I modify?
Take a look atstrcmpto compare strings,!=will not do what you want. In that case!=will compare the variables(apointerto the first element of the arrays) with the string"*". That is why it was not working properly.
Here is one way but the problem with it is unnecessary usage of output screen. ``` lenth=printf("%d",num);// or lenth=printf("%s",str); ``` How could i find length without having output from printf?
You can usesnprintf()with anemptybuffer (i.e. pass a null pointer), which will return the number of characters that would have been written into the buffer if there was enough space in it: ``` int length = snprintf(0, 0, "%d", num); ``` This way, you don't need to use an actual buffer and it won't print onstdoutlikeprintf()does.
``` #include<stdio.h> int power(int m,int n); main() { int i; for(i=0;i<10;i++) printf("%d %d %d\n",i,power(2,i),power(-3,i)); return 0; } int power(int base,int n) { int i,p; p=1; // doubt in this line for(i=1;i<=n;++i) p=p*base; return p; } ``` when p is declared as 1 . Then how it calculate the value for 2^0.yet I'm the beginner of c programming i can't able to get the logic behind this.And my doubt in this function program is how it works for 2^0 when p=1.Thanks for your replay..
I'm assuming by 2^0 you mean the inputs to the functionpowerare 2 and 0. In that case,n = 0, and the for loop doesn't even run becausei = 1which is greater than 0. In that case, the function returns 1 because you initializedpto 1, and the loop didn't modify it.
Suppose I am writing a sorting-array method. At the time I did not know pointer, I usually defined array as global so that it automatically change. Now I try to use it but it fails, basically it ends up with ``` int a[5]; sort(&a); // Calling sort ... // My method void sort(int *a[]) { int key = *a[1]; // I've got a bug right here ... } ``` I am still unfamiliar with using pointers. Moreover I can not use reference, either. Please suggest me some ways to do that. Thank you so much.
Change your function to just this ::void sort(int *a)or this ::void sort(int a[]) And when you callsortfrom the main, you need not callsort(&a),ais an array pointer itself, callingsort(a)will do it!
Doesalignof(N) == sizeof(N)where N is an integral type? I'm asking for both C and C++, hope this isn't a problem.
It's machine-specific. On a 32-bit machine,alignof(int64_t)could easily be 4. Too, assumptions that are widespread now won't be for so very long.
I don't understand the output of this code: ``` main() { int ret = ~(~0 <<5) << 2; printf("ret: %d, %u\n", ret, ret); } output: ret: 124, 124 ``` If I process mentally, I do this: resolving ~0 gives binary 1resolving ~0 << 5 gives binary 100000resolving ~(~0 << 5) gives binary 011111resolving ~(~0 << 5) << 2 gives binary 111100convert binary 111100 to decimal gives 60 What did I do wrong ?
Integral literals in C areints by default, andintis usually 4 bytes long (depending on the compiler). This means that~0is not1, it's 32 1s. ``` ~0 == 11111111111111111111111111111111 ~0 << 5 == 11111111111111111111111111100000 ~(~0 << 5) == 00000000000000000000000000011111 ~(~0 << 5) << 2 == 00000000000000000000000001111100 ```
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 At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. Can anyone explain these lines and related terminologies in a beginners words?
Expressions such asn++have side effects, i.e. they not only produce a result, but also modify a variable. The*operator doesnotintroduce a sequence point. Therefore, in the expressionn++ * n--it is not specified, whether the side effect ofn++(incrementingn) has already happened whenn--is evaluated. Depending on that,n++ * n--yields different results. ;introduces a sequence point. Ifn == 5, then aftern++; n--;,n == 5holds again.
I want to write a script (orccode) that canautomaticallyprint the list of supported sys calls (the full function signature; specially, their names, return type and argument list)? I have searched for the solutions for a while, and know syscall names are present in . But there is no argument list or return type? My target platform is Linux (specifically, Ubuntu) andc. PS: By syscall, I mean the libc wrapper functions for syscall...
Based on @knm241 's comments, this will work: ``` grep '^asmlinkage.*sys_' /usr/src/linux-headers-3.16.0-30/include/linux/syscalls.h ```
In the following code,how to create a pointer to the variabletriangle.pluto.mars.aso it becomes unnecessary in the printf line to repeat the whole path for membera. ``` #include <stdio.h> int main(){ struct euler { int a; int b; }; struct gauss { int f; int g; struct euler mars; }; struct aristotle{ int x; int y; struct gauss pluto; } triangle; triangle.pluto.mars.a = 151; printf("\nThe value is: %d\n\n",triangle.pluto.mars.a ); return 0; } ```
The band-aid solution: ``` int * someVariable = &(triangle.pluto.mars.a); ``` The long solution: Do a redesign.
This question already has answers here:Why is "a" != "a" in C?(11 answers)Closed8 years ago. Given below is a piece of code that does not do what I want ``` do { printf("inserisci un nome: "); scanf("%29s", s); } while (s!="*"); ``` My aim is to exit from the cycle if the string entered is "*". Why doesn't it work? What should I modify?
Take a look atstrcmpto compare strings,!=will not do what you want. In that case!=will compare the variables(apointerto the first element of the arrays) with the string"*". That is why it was not working properly.
Here is one way but the problem with it is unnecessary usage of output screen. ``` lenth=printf("%d",num);// or lenth=printf("%s",str); ``` How could i find length without having output from printf?
You can usesnprintf()with anemptybuffer (i.e. pass a null pointer), which will return the number of characters that would have been written into the buffer if there was enough space in it: ``` int length = snprintf(0, 0, "%d", num); ``` This way, you don't need to use an actual buffer and it won't print onstdoutlikeprintf()does.
``` #include<stdio.h> int power(int m,int n); main() { int i; for(i=0;i<10;i++) printf("%d %d %d\n",i,power(2,i),power(-3,i)); return 0; } int power(int base,int n) { int i,p; p=1; // doubt in this line for(i=1;i<=n;++i) p=p*base; return p; } ``` when p is declared as 1 . Then how it calculate the value for 2^0.yet I'm the beginner of c programming i can't able to get the logic behind this.And my doubt in this function program is how it works for 2^0 when p=1.Thanks for your replay..
I'm assuming by 2^0 you mean the inputs to the functionpowerare 2 and 0. In that case,n = 0, and the for loop doesn't even run becausei = 1which is greater than 0. In that case, the function returns 1 because you initializedpto 1, and the loop didn't modify it.
If I want to dynamically link a shared library (.so) for a C++ application (which was built with g++) using LD_PRELOAD, does it matter if the .so is generated from a C source file (using gcc) or a C++ source file (using g++)? And why or why not? Thanks for helping me understand this.
Yes, a C++ executable can be linked (both statically and dynamically) to a C library. This is completely deliberate. The C++ ABIs aredesignedto be backwards compatible. You will have to ensure that the declarations of functions and so on of the library symbols, as written in your C++ program, are markedextern "C"to denote that you are crossing a language boundary. Typically, the library's own shipped header files will do this for you.
I am finding out information related to usb mass storage using udev library functions like (vendor ID, product ID, Manufacturer, Product, Serial etc). Can any one suggest how to get usb mass storage size using udev.
Size is apparently not among the property values. It is, however, one of the sysfs attributes but I don't know how long it has been there. It is not mentioned inDocumentation/ABI/testing/sysfs-blockfor some reason. You can get the value as a string like any other sysattr: ``` blocks_string = udev_device_get_sysattr_value(dev, "size"); ```
Inex26of 'Learn C the Hard Way' in thedb.cfile Zed defines two functions: ``` static FILE *DB_open(const char *path, const char *mode) { return fopen(path, mode); } static void DB_close(FILE *db) { fclose(db); } ``` I have a hard time understanding the purpose/need for wrapping these very simple calls tofopenandfclose. What are, if any, the advantages of wrapping very simple functions, like the example given above?
In this particular case a wrapper is used to hide the detail thatDB_open,DB_readorDB_closeall map to file operations. This approach implements anabstraction layerthrough which all database related functions are to be accessed. Also this providesmodularity, which may later allow adding more methods to open/read/close databases. As explained by Michael Kohne in the comments, this wrapper should be improved to totally hide e.g. the type ofFILE *db, by substituting it withstruct DB_context *context;.
I am troubleshooting a recent session ID collision and want for this purpose exercise the functionphp_session_createand compute an empirical probability for this function to generate colliding session IDs in some standardised (labor) conditions. However that function is not directly bound in PHP, but seems to be only indirectly accessible. What would be the easiest strategy to generate a lot of session IDs?
If you want to generate random strings you can use PHP'smcrypt_create_ivfunction. ``` $NUM_BITS = 256; $random_bits = mcrypt_create_iv($NUM_BITS / 8); $printable_key = base64_encode($random_bits); ```
I've used typedef before, but I've never used one with a pointer. What effect does this have on the typedef? Code for reference: ``` typedef struct node NODE, *PNODE, **PPNODE; ```
Instead of usingstruct nodeyou can replace it withNODE Instead of usingstruct node*you can replace it withPNODE Instead of usingstruct node**you can replace it withPPNODE The statement can be broken down to ``` typedef struct node NODE; typedef struct node* PNODE; // PNODE is pointer to node typedef struct node** PPNODE; // PPNODE is pointer to pointer to node ```
What combination of preorder,inorder and postorder Traversal generate a unique binary Tree?
following combination can uniquely identify a tree. Inorder and Preorder. Inorder and Postorder. Inorder and Level-order. And following do not. Postorder and Preorder. Preorder and Level-order. Postorder and Level-order. For more infomation refer:Geeksforgeek
I'm trying to allocate some memory using MACROS. But I get this errors: error: expected expression before ‘)’ tokenerror: expected statement before ‘)’ token This is my code: ``` #define ALLOC(p,n) (p*)malloc(sizeof(p)*n) int main(){ char *ponteiro; ponteiro=ALLOC(5,ponteiro); return 0; } ```
Change: ``` #define ALLOC(p,n) (p*)malloc(sizeof(p)*n) ``` to: ``` #define ALLOC(p,n) malloc(sizeof(*(p))*(n)) ``` and in themain()free the allocated memory beforereturn ``` int main(){ char *ponteiro; ponteiro = ALLOC(ponteiro,5); /* Do something */ free(ponteiro); return 0; } ```
Is it possible to lock a socket for a thread? For example usingflock? These locks are designed for files, but they take a generic file descriptor as a parameter.
The documentation specifically states that flock is meant for files. From the MacOS documentation page (man): (emphasis added) Flock() applies or removes an advisory lock on thefileassociated with the file descriptor fd. In particular, this is meant for inter-process synchronization on the samefile. Assuming that you are trying to lock amongst threads within a process, it seems wise to instead rely on pthread_mutex_lock/unlock. (You are about to do a slow IO, so I woulnd't bother with spinlocks either). Hope that helps,
I get the following error : argument of type "const char *" is incompatible with parameter of type "LPCWSTR" Here is my code : ``` static char *getFmuPath(const char *fileName) { char pathName[MAX_PATH]; int n = GetFullPathName(fileName, MAX_PATH, pathName, NULL); return n ? strdup(pathName) : NULL; } ``` I have declaredMAX_PATHbut it still shows error in pathname ``` #define MAX_PATH 4096 ``` What is the problem ?
GetFullPathNamedoesn't take achar *. Look at the docs, it takesLPTSTRandLPCTSTR. Depending on your build settings,LPTSTRand related types will become eitherchar*(ANSI builds) orwchar_t*(Unicode builds). You are building as Unicode. Also, I don't know why you are definingMAX_PATH. That is a Windows constant so you should not re-define it.
``` int main() { printf("%c", "\n"); return 0; } ``` Here according to type specifier a character is required. But we are passing itconst char *. I was hoping that it would give me a warning message in code blocks GNU GCC compiler but it is not giving me any warning and printing the$character. why it is not giving any type of warning?
You need to enable that warning. Compiling your code astest.cppand adding#include <stdio.h>forprintfwith the correct warning flag under gcc 4.7.2: ``` $ gcc -c -Wformat test.cpp test.cpp: In function 'int main()': test.cpp:5:18: warning: format '%c' expects argument of type 'int', but argument 2 has type 'const char*' [-Wformat] ```
I trying to use Gstreamer in Visual Studio 2012. So I installed gstreamer-1.0-devel-x86-1.5.2.msi and gstreamer-1.0-x86-1.5.2.msi, then I added gstreamer-1.0.props in Property Sheet and changed working directory in "properties->configuration properties->debugging" to MY\GSTREAMER\PATH\bin. And tried to compile this: ``` #include "stdafx.h" #include <gst/gst.h> int _tmain(int argc, char* argv[]) { GstElement *pipeline; GstBus *bus; GstMessage *msg; /* Initialize GStreamer */ gst_init (&argc, &argv); return 0; } ``` But got this issue: The procedure entry point g_type_check_instance_is_fundamentally_a could not be located in the dynamic link library libgobject-2.0-0.dll. How I can resolve this?
I found solution: my program used not right dll, that was the same named dll of GTK#, after deleting GTK#(wrong, but quick ;)) my program started to load the right dll from Gstreamer.
I read somewhere that withscanf()I can input a maximum of 15chars. Is it right? Is it bounded?
Hasscanf()a limited bound on the number of bytes that the user can input? NO. However, FWIW, we can impose a limit on the length of the input actually to be scanned. For that. we use the maximum field width along with the conversion specifier. A simple example will be ``` char arr[15] = {0}; scanf("%14s", arr); ``` The above format guarantees that whatever be the length of the user input, (i.e., the data present of the input buffer),scanf()will only read14chars, and hence, even in case oflongeruser input, we can prevent the buffer overflow. Still, it does not impose any limit on theuser input. User can still input an arbitrary number (at least, theoretically) ofchars, when asked.
This question already has answers here:size of int variable(6 answers)Closed4 years ago. Why in Turbo C compilersizeof(int)is 2 bytes and in gcc Linux compiler is of 4 bytes?
sizeof(int)is not a constant across all platforms. It varies from system to system. PS: Only sizeof object which is constant across all platforms issizeof(char)
How can I improve this function in regard to speed : ``` void chrapp (char arr[], char chr, int pos) { memmove(arr + pos + 1, arr + pos, strlen(arr + pos)); *(arr + pos + 1) = chr; } ``` Also, it unfortunately doesn't work with appending a character to the very beginning of thearray, which is also a rein for improvement.
Your original code is going through the string twice. Once for calculating the length of the string and the second time for moving it. You can do it in one loop, however considering that the standard library functions are implemented in highly optimized manner it is not sure it will actually speed up things. Try the following code: ``` void chrapp (char arr[], char chr, int pos) { char *s; char cc; for(s=arr+pos; *s; s++) { cc = *s; *s = chr; chr = cc; } *s++ = chr; *s = 0; } ```
Malloc function on success returns pointer to the memory location allocated and returns null value on failure. If I put malloc() in an infinite while loop, will this loop ever stop? After malloc() allocates the entire memory available, will it stop execution or just keep returning null value?
Repeated calls tomallocthis way will just keep returning null pointers forever. (However, if you try to use that null pointer, you'll of course get a segfault). This is different behavior fromnewin C++, which throwsbad_allocif it can't allocate new memory.
``` /*Program to print all the numbers between a lower bound and a upper bound values*/ #include<stdio.h> #include<stdlib.h> void recur(int a, int b); int main(void) { int x,y; printf("Enter the lower and upper bound values: \n"); scanf("%d %d",&x,&y); void recur(x,y); return 0; } void recur(int a,int b) { if(a<b) { printf("%d /n",a); a++; void recur(a,b); } } ``` The output I get is: ``` Enter the lower and upper bound values: 10 50 process returned 0. ``` Is there anything wrong with the syntax or return type..? I've just started learning c.Need Help
Both ``` void recur(x,y); void recur(a,b); ``` declaresthe functions (prototype). Tocallthem, change them to ``` recur(x,y); recur(a,b); ```
I have two functions in my c programs. Lets name thema()anda(). In some where in the code I use their result in an equation: take a look at this: ``` int number = 2; int x; int a(){ number += 3; return number; } int b(){ number *= 2; return number; } x = a() + b(); printf("%d", x); ``` Here I expect 15 to be printed. But I get 11. Can anybody explain this?
In the statement, ``` x = a() + b(); ``` The order in which the functions a() and b() will be called isunspecified. But there's a sequence point before calling each function and after returning from each function. That means there are two possible orders of calls:1) a() first and then b().2) b() first and then a(). In case (1), the result will be 15 and in case (2), the result will be 11. There's no undefined behaviour despitenumberbeing modified by both functions as a side-effect of function calls.
I am a beginner in coccinelle and try to run my first example. Currently I'am following the steps ofthis article I created the c fileI created the coccinelle scriptI run it using$ spatch -sp_file test.cocci test.c In the terminal I got the expected result as mentioned in the article ``` --- test.c +++ /tmp/cocci-output-17416-b5450d-test.c @@ -7,7 +7,7 @@ main(int argc, char *argv[]) char *buf; /* allocate memory */ - buf = alloca(bytes); + buf = malloc(bytes); return 0; } ``` However the c file didn't change as expected. Can any body tell me where can I get the changes made by the script?
using ``` spatch --help ``` I got all the option for the command spatch . So i should use ``` $ spatch -sp_file test.cocci test.c -o /tmp/newtest.c ``` the result of runing the patch is in /tmp/newtest.c
For Example int and INT. About this two i just know int is the fundamental type and INT is windows data type both gain 4 bytes in memory and INT is use with window API. But i don't understand what is the major and proper different between both of them. Help me to understand this both fully?
intis a language keyword,INTis not. The size and range of values that anintcan take is constrained, but not fixed, by the C++ standard. INTis a data type defined by Windows that is a 4 byte signed integral type with 2's complement. With a MSVC compiler targetting Windows, it is probablytypedeffed or#defined toint, sinceintin that case has the required characteristics. Usingstd::int32_twould be preferable as it's multiplatform, although a compiler does not have to support it.
I have a function designed to make a socks handshake packet; but I can't find any information regarding how the authorization fields are filled. How is the authentication packet formatted? ``` void socks_auth(int sd, char *buffer) { char *ptrBuff; ptrBuff = buffer; *(ptrBuff++) = SOCKS_V; *(ptrBuff++) = 2; *(ptrBuff++) = 0x00; *(ptrBuff++) = 0x02; send(sd, ptrBuff, ptrBuff - buffer, 0); recv(sd, buffer, 2, 0); if (buffer[1] == 0xFF) write(STDOUT_FILENO, "not supported\n", 14); if (buffer[1] == 0x02) { }; } ```
I'd suggest you start withRFC1928,SOCKS Protocol Version 5and possiblyRFC1961GSS-API Authentication Method for SOCKS Version 5. If neither of those help, perhaps looking at the source ofsocat, which can act as a SOCKS5 proxy, will help.
I'm trying to read a character that has to be 'C' or 'n'.In case it is not, print an error and ask for another char. ``` #include <stdio.h> int main(int argc, char const *argv[]) { int c; printf("Enter the character: "); c = getchar(); while (!(c=='C' && c=='n')){ printf("Wrong!.\n"); printf("Enter the character: "); c = getchar(); } printf("\n"); return 0; } ``` And what I get is: Enter the character: sWrong!Enter the character: Wrong!Enter the character: Like it is checking twice in the while loop.
Two things: 1) You are pressing a character and then hitting enter. That's two characters. If you want to read a whole line, don't usegetchar. 2) Your conditional makes no sense. It will never be the case thatcis both equivalent to'C'and equivalent to'n', so you're testing something that cannot be. Your loop will never end.
I am passing a python module to C as aPyObject. I want to check to see if this value is NONE in my C code, using this form: ``` int func(PyObject tmp) { if(tmp) { // etc ``` I am getting the following error. How can I convert from a PyObject to boolean value, simillar to the way Python's if function behaves. It is worth noting that whentmpis aboost::python::objectvariable this command works as expected. ``` ex_program.cpp:72:7: error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool' if (tmp) ^~~ ```
PyObject_IsTrueseems to do what you want: ``` int PyObject_IsTrue(PyObject *o) Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1. ```
I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors. https://msdn.microsoft.com/en-us/library/027c4t2s.aspx
CFLAGS+= -fdiagnostics-absolute-paths
I've asorted arraybut it'snot necessarily sequential, and I need to knowIF it contains any duplicates. ``` Array : | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 8 | ``` I know we can linearly traverse in O(n) check if it contains any duplicates, but I was wondering if it is possible using Binary Search.
No, You can't do it with binary search. All algorithms will take at least linear time.
Given an index and an array of integers, I need to delete the element in the given array which was stored in the given index through the use ofmemcpy(). The new set of elements will be stored on the given array. Here's an illustration of what I want to do, though I'm having trouble implementing it. SoarrayElemafter deleting 10 would look like this:
You can't usememcpy, because source and destination overlap, but you can usememmove, e.g.: ``` memmove(&a[1], &a[2], 5 * sizeof(a[0])); ``` This copies the 5 elements starting ata[2]down to the 5 elements starting ata[1], taking care of the fact that the source and destination regions overlap.
I have a function designed to make a socks handshake packet; but I can't find any information regarding how the authorization fields are filled. How is the authentication packet formatted? ``` void socks_auth(int sd, char *buffer) { char *ptrBuff; ptrBuff = buffer; *(ptrBuff++) = SOCKS_V; *(ptrBuff++) = 2; *(ptrBuff++) = 0x00; *(ptrBuff++) = 0x02; send(sd, ptrBuff, ptrBuff - buffer, 0); recv(sd, buffer, 2, 0); if (buffer[1] == 0xFF) write(STDOUT_FILENO, "not supported\n", 14); if (buffer[1] == 0x02) { }; } ```
I'd suggest you start withRFC1928,SOCKS Protocol Version 5and possiblyRFC1961GSS-API Authentication Method for SOCKS Version 5. If neither of those help, perhaps looking at the source ofsocat, which can act as a SOCKS5 proxy, will help.
I'm trying to read a character that has to be 'C' or 'n'.In case it is not, print an error and ask for another char. ``` #include <stdio.h> int main(int argc, char const *argv[]) { int c; printf("Enter the character: "); c = getchar(); while (!(c=='C' && c=='n')){ printf("Wrong!.\n"); printf("Enter the character: "); c = getchar(); } printf("\n"); return 0; } ``` And what I get is: Enter the character: sWrong!Enter the character: Wrong!Enter the character: Like it is checking twice in the while loop.
Two things: 1) You are pressing a character and then hitting enter. That's two characters. If you want to read a whole line, don't usegetchar. 2) Your conditional makes no sense. It will never be the case thatcis both equivalent to'C'and equivalent to'n', so you're testing something that cannot be. Your loop will never end.
I am passing a python module to C as aPyObject. I want to check to see if this value is NONE in my C code, using this form: ``` int func(PyObject tmp) { if(tmp) { // etc ``` I am getting the following error. How can I convert from a PyObject to boolean value, simillar to the way Python's if function behaves. It is worth noting that whentmpis aboost::python::objectvariable this command works as expected. ``` ex_program.cpp:72:7: error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool' if (tmp) ^~~ ```
PyObject_IsTrueseems to do what you want: ``` int PyObject_IsTrue(PyObject *o) Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1. ```
I am looking for the clang equivalent of the cl command /FC. I need full paths for my build tool to parse out and open the code files with the errors. https://msdn.microsoft.com/en-us/library/027c4t2s.aspx
CFLAGS+= -fdiagnostics-absolute-paths
I have a very stupid question, I just can't answer. Can somebody tell me why the following code works? ``` char hello[]="Hello World\n"; char *hptr = hello; while(*hptr) { printf("%c", *hptr++);//here the output must be "ello World", but C thinks otherwise!!! } ```
You're using a post-increment: ``` *hptr++ ``` This uses the value ofhptrfirst, and then increments it. If you wanted to skip the first letter, you would use a pre-increment: ``` *++hptr ``` This increments the pointer value,thenuses it as a function argument.
What is wrong in this function? ``` void stringReverse (char stringa[]) { if (stringa[0]!='\0') { return stringReverse(&stringa[1]); printf("%c", stringa[0]); } } ``` I have to write a function that invert a string (ex: "Hello" in "olleH") using recursion; the function has to receive a string (nothing else) and to print the character in the inverse order... i don't understand why what i write didn't print anything...
returnreturns a value from the function and performs no further statements in that scope. Have a think about where you want that statement to be... Not answering in full because this sounds like homework!
I'm trying to get my program to open files with paths that I declare earlier in the program. My declared string ``` char *pathToFile="/var/www/mcc-libhid/"; ``` My current code ``` fptr=fopen("configurationSettings.txt","r")) ``` How I want the program to read it: ``` ftpr=fopen("/var/www/mcc-libhid/configurationSettings.txt" , "r"); ``` What is the syntax to do this?
Usesnprintf()and prefix the path into the buffer. ``` char buf[PATH_MAX]; snprintf(buf, sizeof buf, "%s/configurationSettings.txt", pathToFile); ``` and usebufinfopen(): ``` ftpr=fopen(buf, "r"); ```
I just finished coding my c program in visual studio (VS) and what I had done is just drag the compiled .exe file out of the folder to run it on other computers, except on other computers for that to work I guess I need VS since it says the MSVCR110D.dll is missing which is from VS. So how can I run my program on other computers that don't have VS?
You can useIExpresswhich is used for distributing self-contained installation packages. It is there in every windows machine preinstalled. Using this utility you can make the executable.exewhich will be incorporated with dependentdlls. You can seeStep by step guide, to see how to use it.
Can we include static variable in header files. If yes,Can other files can access it ? Can we include static function in header files and use it in another files. Can we pass static variable as function arguments ?suppose some function is there in header file header.h : fun(static int a,static int b)
Any name declared in the global namespace with specifierstatichas internal linkage. This means that the name is visible within the translation unit where it is declared. So if a header with a declaration of a name with static keyword is included in several translation units then each translation unit will have its own variable with such a name.
I haveenumin header file. ``` typedef enum{ up = 8, down = 2, left = 4, right = 6 }direction; ``` I want use enum to identify type of move. Like this: ``` void sayTypeOfMove(int type){ switch(type){ case direction.up: printf("IT IS UP MOVE..."); break; } } ``` The code does not compile , where is the problem?
C understands the enum elements when it knows you're dealing with that enum, so the right code would be ``` void sayTypeOfMove(direction type){ switch(type){ case up: printf("IT IS UP MOVE..."); break; } } ``` By the way,typeis a really bad name, because it feels so much like it should be a reserved keyword.
In my project I useget_cpu()andput_cpu()to disable and enable the preemption in the kernel on asmpmachine. Is there asafe wayto get the current preemption status in an smp machine i.e. whether the preemption is turned on or off.
preempt_count() returns current thread's preemption count. 0 value means that preemtion is allowed. Usually, you shouldn't request preemtion status unless for the selfcheck. If some block of code requires preemtion to be disabled, it should be wrapped withpreempt_disable()/preempt_enable()calls (or their alternatives).
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed8 years ago. I want to understand the syntax of the struct which i have seen some where. Can some please explain the meaning ofunsigned int xyz:1;. Is it just assigning default value to a variablexyz? BTW this code is in Objective C. ``` struct { unsigned int xyz:1; } testStruct; ```
It's abit field. You are telling the structure that you will only be using one bit ofxyz. This allows the compiler to make packing optimisations.
I was just studying about structures and classes. I created a sample structure for getting familiar with it and tried to initialize an array in it. when I compiled the program it gave me error ``` error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token char arr[5] = {2,3,8,67,87}; struct abc{ char a; char b; char c; char arr[5] = {2,3,8,67,87}; }; struct abc xyz[5]; ``` Is array initialization not allowed in declaration of a structure as well as class ?
I guess in C you can do like this: ``` struct abc{ char a; char b; char c; char arr[5]; }; struct abc test= { 5, 2, 3, { 'a', 'b', 'c', 'd', 'e' } }; ```
Other than being able to dereference avoid**, I don't understand the following: ``` void * foo, **bar; foo++;//error bar++;//no error ``` Why doesn't the first work but the second does? What's the difference?
First snippet ``` foo++;//error ``` because,foois pointer tovoidand you cannot have pointer arithmetic onvoid *, size of thevoidtype is not defined. Second snippet, ``` bar++;//no error ``` because,baris a pointer toa pointer tovoid. So, arithmetic operation is permitted, as the size of a pointer to pointer type is well defined. FWIW, don't get surprised if sometimes,void pointer arithmetic "works" without any error.
I'm working on a homework problem and I already got the answer correct, but it was the result of adding operators out of frustration so I'm hoping someone can clarify this for me. I'm testing to see if a number is positive or negative, return 1 if x > 0, return 0 otherwise. Only using the bit operations ! ~ & ^ | + << >> Here's my answer: !(x >> 31 | !x) When I work this out on paper my understanding of it falls apart. move the sign bit all the way to the rightOR that bit with !xpositive would be 0 | 1negative would be 1 | 0! the result, which always, not matter what, ends up as 0!(0 | 1) = 0!(1 | 0) = 0 What am I understanding wrong?
Where you're off is in #2: if x is positive, x >> 31 == 0 and !x == 0 so !(0 | 0) == 1if x is negative, x >> 31 == 1 and !x == 0 so !(1 | 0) == 0if x is zero, x >> 31 == 0 and !x == 1 so !(0 | 1) == 0
How do I get the numerical value/position of a character in the alphabet (1-26) in constant time (O(1)) without using any built in method or function and without caring about the case of the character?
If your compiler supports binary literals you can use ``` int value = 0b00011111 & character; ``` If it does not, you can use 31 instead of 0b00011111 since they are equivalent. ``` int value = 31 & character; ``` or if you want to use hex ``` int value = 0x1F & character; ``` or in octal ``` int value = 037 & character; ``` You can use any way to represent the value 31. This works because in ASCII, undercase values are prefixed with 011, and uppercase 010 and then the binary equivalent of 1-26. By using the bitmask of 00011111 and the AND operand, we covert the 3 most significant bits to zeros. This leaves us with 00001 to 11010, 1 to 26.
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 I am trying to export some C code for my application in Android Studio using the NDK, but I am having this problem in the compilation. Can someone help me?
rindexis an old name (averyold name!) forstrrchr. If it looks like it's trying to find characters in strings, try changing all the calls tostrrchr. (Similarly, you may need to changeindextostrchr.)
I would like to change the default label color of a GtkCheckButton. I surely need to access its GtkContainer or GtkBin and iterate through its children. However, I have not found any code to do this. I have: ``` GtkWidget* myCheckbox = gtk_check_button_new_with_label("Hello"); GdkColor color; gdk_color_parse ("#FF0000", &color); gtk_widget_modify_fg (myCheckbox, GTK_STATE_NORMAL, &color); ``` But it modifies just the border's color. Any ideas?
OK, this code works: ``` if(GTK_IS_BIN(myCheckbox)) { GtkWidget *child = gtk_bin_get_child(GTK_BIN(myCheckbox)); GdkColor color; gdk_color_parse ("#FF0000", &color); gtk_widget_modify_fg (child, GTK_STATE_NORMAL, &color); } ``` The idea came fromFinding children of a GtkWidget. HTH
I have text files weighing ≈ 200GB.I'm storing in DB pairs ofkey-position_in_file,and reaching the data usingfseek. Is there recommended way to compress the files,and seek to position in a compressed file,without decompressing from the beginning of the file. [I prefer to use C as language][No need to perform writes. No need to be super fast]
Here is anexample of random access of deflated data. It runs through the compressed data once to build a random access index with entry points at about every 1 MB of uncompressed data. (You can change that density.) Each entry point is at a deflate block boundary, and saves the 32K of uncompressed data that precedes it in order to populate the sliding dictionary for decompression.
I have set stack size to 2000Kb by ulimit -s 2000 and ulimit -Ss 2000 for hard limit. And in the below program i have allocated appox 2040000(510000 x 4) bytes which is less than i limited i.e,. 2048000(2000*4)bytes but i see that my program crashes! Can anybody suggest why this happens. ``` #include <stdio.h> #include <malloc.h> int main() { int a[510000] = {0}; a[510000] = 1; printf("%d", a[510000]); fflush(stdout); sleep(70); } ``` EDIT 1: Crash is not because of the array index out of bound as i tried lower index and still crashes. This happens only when i limit by ulimit.
int a[510000]will be an array with index from0to509999.a[510000]is outside the array range.
The code excerpt: ``` int main(int argc, char *argv[]){ PySys_SetArgv(argc, argv); ``` produces error message error: cannot convert ‘char**’ to ‘wchar_t**’ for argument ‘2’ to ‘void PySys_SetArgv(int, wchar_t**)’ How do I convertargv?
You could look into whether your compiler supportswmain. If so, you can replacemainwith: ``` int wmain(int argc, wchar_t *argv[]) { PySys_SetArgv(argc, argv); ```