question
stringlengths
25
894
answer
stringlengths
4
863
I am trying to work on pointers. I am under a situation that i want to traverse the linked list after the second node(from third node). I have the basic idea to traversing the linked list is: ``` while(temp!=NULL) { temp=temp->next; } ``` So what i want is this linked list must start from third position. Could any...
If your list istempthentempis also the first element. Thentemp->nextwill be second element, andtemp->next->nextwill be the third. So if you write ``` temp = temp->next->next; ``` tempwill be pointing to the third element and you can start your traverse from there.
I'm getting this error: ``` code : ORA-00000 msg : The statement is not scrollable ``` This is the code: ``` char query[] ="select max(VQC_ID) from vqc"; OCI_Statement* st; st = OCI_StatementCreate(cn); OCI_ExecuteStmt(st, query); OCI_Resultset* rs; rs = OCI_GetResultset(st); OCI_FetchFirst(rs); ...
Read ocilib documentation and you will have the answer.... You need to declare the statement 'scrollable' in order to useOCI_FetchFirst. If you just want to fetch only one value, useOCI_FetchNext
How can I clonechar** argvtochar** copy? original -char** argvcopyto -char** copy
Withargcbeing the number of elements in argv: ``` char** copy = (char**)malloc(argc * sizeof(char*)) ; for (int i = 0; i < argc ; i++) { copy[i] = strdup(argv[i]) ; } ``` Freeing the allocated memory once we are done with the clone, is left as an exercise to the reader.
I wanted to write a code which makes a uppercase of first letter of string 1 and 3 and printing those. I tried the code below this but compiler givesİNVALİD CONVERSİON OF CHAR TO İNTWhat is wrong with this code should i try with strlen and for loop? This is code;int main() { char str1[] = "elektrik"; char str2[...
You need ``` *str1 = toupper(*str1); ``` ... Asssuming thatstr1is a pointer to char (and include the appropriate header files)
Is there a way to find out if a particular interface exits using C .
getifaddrs. There is an example program on the manpage. Basically you would have to just loop through the list looking for a match. Optionally you can look atif_nameindexif_indextonameandif_nametoindex
This question already has answers here:Pointer arithmetic for void pointer in C(10 answers)Closed9 years ago. I am getting the unknown size error from the code below, ``` atmel_device_info_t *info; int *ptr = row->offset + (void *) info ``` It is a casting problem, what should I do to fix the error? thank you...
You cannot portably do arithmetic with avoid *pointer. This makes sense, since it's a pointer to an unknown type of data, that data has no intrinsic size. The size of the pointed-to data is a central part of doing arithmetic. usually a "byte" pointer works: ``` int *ptr = (int *) ((unsigned char *) info + row->offse...
I want to determine programmatically if my shell extension is called as acontext menu handleror adrag-n-drop handler. I have registered my shell extension in proper location with same CLSID. Registry: ``` [HKEY_CLASSES_ROOT\*\shellex\ContextMenuHandlers\{E991C840-C1EB-455C-AD64-282473005C58}] @="Test Context Menu" ...
You can detect type of extension with which shell wants to work only inside IShellExtInit.Initialize. For context menu handler pidlFolder is zero, for drag and drop handler pidlFolder is PIDL of folder.
``` while( rd = read(fd1, buf, 512) != 0) { len += rd; if(readed < 0) perror("read: "); } ``` MAN pages says, that read() returns number of read bytes, but in my case this code returns number of blocks(depends of 3rd argument) or number of iterations. for example, I have file with 36 symbols and this co...
``` rd = read(fd1, buf, 512) != 0 ``` means ``` rd = (read(fd1, buf, 512) != 0) ``` The result of!=is always either0or1. You probably meant ``` while ((rd = read(fd1, buf, 512)) != 0) ```
I have noticed that an empty array in the end of the structure is often used in open source projects: ``` typedef struct A { ...... void *arr[]; } A; ``` I want to know is this a C standard? Or only OK for gcc compiler?
As of C99, it is now a C standard. Pre-C99 compilers may not support it. The old approach was to declare a 1-element array, and to adjust the allocation size for that. New way: ``` typedef struct A { ...... void *arr[]; } A; int slots = 3; A* myA = malloc(sizeof(A) + slots*sizeof(void*)); myA->arr[2] = fo...
I have to test the given folder path is a mount point or it is in local to my system with c code. I read on net that/etc/mtabfile have entry for mounted point. I can check that file but is their any system call or any function to check mount point. My kernel version is2.6.28.10.
These functions can be used for data structure access the mtab file: ``` FILE * setmntent(const char *file, const char *mode) int endmntent (FILE *stream) struct mntent * getmntent (FILE *stream) struct mntent * getmntent_r (FILE *stream, struct mentent *result, char *buffer, int bufsize) int addmntent (FILE *str...
I am starting to learn pointers in C. Why do I have an error in line 8 at&i? This is the source: ``` char * func(char *d, char *str) { return d; } int main(int argc, char *argv[]) { char *i = NULL; func(&i, "aaa"); // line 8. here I have the error (in "&i") } ```
You are passingchar**and the function expects achar*. You need to passiwithout the address of & operator, because this way you are taking the address of the pointer. Just passfunc(i, "aaa");
Instead of being an int, I would like prev to be a pointer to another Vertex. However, I can't declare prev as a VertexPointer because the typedef for VertexPointer comes afterwards. How should I declare prev? ``` #include <stdio.h> #include <stdlib.h> #include <time.h> //function generates a random float in [0,1...
You could try this ``` typedef struct Vertex{ int key; struct Vertex *prev; float loc[4]; } Vertex; ```
I need some help with my assignment. We are supposed to generate and print all 52 cards, but I'm having trouble understanding how to print "Ace", "2".....etc.
``` for(i=0; i < 52; i++) { if(i%13==0) { printf("Card %2d = King %s\n", i,suits[i/13]); } else if(i%13==1) { printf("Card %2d = Ace %s\n", i,suits[i/13]); } else if(i%13==11) { printf("Card %2d = Jack %s\n", i,suits[i/13]); } else if(i%13==12) { ...
So, I have used fork() where the parent is opening a file and reading its contents into a buffer and sending the buffer from the write-end (fd[1]) to the read end (fd[0]) The child process is responsible for reading in the buffer. I want to redirect whatever is in fd[0] to stdin, so I can use Unix commands on it. To ...
It seems to be quite OK. Maybe you could close some fds afterdup2: ``` // in child process dup2(fd[0], STDIN_FILENO); close(fd[0]); close(fd[1]); ``` EDIT: There seems to be typo:"/bin/grep/" It should be:"/bin/grep"
I need to implement thestrcpysource in C. I dont understand why am i have this eror in line 15 (in the line- "return saved;"): Error: return value type does not match function type this is the full source: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> char str_cpy(char *d, co...
You are returningsavedwhich is of typechar *, so declare you're function returningchar *as, char * str_cpy(char *d, const char *s)
Forwrite(fd[1], string, size)- what would happen ifstringis shorter thansize? I looked up the man page but it doesn't clearly specify that situation. I know that forread, it would simply stop there and read whateverstringis, but it's certainly not the case forwrite. So what is write doing? The return value is stillsi...
When you callwrite(), the system assumes you are writing generic data to some file - it doesn't care that you have a string. A null-terminated string is seen as a bunch of non-zero bytes followed by a zero byte - the system will keep writing out until it's writtensizebytes. Thus, specifyingsizewhich is longer than yo...
``` #include <stdio.h> #define MAX 9 void main (int argc, char *argv[]) { printBoard(); } void printBoard(void) { int row,col; row=col=0; for(row;row<MAX;row++) //row navigation for(col;col<MAX;col++){//column navigation printf("r:%d,c:%d",row,col); }/*End Column Nav*/ printf("\n"); } `...
Try adding afunction prototypeforprintBoardabovemain()e.g., ``` void printBoard(void); void main(...) ```
My C application reads a file character by character and stores the char value in a char array. At a certain point, the char array needs to be cleared so another value can be entered. However, when I try to clear it, the chars still remain in the array. This is how I reset the array: ``` void resetArray(){ opera...
Setting the first character as the null terminator will leave the rest of the array in memory intact. Printing the string will not print them, but they are still there. You have to clear the remaining memory. ``` memset( array , 0 , sizeof( array ) ) ; ```
What's the difference betweenstrtokandstrtok_rinCand when are we supposed to use which?
strtokis equivalent to (and often defined as): ``` char *strtok(char *str, const char *delim) { static char *save; return strtok_r(str, delim, &save); } ``` in general, you should usestrtok_rdirectly rather thanstrtok, unless you need to make your code portable to pre-POSIX-2001 systems that only supportstrt...
I don't really understand the difference between "closing the write end of the pipe" and "not writing anything to the pipe". If I don't write anything to the pipe and the pipe is empty, why is the read end simply blocked rather than reading an EOF? How is that different from closing the write end?
Reading an EOF from a pipe (or from anything) indicates that there's no more input, and that there won't be any more input in the future. If there's no input available at the moment, but the pipe hasn't been closed, then the reader will (by default) block waiting for input; if the writer then writes to the pipe, that...
what is the difference between these operators in C and in unix shells? In C doesn't the && mean do the first process and if it is true do the second process? How would it be different in unix shells? Thanks edit i don't mean the difference between && and ||, but rather how they differ in c language and in unix shell...
Precedence is one big difference. Consider the following: ``` a || b && c ``` InC, ifais true, neitherbnorcneed to be evaluated, since the expression is parsed asa || (b && c). However, in shell, ``` true || false && echo foo ``` will outputfoo, since it is parsed the same as(a || b) && c. Also, keep in mind t...
I think reading memory should not cause any issue eg ``` char *d=""; char *d2="test"; memcmp(d,d2,10); ``` Canmemcmp()everfail ?
Your assumption is incorrect, as reading memory at an address not mapped into the process's address space will cause aSEGV. Particularly reading address 0 (on almost all architectures), and reading kernel memory space (if it's even mapped in), but in general reading logical memory to which no physical memory is mapped...
This post: Empty or "flush" a file descriptor without read()? , says that it is possible to do alseek()on a fd you don't want to read from, thereby avoiding unnecessary copying, but this does not apply to fds I create withtimerfd_create(). Why is this so and does there exist a workaround (except to useread(), which ...
timer_fds are not seekable. Not everyfdis. Usereadto read the relevant bytes. Note that contrary to thePOSIXtag, these calls are Linux specific. From the man page: ``` CONFORMING TO These system calls are Linux-specific. ```
If you have: ``` unsigned char data[] = {0x00, 0x02, 0xEE}; ``` Would the length be 3 or would the hex values be representative of two or more bytes and thus equal out to something like 6?
The array is of typeunsigned char[], therefore the values it contains are (as big as)unsigned chars, which should be 1 byte. Since the array contains 3 values, its total size is 3 bytes. Thesizeofoperator can help you figure this stuff out: ``` unsigned char data[] = {0x00, 0x02, 0xEE}; int main(void) { printf("s...
My task is to make a program in C that opens a pipe, then one of the process' executes the ls command and writes the output into the pipe. The other process should then read it and display it in the shell. So, the main problem I'm struggling with is this: ``` execl("/bin/ls", "/bin/ls", NULL); ``` How can I redirec...
Use popen() instead of execl() to read the application output, seehttp://linux.die.net/man/3/popen
This ``` #include <stdlib.h> // test.c int main() { double *arr = (double*) calloc(1000, sizeof(arr)); for (int i = 0; i < 1000; i++) arr[i] = 1; free(arr); return 0; } ``` compiled as ``` gcc test.c -std=c99 -o test ``` produces the outputAborted (core dumped)when run on Cygwin as./test....
Change ``` double *arr = (double*) calloc(1000, sizeof(arr)); ``` to ``` double *arr = (double*) calloc(1000, sizeof(double)); ``` UPDATE: sizeof(double)andsizeof(pointer)depends on architecture. In your case they are different.
I am using Ubuntu. I have written code to open another terminal application using C program. Now I want to route the output " hello world " to new started terminal window...? Can anyone tell me the code or procedure to implement it...?
Generate the Terminal using system("gnome-terminal") Then sleep for 1 seconds, then open /dev/pts and read the file one by one and get the name. With the help of that name get the status of the file and compare the access time of the file like ``` if(Old_time < Status.st_atime) { Name=File_Name->d_name; Old_...
Can anyone tell me the procedure or C code to start another terminal after executing that C code. Actually I want to write a program which can start a new terminal without clicking to terminal icon. Can anybody guide me or provide me with C code.
Use the below C code: ``` #include "stdio.h" int main(void) { system("gnome-terminal"); return 0; } ``` system() function will run the terminal command's you can run any linux command using the system function in the C code.
I learnt that child process gets new process id after running api, posix standard fork() & i win32 CreateProcess() Does the child process gets unique process name different from parent process in both unix and windows world? Because i need to measure the min/max of cpu&mem utilization of all the processes(using na...
A process does not have a name in Windows. It has a unique process ID, and a filename which the process was launched from. Everything in the Win32 API that deals with processes is based on process IDs only, not on names. There are various API functions that allow you to retrieve the filename that was used to create...
I am trying to run this and cant seem to find out why it wont run. Thank you in advance. Please know I am new. ``` #include <stdio.h> #include <math.h> int main(void) { float IR; float invested; float time; printf("Please enter the following to be calculated:"); scanf("Interest rate: %f\n", &IR); scanf("Amount inve...
^is not the power function. you need to useans = invested * (1 + pow(IR, time)); ^is a Bitwise exclusive ORXOR.
Can we schedule a program to execute every 5 ms or 10 ms etc? I need to generate a pulse through the serial port for 1 khz and 15 khz. But the program should only toggle the pins in the serial port , so the frequency has to be produced by a scheduler. is this possible in linux with a rt patch?
I believe a better solution is to put your "generate a pulse" function in a loop, for example: ``` for (;;) { generate_pulse(); /* generate a pulse */ sleep(5ms); /* or 10ms */ } ```
I'm trying to access a website url(https) and read back it's contents(a json from an api). What c commands would I use?
Have you looked atlibcurl? Never used it, but I've seen it used quite a bit. Otherwise it's going to be somewhat system dependant, if you're on linux you could use popen() on a command that dumps to stdout.
Why is rand_float only returning the value 0.000000? ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int test, int numpoints, int numtrials, int dimension){ //generate a random number float r = rand_float(); //print it printf("%f", r); printf("\n"); } //function generates...
Note the return type of rand_float isint. So the[0,1)value (in the float) is beingimplicitly castto0(an int), which is all that function will ever return. Fix the return type - by changing it frominttofloat. Also, either forward-declare the rand_float function or move the function definition ahead of the main funct...
Trying to generate a psuedo-random float btwn 0 and 1. Getting this error when I run the code: ‘RAND_MAX’ undeclared (first use in this function) ``` #include <stdio.h> #include <time.h> int main(test, numpoints, numtrials, dimension){ //generate a random number srand(time(NULL)); float r = (float)(ran...
To useRAND_MAXin C, you need to include its header:#include <stdlib.h>rand()/RAND_MAXis an integer division, if you want floating division, you should covert it tofloatfirst, then divide:(float)(rand()) / RAND_MAXYou need to define your main as:int main ( int arc, char **argv )
I am trying to use a function as a parameter for another function. I want to get different computations depending on the function I pass. I tried implementing this by writing this program:http://pastebin.com/CJfFarVaCode:The problem is I get this error over and over again: ``` trapeze.c:14:8: error: conflicting types...
Change the call totrapeze: ``` exp_2 = trapeze(0, 1, n, exp2); exp_1 = trapeze(0, 1, n, exp1); ```
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do...
TheGD libraryis basic but still quite useful. (It's embedded into the PHP language.) Or, if you don't want to rely on external libraries, output your data to a text format likePPM, and then convert it to a different format in your favourite graphics editor (or a tool like ImageMagick).
Hi I'm doing homework for my computer science class and I'm stuck on this question. Given a IEEE floating-point format of n bits with e exponent bits, give expressions for a)The largest finite positive number.b)The largest (closest to 0) negative number.c)The minimum ULP. in terms of n and e. Could somebody help w...
Floating point numbers can be expressed as ``` (-1)^Sign * Number * 2 ^ Exponent ``` And usually you have 23 bits for the number, 8 for the exponent and 1 for sign. With that you could answer 1) and 2). I don't know what ULP is.
If we write: ``` //in main FILE *p = fopen("filename", "anymode"); ``` My question is: to what isppointing?
The file pointerpis pointing a structure handled by the C library that manages I/O functionality for the named file in the given open mode. You can't tell, a priori, whether what it points at is statically allocated memory or dynamically allocated memory; you don't need to know. You treat it as an opaque pointer. N...
I'm learning C and have a question of:Explain the difference between int (*twod)[3] as a parameter as compared to int *(twod[3]).I don't really know what the difference is completely. If someone could help me to understand the difference that would be much appreciated.
Wellthiscan be a useful site: The first one: declare twod as pointer to array 3 of int, which means visually: ``` twod ---> [1, 2, 3] ``` The second one: declare twod as array 3 of pointer to int Visually: ``` twod[ twod0, twod1, twod2] | | | int int int ```
So far, I've tried (without success): QJsonDocument– "document too large" (looks like the max size is artificially capped at1 << 27bytes)Boost.PropertyTree– takes up 30 GB RAM and then segfaultslibjson– takes up a few gigs of RAM and then segfaults I'm gonna tryyajlnext, but Json.NET handles this without any issues ...
Check outhttps://github.com/YasserAsmi/jvar. I have tested it with a large database (SF street data or something, which was around 2GB). It was quite fast.
This question already has an answer here:Why does autoconf erroneously find a function which isn't available later?(1 answer)Closed9 years ago. Say inconfigure.acI check for the availability of a C function, like ``` AC_CHECK_FUNCS( [arc4random] ) ``` And later the configure process is positive on this function: `...
It generates a test program that declares a function with the same name, then compiles and link it. Change a few characters in the name of the function (to make the test fail) and check config.log, you'll see the source code of the test program when it fails.
I'm basically using the C function, fscanf() to read in data from a file. using fopen and checking it I know the file is being opened successfully by checking the return value. The file is formatted with Char, Int, Int. The issue I have is I can only read in one line at a time and the loop exits. Would appreciate if ...
You want if(datatest==-1) rather than if(datatest = -1) One tests equality, while the other is an assignment expression. Any "assignment expression" inCwill return the value to which the variable is assigned. So for example,datatest= -1will return-1.
I am trying to send my port number to a function as const char *. The memory address on receiving is out of range. Can someone tel me what is the correct way of doing this ? This is my code Inside main() ``` socket_open("host", 12345); // host and port number ``` On function side ``` socket_open(char * host,int p...
Ifgetaddrinfois expecting a string you must convertport(anint) to one first. Here is one way: ``` char portStr[MAX_PORT_STR_LEN]; snprintf(portStr, MAX_PORT_STR_LEN, "%d", port); ``` Now you can send it togetaddrinfo: ``` error = getaddrinfo(host, portStr, &hints, &res); ```
Can you cast an object to a string of hex data (similar to how packets are sent) and then store that and then cast the object back? I know its possible with C structs which are basically objects undearneath in C++. Compatibility of the serialization across different systems isn't important. ``` auto obj = new Someth...
No. Reasons:a) Dynamic allocated memory, ie. pointer in the struct/class.b) Endianess, int-size, padding etc. of the struct, order of the members... Other things:"If" it would be possible, there is no reason to create a full objectwith constructor call before overwriting it.And in my opinion, you´re overusing auto.
``` #include <stdio.h> int gcd() { int i,j,rem; printf("Enter two integers: "); scanf("%d%d",&i,&j); while (i !=0) { rem = j % i; j=i; i=rem; } printf("Greatest common denominator is %d\n",j); } int main() { gcd(); return 0; } ``` I am learning C using "C programming a modern approach 2nd ...
I recommend passing the numbers as an array ofintand then applying the gcd algorithm on it recursively (preferably). ``` int gcd(int *array, int n) { if(n == 0) { //find gcd using while loop of array[n] and array[n + 1]. store in result. return result; } return gcd(int *a, n -1); } ```...
in cmake, can cmake folder and CMakeLists.txt sit in different folder?\ usually, cmake folder and CmakeLists.txt are in same source root directory. But, to re-use cmake folder for different project, is that possible to put cmake folder into other places? Is this a good approach ans thinking? Thanks,
I don't see any problem with that. You just have to know the relative path from the ${CMAKE_SOURCE_DIR} or the absolute path in order to use it in your CMake files.
i am trying to execute following code , though i know that "syntactically" ordered construct should appear within the for loop, but why the code gets stucked within ordered clause i.e. execution should have given me a straight away "syntax error". ``` omp_set_num_threads(11); #pragma omp parallel { // 1 #pragma om...
#pragma omp orderedmay only appear inside#pragma omp for orderedconstruct. Source
I want to add someprintfstatements of my own in the BSD network stack. But after adding them I cannot see the messages coming up on the console of my machine. I tried to add some in the netisr ( sys/net/netisr.c ) . Cannot even find the already presentprintfstatements. A noob at kernel programming. ``` netsmp_lockini...
The kernel can't use the C Standard I/O facilities. It must use a logging facility. For example,sys/netinet/in.cuses ``` log(LOG_INFO, "in_scrubprefix: err=%d, old prefix delete failed\n", error); ``` to communicate to the world outside what happened.
When I write a C program, I often need to name a function like this: conn_pool_init (In this function, initialize the connection pool, and start it). I often consider what is the best opposite function name. I have seen such as conn_pool_end, conn_pool_stop, or conn_pool_deinit. So I want to ask if there is a convent...
In linux kernel drivers, usually you have amodule_init()&module_exit()functions. module_init()is where you initialize stuff and module_exit()is where you clean up, free memories, destroy data structures and exit.
In "Windows Task Manager" tool, under "Allpications" tab there is a function called "End Task". I want to accomplish this job through terminal. Is there any way to do it? It is not close a process which can be done with command "taskkill". Because may be several "task" instances are pointing to one process. For examp...
Roll your own. To do so: Find the window, probably by title/caption usingFindWindow()orEnumWindows()and then send it aWM_CLOSEmessage usingSendMessage().
im trying to find the average coffee drank by the programmers. I can find and display the average but it just seems wrong, the way it is displayed. I just can't manage to extract the last line which displays the average. ``` char poste[]={'A','P','A','P','A','O','P','P','O'}; int nbCafe[]={3,5,2,1,7,1,0,3,2}; int pro...
If you just want to display the average, then just print the average. Move the printf outside the for loop. ``` for(i=0;i<9;i++) { if (poste[i]=='P') { progonly+=nbCafe[i]; progmoyenne=progonly/4.0; } } printf("%f\n",progmoyenne); ```
in cmake, can cmake folder and CMakeLists.txt sit in different folder?\ usually, cmake folder and CmakeLists.txt are in same source root directory. But, to re-use cmake folder for different project, is that possible to put cmake folder into other places? Is this a good approach ans thinking? Thanks,
I don't see any problem with that. You just have to know the relative path from the ${CMAKE_SOURCE_DIR} or the absolute path in order to use it in your CMake files.
i am trying to execute following code , though i know that "syntactically" ordered construct should appear within the for loop, but why the code gets stucked within ordered clause i.e. execution should have given me a straight away "syntax error". ``` omp_set_num_threads(11); #pragma omp parallel { // 1 #pragma om...
#pragma omp orderedmay only appear inside#pragma omp for orderedconstruct. Source
I want to add someprintfstatements of my own in the BSD network stack. But after adding them I cannot see the messages coming up on the console of my machine. I tried to add some in the netisr ( sys/net/netisr.c ) . Cannot even find the already presentprintfstatements. A noob at kernel programming. ``` netsmp_lockini...
The kernel can't use the C Standard I/O facilities. It must use a logging facility. For example,sys/netinet/in.cuses ``` log(LOG_INFO, "in_scrubprefix: err=%d, old prefix delete failed\n", error); ``` to communicate to the world outside what happened.
When I write a C program, I often need to name a function like this: conn_pool_init (In this function, initialize the connection pool, and start it). I often consider what is the best opposite function name. I have seen such as conn_pool_end, conn_pool_stop, or conn_pool_deinit. So I want to ask if there is a convent...
In linux kernel drivers, usually you have amodule_init()&module_exit()functions. module_init()is where you initialize stuff and module_exit()is where you clean up, free memories, destroy data structures and exit.
In "Windows Task Manager" tool, under "Allpications" tab there is a function called "End Task". I want to accomplish this job through terminal. Is there any way to do it? It is not close a process which can be done with command "taskkill". Because may be several "task" instances are pointing to one process. For examp...
Roll your own. To do so: Find the window, probably by title/caption usingFindWindow()orEnumWindows()and then send it aWM_CLOSEmessage usingSendMessage().
im trying to find the average coffee drank by the programmers. I can find and display the average but it just seems wrong, the way it is displayed. I just can't manage to extract the last line which displays the average. ``` char poste[]={'A','P','A','P','A','O','P','P','O'}; int nbCafe[]={3,5,2,1,7,1,0,3,2}; int pro...
If you just want to display the average, then just print the average. Move the printf outside the for loop. ``` for(i=0;i<9;i++) { if (poste[i]=='P') { progonly+=nbCafe[i]; progmoyenne=progonly/4.0; } } printf("%f\n",progmoyenne); ```
I have written a simple "hello, world" program from herehttp://www.cprogramming.com/tutorial/c/lesson1.html cprogramming: lesson 1, the output is shown then the terminal prompt shows up in the following one. When executing another program: ``` #include <stdio.h> main() { int age; printf("How old are you?"); scanf("%...
Alignment can be done using escape sequences. In your case u need to use \n for new line
Now I have encounter a problem as below: ``` int foo(void){ char a[10] = "foo"; char b[10] = {"foo"}; ... } ``` I used gdb to inspect the content of both 'a' and 'b' and they looked exactly the same. Is there any difference between the variabel a and b?
They are the same: C11 §6.7.9 InitializationAn array of character type may be initialized by a character string literal or UTF−8 string literal,optionally enclosed in braces.Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize...
I need to open and read an encrypted file in a C++ program. Do I need to keep the password in the program? Are the user able to get the password when the program is disassembled? What's the best way to keep the user away from the password?
If you just put the password hard coded then, yes. With some dissassembly it is easy to get the password (you don't even need to dissassemble fully, only get the strings). You can try to obfuscate the password somehow, such as computing a hash of something that creates the password (this is very simplistic). In the en...
I need to open and read an encrypted file in a C++ program. Do I need to keep the password in the program? Are the user able to get the password when the program is disassembled? What's the best way to keep the user away from the password?
If you just put the password hard coded then, yes. With some dissassembly it is easy to get the password (you don't even need to dissassemble fully, only get the strings). You can try to obfuscate the password somehow, such as computing a hash of something that creates the password (this is very simplistic). In the en...
In C I wrote a code usingsystem()to start another application , say abc.exe .Now how do I find if abc.exe has exited and when it has done so , I want to run another application, say xyz.exe .
system()is synchronous i.e. when it is done you simply get to the next instruction of your code, so basically it should be : ``` system("abc"); system("xyz"); ``` alsosystemreturns the exit status of executed program, so if there is a dependency between programs andxyzcan't be executed without successful execution ...
I am new to C and I have no idea how to handle this array: ``` char *args[MAX_LINE/2 + 1]; ``` What does this line mean exactly? Is it a pointer to an array of chars? The assignment given with this was to fill this array with multiple string tokens, but I don't understand how a char pointer can store a whole string?...
``` char *args[MAX_LINE/2 + 1]; ``` argsis an array of pointer to char of sizeMAX_LINE / 2 + 1. Each element is achar*, i.e., each element may be a string. You'll have to initialize them though (i.e., point them somewhere valid.) For example, to read from stdin: ``` args[0] = malloc(some_size); /* read a string f...
This question already has answers here:How to get the return value of a program ran via calling a member of the exec family of functions?(6 answers)Closed9 years ago. I have the following code in c: execlp("ReturnValue.c"); ReturnValue.c should return an integer between 0-3, and since execlp won't return anything w...
You could do something like this: ``` pid = fork(); if (pid == 0) { execlp("ReturnValue.c", ...); } else if (pid > 0) { waitpid(pid, &status, ...); /* extract the return status */ WEXITSTATUS(status); } else { /* fork() error */ } ``` Seewaitpid(3)orman 3 waitpid
Whenever I try to compile my c program on mac it gives the following error. I am completely clueless about it. 'sys/cdefs.h' file not found
have you installed "Xcode Command Line Tools" ? just install it in your terminal. ``` sudo xcode-select --install ```
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.Closed9 years ago.Improve this question ``` char * abc = "ABC"; int i; printf("%s\n", abc); for (i = 0; i < strlen(abc); i++) { abc[i] = tolow...
char * abc = "ABC";defines a string literalwhich cannot be changed during runtime.Usechar abc[] = "ABC"; edit: Maybe you "can" change it in some cases,but there is no guarantee for anything.It could work, it could crash,or doing other strange things with your programwhich are not immediately recognizable.
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.Closed9 years ago.Improve this question For sockets, which side does the majority of the work? I've been given this question to answer and don't r...
Client should know the details of the server it connects to. Theconnectcall is instantaneous. But on the other hand the server should be continuously listening to a port for any incoming connections in theacceptcall. So technically a server would take more of the processor time. Once the connection is established t...
So I need to print a title using \ __ || it will become something like this ``` ______ |_ _ \ | |_) | | __'. _| |__) | |_______/ ``` how to print all, and i get error even though i use \ to print \
To print \ you need to put \\ in your string, because \ is an escape (e.g. \n for a new line).
``` #include <stdio.h> #include <stdlib.h> int constChars(const char* str) { int size = sizeof(str)/sizeof(char); printf("Size is %d.\n", size); int i = 0; for (i=0;i<size;i++) printf("%c ", str[i]); return 0; } int main(void) { char a[10]={'b','c','d','e','f','f','f','f','f','f'}; ...
When you pass an array to a function, it gets rewritten as a pointer, wheresizeofinformation is lost. If you did this inmaininstead, i.e: ``` char a[10]={'b','c','d','e','f','f','f','f','f','f'}; int size = sizeof(a)/sizeof(a[0]); printf("Size is %d.\n", size); ``` It prints10as expected. But once you pass it tocons...
Similar to GCC, clang supports stopping at different stages when processing C/C++. For example, passing a-Eflag causes it to stop after the pre-processor and-cstops before linking. So far, I am aware of, -E: pre-processing-fsyntax-only: syntax checking-S: assembly-c: object code Am I missing any stopping points bet...
You can also use-S -emit-llvmto generate LLVM IR assembly files and just-emit-llvmfor LLVM bitcode object files. These are the language-independent code representations that clang and other LLVM front-ends generate and pass to LLVM to compile into an executable.
I wanted to know if you can use a variable to specify field width, for example: ``` float g = 123.4567; int x = 3; int y = 4; printf("%(%d).(%d)f", x,y,g); ``` I want my output to be: "123.4567", basically the same as ``` printf("%3.4f"); ``` I don't think the compiler will read the current format, but maybe there...
``` printf("%*.*f", x, y, g) ``` The*in a format specifier means "I'll pass this number as an argument."
I added this to my.profile but I stil get warnings : ``` QMAKE_CXXFLAGS_WARN_OFF = -Wunused-parameter ```
UseQMAKE_CXXFLAGS_WARN_ON += -Wno-unused-parameter,because the flags in QMAKE_CXX_FLAGS will always before QMAKE_CXXFLAGS_WARN_ON, and QMAKE_CXXFLAGS_WARN_ON contains the flag -Wall. This means your flag will be overwrite by flag -Wall.
Are there all types of files that can be opened with notepad like .txt, .c or .java the same ones that can be opened withfopen()or is there any exception?
The short answer is that C does not care about file types and therefore your assumption is true. The long answer is that the short answer only applies to regular files (all of the ones listed by you are regular files), in some cases it does not apply to special files like device files, FIFOs. On Windows, you might ha...
Hello my software should print the abc but unfortunately it does not work I think the problem is related to the line 19 so if someone could tell me why this is happening I appreciate it My code- ``` #include <stdio.h> #include <string.h> #define NUM_ABC_LET 27 void ABC(char abc[NUM_ABC_LET]); int main() { char...
If you enable warnings in your compiler (e.g.gcc -Wall -Wextra -Werror) it will tell you the problem straight away: you are using strcat in a nonsensical way.
If I type 0.01 or 0.02 the the program just exits immediately. What do I do? ``` #include <stdio.h> char line[100]; float amount; int main() { printf("Enter the amount of money: "); fgets(line, sizeof(line), stdin); sscanf(line, "%f", &amount); if (amount == 0.0) printf("Quarters: 0\nDimes: 0\nNickels: 0\nPenn...
What is the most effective way for float and double comparison? You should use something like this ``` bool isEqual(double a, double b) { return fabs(a - b) < EPSILON; } ``` or this ``` #define ISEQUAL(a,b) ( fabs((a) - (b)) < EPSILON) ``` and define EPSILON ``` #define EPSILON (0.000001) ```
My code: ``` char* fileName; fileName=g_filename_from_utf8(gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)),-1,NULL,NULL,NULL); ``` The string returned from gtk_file_chooser_get_filename() cannot be referenced, so it can't be freed. Is this a memory leak? Should I assign it to an identifier and then fre...
Yes, this will be a memory leak. You have to free it using g_free() as notedhere Also you have to check forNULLasgtk_file_chooser_get_filenamecould returnNULLon error as well.
I'd like to ask if it's possible to do something like this: For example I have a string B with text and I wrote a code like this: ``` puts("Enter the number of character in string B:"); gets(number); ``` I would like that a program would print a character that user has entered. For example char B[] = {"Shop"}; us...
Regard to Joe`s answer: Do not forget to check negative value: ``` if (number <= strlen(B) && unmber>=0) printf("%c", B[number - 1]); else printf("Entered number: %d : is out of range\n", number); ```
How do I execute below mentioned command using exec inside a C language program in linux? wget -P ./Folder http://www.google.com
execl("/usr/bin/wget", "-P", "./Folder", "http://www.google.com", NULL); Unless you have to use exec, I suggest usingsystemfrom libc, since it is more portable (in case you ever decide you want to port it).
Recently my C professor gave us the following puzzle: ``` char c1, c2, c3; c1 = 'a'; c2 = 'e'; c3 = c1 * c2; printf("%c",c3); ``` Answer: E However, I'm a bit confused as to how this would be solved intuitively other than having the product already memorized. From what I've researched the int values of the charact...
first,97 * 101is9797. (In hex,0x2645). andcharis 1byte. so0x2645become0x45. 0x45 == 69 == 'E'. That's it.
This very simple example ofexec()system call. Here, I am trying to callexeclp()twice. But, I am not getting excepted output. It shows output only for first call with current directory. ``` #include <stdio.h> #include <unistd.h> int main() { int ret1,ret2; ret1 = execlp( "pwd", "pwd", (char *) 0); ...
execlp()replacesthe current process image with a new process image. It doesnot return(unless there was an error starting the new process). Therefore the secondexeclp()call is never reached.
As we known, we can usepoll/selectwith Netmap:http://info.iet.unipi.it/~luigi/netmap/ Is it possible to useepolland whether it makes sense to use epoll with Netmap, or it has no advantages in speed?
netmap author here: we have changes to enable epoll() for linux (the equivalent kevent() on FreeBSD is already supported). The advantage only exists when you have to handle several file descriptors in the same poll/select/epoll/kqueue operation.
I suppose I am just stupid (I tried all). Help me out of here: ``` #include <stdio.h> #include <string.h> int main() { const char * y = "747.0"; double x; x = atof(y); printf("%.5f\n",x); printf("%e\n",x); return 0; } ``` result: ``` 0.00000 0.000000e+00 ```
You need to includestdlib.hto offeratof()a prototype, without proper prototype, compiler will suppose its return value be anint.
This very simple example ofexec()system call. Here, I am trying to callexeclp()twice. But, I am not getting excepted output. It shows output only for first call with current directory. ``` #include <stdio.h> #include <unistd.h> int main() { int ret1,ret2; ret1 = execlp( "pwd", "pwd", (char *) 0); ...
execlp()replacesthe current process image with a new process image. It doesnot return(unless there was an error starting the new process). Therefore the secondexeclp()call is never reached.
As we known, we can usepoll/selectwith Netmap:http://info.iet.unipi.it/~luigi/netmap/ Is it possible to useepolland whether it makes sense to use epoll with Netmap, or it has no advantages in speed?
netmap author here: we have changes to enable epoll() for linux (the equivalent kevent() on FreeBSD is already supported). The advantage only exists when you have to handle several file descriptors in the same poll/select/epoll/kqueue operation.
I suppose I am just stupid (I tried all). Help me out of here: ``` #include <stdio.h> #include <string.h> int main() { const char * y = "747.0"; double x; x = atof(y); printf("%.5f\n",x); printf("%e\n",x); return 0; } ``` result: ``` 0.00000 0.000000e+00 ```
You need to includestdlib.hto offeratof()a prototype, without proper prototype, compiler will suppose its return value be anint.
I want to know if file is exists with C. I saw that I can do it by this function: ``` int file_exist (char *filename) { struct stat buffer; return (stat (filename, &buffer) == 0); } ``` But stat can failed also if the file exists, but there were some other errors (and then I would get negative number). How...
At least in UNIX systems there is a var called errno that gets the exact error you got. Check it against EFAULT. (more details onman 2 statandman errno). Checking is something like this: ``` if (stat(path) == -1) if (errno == EFAULT) //file does not exist else //some other error occurred ```
I have a variable word that points to a characters. However whenever I try to increment &c, I get a bizarre value for c: ``` char *word = "testing"; char c = *word; // 't' c = *(&c + 1); // want to be 'e' ``` Am I doing something wrong?
The line ``` char c = *word; // 't' ``` allocates space in memory on the stack for a new char (c). It then sets this char to be't', because that is what is at*word. The address of c (&c) is not going to be the same asword. To do what you're trying to do: ``` char c; //allocate space for a char char...
Although acharis composed of1 byteon all compilers I know, I was under the impression thatCdoesn't guarantee the length of achar, it only guarantees thatchar < short < long. Therefore I assumed thatsizeofmeasures its result inchars in order to abstract from the platform it's running on. To make it more general, I thou...
The unit used bysizeofis thechar. One of the axioms of the language is thatsizeof(char) == 1. Hence, for systems wherecharis larger than 8 bits,sizeofdoes not measure in 8 bit units.
I am a beginner in c ++ . I am trying to implement a small c ++ code for fun . The program reads its input from a text file which contains names of all my friends. The aim of the program is to return / print all the names beginning with a specified letter / nick name For example ``` Nick Joseph Jack Robert Paul...
Thslogicgoes like this: ``` read the desired prefix from user repeat read one line from file if the line starts with the desired prefix print it until there are no more lines ```
I'm getting the error expression "expected expression before char" ``` char *set_buffer(char *buf, int num_str, ...) { va_list args; va_start(args, num_str); for (int i = 0, offset = 0; i < num_str; ++i) { char *str = va_args(args, char *); // error here offset += snprintf(buf+offset, ...
The macro isva_argnotva_args ``` char *str = va_arg(args, char *) ```
I want to know if there is any alternate C library for the unix command groups, $ groups ---- lists all the group id's of the user. There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.
``` #include "<grp.h>" int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups); ```
Is there a way to list all the installed libraries and/or query if a specific library is installed with gcc? I want to know if glut is available on my system (without browsing all the library path). I am using mingw w/ gcc 4.5.2 under windows.
The way to check will generally be platform and compiler dependent. Getting it 100% right is hard. You can use a build system likeCMakefor generating your actual build system (confused yet;-)?) I founda small tutorialwhich explains how to find glut for you. Essentially, all you need is ``` find_package(GLUT) ``` i...
I have these codes ``` #include<stdio.h> void main() { int a; scanf("%d",&a); printf("%d",(int)a); } ``` My question is,when i type a as an input,i get 45 as ASCII equivalent and now i decided to change these codes to: ``` #include<stdio.h> void main() { int a; scanf("%c",&a); printf("%d",...
When you enter achartoint a; scanf("%d",&a);, it skips taking the input. Thecharstays in the input buffer and the previous value ofais retained. So in your case,45is the initial garbage value ofa. However, when you input as a character as inint a; scanf("%c",&a);, the character is taken from the input buffer, and its...
Usually auint64_tor auint32_t/uint16_tetc can be retrieve from achar* bufas follows: ``` uint32_t val = *(uint32_t*) buf; ``` But now supposebufischar [6], how would one retrieve a numerical value from it? *Unsigned big endian (network byte order)
A portable and standard-conforming way (in contrast to pointer casting or memcpy) would be to make it explicit: ``` uint64_t val = 0; for (int i = 0; i < 6; ++i) val |= (uint64_t)(unsigned char)buf[i] << (8*(6-i-1)); ``` This assumes big-endianess (network byte order). The extra cast tounsigned charis a hack tha...
Can you please tell me what is wrong with the following code ? For some reason the compiler refuses to recognize the O_DIRECT flag. ``` #define _GNU_SOURCE #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { int fd; fd = open(...
Don't worry about it. It's just the indexing parser which decides the text editor syntax highlighting and (ideally) links identifiers to definitions. You can resolve the problem by dumping the predefined macros from the compiler and feeding them into the indexing configuration control panel. Also double check that it...
I have a variable word that points to a characters. However whenever I try to increment &c, I get a bizarre value for c: ``` char *word = "testing"; char c = *word; // 't' c = *(&c + 1); // want to be 'e' ``` Am I doing something wrong?
The line ``` char c = *word; // 't' ``` allocates space in memory on the stack for a new char (c). It then sets this char to be't', because that is what is at*word. The address of c (&c) is not going to be the same asword. To do what you're trying to do: ``` char c; //allocate space for a char char...
Although acharis composed of1 byteon all compilers I know, I was under the impression thatCdoesn't guarantee the length of achar, it only guarantees thatchar < short < long. Therefore I assumed thatsizeofmeasures its result inchars in order to abstract from the platform it's running on. To make it more general, I thou...
The unit used bysizeofis thechar. One of the axioms of the language is thatsizeof(char) == 1. Hence, for systems wherecharis larger than 8 bits,sizeofdoes not measure in 8 bit units.
I am a beginner in c ++ . I am trying to implement a small c ++ code for fun . The program reads its input from a text file which contains names of all my friends. The aim of the program is to return / print all the names beginning with a specified letter / nick name For example ``` Nick Joseph Jack Robert Paul...
Thslogicgoes like this: ``` read the desired prefix from user repeat read one line from file if the line starts with the desired prefix print it until there are no more lines ```
I'm getting the error expression "expected expression before char" ``` char *set_buffer(char *buf, int num_str, ...) { va_list args; va_start(args, num_str); for (int i = 0, offset = 0; i < num_str; ++i) { char *str = va_args(args, char *); // error here offset += snprintf(buf+offset, ...
The macro isva_argnotva_args ``` char *str = va_arg(args, char *) ```
I want to know if there is any alternate C library for the unix command groups, $ groups ---- lists all the group id's of the user. There is a method called getgroups() but it returns the groups of the user this method. Is there a way to get groups for a particular user using C.
``` #include "<grp.h>" int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups); ```