question
stringlengths
25
894
answer
stringlengths
4
863
Below is an example of two dimensional array. ``` int s[5][2] = { {0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9} }; int (*p)[2]; ``` If I writep = &s[0];there is no error. But if I writep = s[0];there is an error, even though&s[0]ands[0]will give the same ...
The addresses are the same, but the types are different. &s[0]is of typeint (*)[2], buts[0]is of typeint [2], decaying toint *. The result is that when performing arithmetic onp, the pattern with which it walks over the array will depend on its type. If you writep = &s[0]and then accessp[3][1], you are accessings[3...
I'm usingSQLDriverConnectfunction to connect to database. In connection string I can specify ODBC pre-configured data source name (DSN), function resolves necessary attributes and all works fine. But after successful connection I need to get instance name to which I have connected or connection port (because there can...
Run the following query on your connection: ``` select @@SERVERNAME ``` This will return the server and instance name The preferred form is apparently to useSERVERPROPERY: ``` SELECT SERVERPROPERTY('ServerName') ``` which will return the server and instance name, and, unlike@@SERVERNAME, correctly returns results...
I get this error: ``` str.c:5:19: error: expected identifier or '(' before 'struct' ``` when compiling the following code. What is wrong with it? ``` #include <stdio.h> struct addpoints (struct point p1, struct point p2){ p1.x += p2.x; p1.y += p2.y; return p1; } int main(){ struct point{ i...
It looks like you wantaddpointsto return astruct point, but you forgot to put inpointafterstruct: ``` struct point addpoints (struct point p1, // ... ``` However, this will still not work unless you pull your definition ofstruct pointout ofmain: ``` #include <stdio.h> struct point{ int x; int y; }; struct...
This question already has an answer here:Closed10 years ago. Why we use a char array to create a buffer in the memory instead of a int array and if int array can be used to create the buffer,how to get the output from it ? ``` int main() { char buffer[100]; fread(buffer,sizeof(int),4,stdin); int i=0; ...
Very simply: we use a char array if we want to read bytes. Either text strings, or (more generally), binary objects. A "byte" is usually 1/4 the size of an "int". Moreover, socket "read" and "write" counts are byte counts. By longstanding convention, they expect byte buffers. 'Hope that helps!
Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function? The code below is not valid in ANSI C (C89, C90): ``` int main() { printf("Hello world!"); int a = 5; /* Error: all variables should be declared at the beginning of the function. */ return 0; } ``` Is it...
Yes. This was already valid in C99 (see the second bullethere).
Does the C11 standard (note I don't mean C++11) allow you to declare variables at any place in a function? The code below is not valid in ANSI C (C89, C90): ``` int main() { printf("Hello world!"); int a = 5; /* Error: all variables should be declared at the beginning of the function. */ return 0; } ``` Is it...
Yes. This was already valid in C99 (see the second bullethere).
How to create an array of strings when there isn't a fixed length of items or characters. I'm new to pointers and c in general and I couldn't understand the other solutions posted on here so my solution is posted below. Hopefully it helps someone else out.
``` char **twod_array = NULL; void allocate_2darray(char ***source, int number_of_slots, int length_of_each_slot) { int i = 0; source = malloc(sizeof(char *) * number_of_slots); if(source == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);} for(i = 0; i < no_of_slots; i++){ source[i] = malloc(siz...
I have a struct and I want to copy the elements in the outfname of orig to the outfname of dest. How can I do this? ``` typedef struct { char outfname[256]; } sudoku_t; void sudoku_copy(sudoku_t* orig,sudoku_t* dest){ } ``` Thanks.
``` void sudoku_copy(sudoku_t* orig, sudoku_t* dest) { *dest = *orig; } ``` just use the assignment operator. As a side-note I suggest you to usedestas the first parameter in your function to align with the C convention used by functions likememcpyandstrcpy.
I got some weird output: ``` Read 0 bytes: P ?\? ``` from my code: ``` #include <stdio.h> #include <string.h> #include <unistd.h> char phrase[0] = "stuff this in your pipe and smoke it"; int main(int argc, char* argv[]) { int fd[2], bytesRead; char message[100]; int pid; pid = fork(); pipe(fd);...
pid = fork(); pipe(fd); This example works when child processes inherit descriptors from the parent. You'll want to callpipebefore youfork.
When I try to compile static, I am getting the following error: ``` gcc defrag.c -o abc.exe --static /usr/bin/ld: cannot find -lc collect2: error: ld returned 1 exit status ``` However, the same thing compiles fine without static: ``` gcc defrag.c -o abc.exe ``` Question: Why did the compilation failed when stat...
The error is occurring becuase "--static" says that all subsequent libraries in your link commandmustbe static ... but you only have adynamiclibc on your system. Recommended solution: gcc defrag.c -o abc -lc --static -lmystaticlib If you're just trying to create a static exe for the sake of having a static exe - I'...
I've come across this piece of code in my O.S book: ``` void *foo() { // does something pthread_exit(NULL); } ``` What is the meaning ofvoid *foo? Does that mean the function return a pointer to something of typevoid?
No, it means that the function returns an pointer of theuntypedtype -void*. This is a "generic" pointer type. Any pointer to data can be cast tovoid*, and returned back to the caller. However, in order todereferencethe pointer, you must cast it to a non-void pointer type (int*,long*,char*, and so on).
Is there a way to have Yacc/Bison print out all the reductions it does to the input it processes? This would be a great debugging aid. I already tried ``` | Item1 { printf("Item1: %s\n", yytext); } ``` which only prints the last character and ``` | Item1 { printf("Item1: %s\n", $$); } ``` which results in aformat ...
I was able to enable debug output by Putting#define YYDEBUG 1in my C declarationsPuttingint yydebug = 1;in the additional C code section For additional reading, checkUsing YYDEBUG to generate debugging information,Debugging Your Parserandthis yacc example.
This question already has answers here:Closed10 years ago. Possible Duplicate:What is the point of function pointers? I saw this code ``` void (*foo)(int); ``` And I understood that is pointer to function. Why should I point to another function what does it give me?
You can use it to store a handler function that can be changed according the program flow, like the comparison function supplied toqsort. ``` void (*my_handler)(int); void set_handler(void(*fn)(int)) { my_handler = fn; } void do_stuff() { // ... my_handler(x); // using a custom handler } if (something)...
I have so much C code. I need to edit that code to follow some coding line tips. So I need to limit all my C code to a maximum of 80 characters per line. Instead of editing each line of code, how can I perform this transformation with a tool/IDE/script?
One such tool I know of isindenton Linux. It can be used to format your code in any style. Example from the man page: The Linux style is used in the linux kernel code and drivers:indent test/metabolism.c -linux Another switch, more specific to your questions: -ln, --line-lengthnSet maximum line length for non-comm...
I know what is the purpose of using static variables in an object oriented language, still, I don't understand what is the meaning of using the "static" keyword in C. Can someone explain it to me?
On a function or global variable,staticmakes the function or global variable local to that file; other files cannot access that function or global variable by that name (but they can access it if you give a pointer to it away). On a local variable, it makes it act as if it was a global variable, but is only accessibl...
I need to write a process in C that takes a user's name via keyboard. When he presses enter, the process goes to sleep. I then need a second process to wake up upon receiving the message, saves the user's name in a file, then goes to sleep and sends a signal to the 1st program that it's done, which in turn wakes up th...
Interprocesscommunication can be done withPipes. For windows seeInterprocess Communicationsand/orNamed Pipes. For Linux I'd suggest to readInter process communication using named pipes(FIFO) in linux.
This question already has answers here:Closed10 years ago. Possible Duplicate:How to add a default include path for gcc in linux? I was wondering is it possible to compile together files from different locations if they are included in the code itself? Lets say the header file is in another location but there is #i...
You can put ``` #include "adress" ``` adress would be like C:/Users/Files.../header.h
I'm finishing up some CSE homework and I have a quick question about declaring integers of larger bit sizes. My task is to implement a function that returns 1 if any odd bit of x is 1 (assuming size of x is 32 bits) and returns 0 otherwise. Am I allowed to declare an integer with the bit value: 101010101010101010101...
You can't use binary literals in C. Instead, use hexadecimal or octal notation. In your case, you'd useunsigned mask = 0xaaaaaaaasince10101010...is0xaaaaaaaawhen expressed in hexadecimal (each1010isain hex).
I have a configuration file that is supposed to have \r\n line ending style, and I want to include the code in my program to check and correct the format. Existing code: ``` int convert_line_endings(FILE *fp) { char c = 0, lastc = 0, cnt = 0; while((c = fgetc(fp)) != EOF) { if((c == '\n') && (last...
No, you can't delete or insert. What you can do is write to a new temporary file by copying everything except\r\nsequences and then overwrite the original file with it.
I want to copy the a file name to a string and append ".cpt" to it. But I am unable to do this with safe functions (strcat_s). Error: "String is not null terminated!". And I did set '\0', how to fix this using safe functions? ``` size = strlen(locatie); size++; nieuw = (char*)malloc(size+4); strcpy_s(nieuw, size, loc...
Thesizeparameter of the _s functions is the size of the destination buffer, not the source. The error is because there is no null terminator innieuwin the first for characters. Try this: ``` size = strlen(locatie); size++; int nieuwSize = size + 4; nieuw = (char*)malloc(nieuwSize ); strcpy_s(nieuw, nieuwSize, locat...
here is my snippet of code: ``` float square_root(x) float x; { ....... } int main(){ printf("Square_root 2 = %f\n", square_root(4)); } ``` When I pass number 4.0 to thesquare_root()function,xparameter inside the function is 4.0000000 so its ok. But when I pass just 4 (like in example),xvariable inside the fun...
You're using the old style of function declaration, where the argument types are listed separately. SeeC function syntax, parameter types declared after parameter list As you are passing anint, it's not being converted tofloatby default. Your function, though, isinterpretingthe argument as afloat, which gives undesir...
I have to profile my multithreaded C++ app and find its bottlenecks. The problem is: I need to see wall clock profile. I have usedoprofileandperf. No one can provide me such information. I have usedperf record -g -e sched:sched_stat_sleep <cmd>butperf recordfalls with SIGFPE exception. This makes me angry. Valgrindd...
Try PAPIhttp://web.eecs.utk.edu/~terpstra/using_papi/, it is an open source profiler. I normally use this profiler to measure the cache performance (e.g, misses and accesses) in some algorithms. Maybe it can be useful also for what you want. If you have MAC, have a look on the profiler "instruments"
I have a function(in some library) whose signature is this: ``` extern LIB3DSAPI void lib3ds_mesh_calculate_face_normals(Lib3dsMesh *mesh, float (*face_normals)[3]); ``` what does it expect in second argument? I tried this: ``` float *norm_verts[3]; norm_verts=(float(*)[3])malloc(3*sizeof(float[3])*mesh-...
``` float (*face_normals)[3] // face_normals is a pointer (to an array of 3 floats) float *norm_verts[3]; // norm_verts is an array of 3 pointers (to float) ``` Pointers are not arrays, arrays are not pointers. I suggest you readcomp.lang.c FAQ, starting with section 6.
Getting raw sockets requires root privilege, and tcp/udp doesn't have it, so I need to know how to get a udp socket and fetch icmp data. The programming language is C and the OS is BSD-like. (In other words I want to write a ping without root privilege)
You can write an UDP ping without root privileges. When theIP_RECVERRoption is enabled, all errors are stored in the socket error queue, and can be received byrecvmsg(2) with theMSG_ERRQUEUEflag set. See the UDP manual. I assume the forge&send routine is already implemented on a SOCK_DGRAM socket. Then, to access...
I'm looking into socket programming in C and I'm curious why do you have to pass a parameteranda length of that parameter in functions likebind()andconnect()? Why not just usesizeof()inside of the function?
Because it gives a simple simple way to handle many different types of protocols with the same API. Since a socket can use many different underlying protocols (as pointed out by @larsman), the call can't know which type of structure it's being handed, exactly. There's some basic "inheritance" going on with the variou...
I am using strtok to extract 2 words from a string names[result]. I want to get the first value from the strtok and stored it into a char array named lastName and the second value into a char array named firstName. However I got an invalid initializer error for 2 lines which are indicated by the arrow when I compiled ...
strtok gives the pointer to the tokenized string. char lastName[50] = p;Isn't really a good thing that you are doing there. Should use strncpy() to copy the string, or if only want the pointer, then should store in another pointer.
I had a doubly linked list capable of holding characters in each node. This is what I do to input characters to each node. ``` printf("Enter string of characters for the list: "); scanf("%s",s); for(i=0;s[i]!='\0';i++) Insert(s[i],&Header1); ``` Now i wish to modify the list to store words in each node.The input...
``` while ( sscanf( sentence, "%s", &node_value ) == 1 ) { //Call to insert into your list goes here //Each pass node_value will be the next word } ``` NOTE: You will have to passnode_valueby value into your list, otherwise all your values will be the same reference!
I need your help in understanding the memset behaviour. ``` char *data = malloc(40); memset(data,1,40); ``` When I saw the data content it was 010101010101010 till the end of the size.Then i changed to this. ``` memset(data,~0,40); ``` I saw the correct content as 11111111 till end . What is the difference between...
memsetfillseach byteof the provided memory region with the value you specify. Please note that only the least significant byte of the last argument is taken to populate the memory block (even though its type isint). In your first case this byte is 0x01, while int the second case it's 0xFF (all ones). That's why you a...
Can I useSELECT COUNT(*) from tableNamein a C program? If so, how do I fetch the results? I don't want to use a loop because I only want the number of rows, not the data.
When you execute the querySELECT COUNT(*) from tableName, the result is a table like with other queries, but that result table has only one column and only one row, which contains the count value. Callsqlite3_prepare_v2normally, thensqlite3_step, which steps to the first (and only) row. Callsqlite3_column_intto get t...
I have taken one gpio of my omap4 based custom board as input gpio. When I connect any external h/w on any port then input gpio gets pull down and I get interrupt on that gpio. Now when I run Linux kernel 2.6 its working fine and gets interrupt on that gpio but when I use Linux kernel 3.0, its not creating interrupt ...
As mentioned in the comments, the issue was resolved by correctly specifying the pull-up on the pin. One more thing to consider usually is the "pin-mux" i.e. one would need to verify that the pin in question is configured as a GPIO and not some other functionality. A detailed description of the pin configuration,spe...
I'm not new to C but I just found out a problem which I have to deal with. How do I access the member of a struct that is a pointer to another struct? ex. ``` typdef struct { int points; } tribute; typedef struct { int year; tribute *victor; } game; int main(){ tribute myVictor; myVictor.points = 10...
Try: ``` myGame.victor = &myVictor; ```
I'm studying some basic functions for my C midterm and I realized I copied down my instructor's example incorrectly. I'm probably just too tired to think this through right now and a little push would be greatly appreciated. ``` void replace_last(char s[], int oldc, int newc){ size_t i, pos-1; /* I have no idea w...
Line number : 5pos==ishould be replaced withpos=i
here is my snippet of code: ``` float square_root(x) float x; { ....... } int main(){ printf("Square_root 2 = %f\n", square_root(4)); } ``` When I pass number 4.0 to thesquare_root()function,xparameter inside the function is 4.0000000 so its ok. But when I pass just 4 (like in example),xvariable inside the fun...
You're using the old style of function declaration, where the argument types are listed separately. SeeC function syntax, parameter types declared after parameter list As you are passing anint, it's not being converted tofloatby default. Your function, though, isinterpretingthe argument as afloat, which gives undesir...
I have to profile my multithreaded C++ app and find its bottlenecks. The problem is: I need to see wall clock profile. I have usedoprofileandperf. No one can provide me such information. I have usedperf record -g -e sched:sched_stat_sleep <cmd>butperf recordfalls with SIGFPE exception. This makes me angry. Valgrindd...
Try PAPIhttp://web.eecs.utk.edu/~terpstra/using_papi/, it is an open source profiler. I normally use this profiler to measure the cache performance (e.g, misses and accesses) in some algorithms. Maybe it can be useful also for what you want. If you have MAC, have a look on the profiler "instruments"
I have a function(in some library) whose signature is this: ``` extern LIB3DSAPI void lib3ds_mesh_calculate_face_normals(Lib3dsMesh *mesh, float (*face_normals)[3]); ``` what does it expect in second argument? I tried this: ``` float *norm_verts[3]; norm_verts=(float(*)[3])malloc(3*sizeof(float[3])*mesh-...
``` float (*face_normals)[3] // face_normals is a pointer (to an array of 3 floats) float *norm_verts[3]; // norm_verts is an array of 3 pointers (to float) ``` Pointers are not arrays, arrays are not pointers. I suggest you readcomp.lang.c FAQ, starting with section 6.
Getting raw sockets requires root privilege, and tcp/udp doesn't have it, so I need to know how to get a udp socket and fetch icmp data. The programming language is C and the OS is BSD-like. (In other words I want to write a ping without root privilege)
You can write an UDP ping without root privileges. When theIP_RECVERRoption is enabled, all errors are stored in the socket error queue, and can be received byrecvmsg(2) with theMSG_ERRQUEUEflag set. See the UDP manual. I assume the forge&send routine is already implemented on a SOCK_DGRAM socket. Then, to access...
I'm looking into socket programming in C and I'm curious why do you have to pass a parameteranda length of that parameter in functions likebind()andconnect()? Why not just usesizeof()inside of the function?
Because it gives a simple simple way to handle many different types of protocols with the same API. Since a socket can use many different underlying protocols (as pointed out by @larsman), the call can't know which type of structure it's being handed, exactly. There's some basic "inheritance" going on with the variou...
I am using strtok to extract 2 words from a string names[result]. I want to get the first value from the strtok and stored it into a char array named lastName and the second value into a char array named firstName. However I got an invalid initializer error for 2 lines which are indicated by the arrow when I compiled ...
strtok gives the pointer to the tokenized string. char lastName[50] = p;Isn't really a good thing that you are doing there. Should use strncpy() to copy the string, or if only want the pointer, then should store in another pointer.
I had a doubly linked list capable of holding characters in each node. This is what I do to input characters to each node. ``` printf("Enter string of characters for the list: "); scanf("%s",s); for(i=0;s[i]!='\0';i++) Insert(s[i],&Header1); ``` Now i wish to modify the list to store words in each node.The input...
``` while ( sscanf( sentence, "%s", &node_value ) == 1 ) { //Call to insert into your list goes here //Each pass node_value will be the next word } ``` NOTE: You will have to passnode_valueby value into your list, otherwise all your values will be the same reference!
I need your help in understanding the memset behaviour. ``` char *data = malloc(40); memset(data,1,40); ``` When I saw the data content it was 010101010101010 till the end of the size.Then i changed to this. ``` memset(data,~0,40); ``` I saw the correct content as 11111111 till end . What is the difference between...
memsetfillseach byteof the provided memory region with the value you specify. Please note that only the least significant byte of the last argument is taken to populate the memory block (even though its type isint). In your first case this byte is 0x01, while int the second case it's 0xFF (all ones). That's why you a...
Can I useSELECT COUNT(*) from tableNamein a C program? If so, how do I fetch the results? I don't want to use a loop because I only want the number of rows, not the data.
When you execute the querySELECT COUNT(*) from tableName, the result is a table like with other queries, but that result table has only one column and only one row, which contains the count value. Callsqlite3_prepare_v2normally, thensqlite3_step, which steps to the first (and only) row. Callsqlite3_column_intto get t...
I have taken one gpio of my omap4 based custom board as input gpio. When I connect any external h/w on any port then input gpio gets pull down and I get interrupt on that gpio. Now when I run Linux kernel 2.6 its working fine and gets interrupt on that gpio but when I use Linux kernel 3.0, its not creating interrupt ...
As mentioned in the comments, the issue was resolved by correctly specifying the pull-up on the pin. One more thing to consider usually is the "pin-mux" i.e. one would need to verify that the pin in question is configured as a GPIO and not some other functionality. A detailed description of the pin configuration,spe...
I'm not new to C but I just found out a problem which I have to deal with. How do I access the member of a struct that is a pointer to another struct? ex. ``` typdef struct { int points; } tribute; typedef struct { int year; tribute *victor; } game; int main(){ tribute myVictor; myVictor.points = 10...
Try: ``` myGame.victor = &myVictor; ```
I am having a two c program filetemp1.candtemp2.c. I compiled and generateddot ofiles for thistemp1.oandtemp2.o. After that I genratedfinal.oandfinal.aby combining these twodot ofiles. Now these two static libraries are working fine. Now nm report offinal.ais displaying all file names and symbols. But nm report offin...
If we create.afile from.ofiles(temp1.oandtemp2.o) then the.awill have the file name of all.ofiles and its content. But while creating.ofrom some.ofiles, then it will contain only content of all.ofiles and the file names of each.owill not be present.
I'm writing by hand an application that useGtk+. I'm using aGtkGridto hold myGtkWidgets, but I can't put aGtkWidgetinto specific colum, as the second parameter ofgtk_grid_attach()function says. E.g, the last element was placed into the 4-column, if I try to put into the 6-column it does not works; theGtkWidgetis auto ...
You can't just "skip" a column, this has no meaning. An empty column is just 0 pixels wide. You need to put something there, either in the same row, or in another, if you want it to have a width > 0. You can just put a GtkFixed widget there if you want, but if this is just to separate 2 widgets, you may want to use th...
I'm looking into visualizing a large amount of C code, preferably having its state machine reverse engineered and graphed out for me diagrammatically. I've looked into Graphviz and Dot, and it appears that I could probably stitch something together from the API to do the job. But honestly I kind of expected that it ...
You can try the Enterprise Architect but that's really not a good idea and in any case you'll need to do a lot of manual changes to the result. It's more or less like relying on an automatic translator to speak for you in the language you don't know. It's especially problematic for procedural type of code, like you pr...
I have a__m128iregister with 8 bit values with the content: ``` {-4,10,10,10,10,10,10,-4,-4,10,10,10,10,10,10,-4} ``` Now I want to convert it to eight 16 bit values in a_m128iregister. It should look like: ``` {-4,10,10,10,10,10,10,-4} ``` How is this possible with the least amount of instructions as possible? I...
Assuming you just want the first 8 values out of the 16 and are going to ignore the other 8 (the example data you give is somewhat ambiguous) then you can do it with SSE2 like this: ``` v = _mm_srai_epi16(_mm_unpacklo_epi8(v, v), 8); ```
I want to declare character array and later want to fill it. But getting error: ``` char line[BUFSIZE+1]; strcpy(line,"Memory is Full", sizeof(line)); ``` Error is: ``` wrong number of arguments in call to strcpy. ``` Is there any alternative to achive this?
If you have it, usestrlcpy(). It does what you might expectstrncpy()to do. Failing that, I would recommend usingsnprintf(), if you have it.
I have a question to ask, which occurred when reading the concept of static variables. If I create an allocated block of memory in a function, usingmalloc, and then the function returns tomain, without having usedfree()on the allocated memory, will that memory block be susceptible to changes in the course of the progr...
Once youmalloced a certain num ber of bytes, it's going to be alive throughout your program's lifetime unless you explicitlyfreeit. It doesn't matter in which function you did themalloc, the memory is going to be alive for you to use anywhere in your program provided you have a valid pointer to themalloced memory.
How can I inspect end of file in next code. I try to write function that can read wchar_t symbols one by one while some define earlier symbol be read, but if EOF be read function must stop. ``` wchar_t wchr[1]; BOOL b = TRUE; do { b = ReadFile(hReadFile, wchr, sizeof(wchar_t), &dw, NULL); if(!b)break; ...
The way to check ifReadFileis at the end of the file is to check how many bytes it has read vs how many you requested. That is: ``` if(!b)break; ``` should read: ``` if(dw != sizeof(wchar_t)) break; ```
For a second I was hoping to get away withsed'sa\command, butsed(in my hands, anyway) isn't really a fan of keeping state (inserts after every #include). So is there a way to do this withsed? Is there asmartway of doing this? I'll resort to writing a regular Python/Ruby script if that's the way to go, but this seems...
Before applying your sed you can reverse the file line by line with the command tac and then let sed do aninsertinstead of append. And of course make sure that sed only does this insert once. Like this: ``` tac file | sed '1,/#include/ {/#include/i\ #include whatever }' | tac ``` That should do the trick.
Is this possible to figure out thread's scheduling policy from linux console? I mean is it possible to receive something whatpthread_getschedparam()returns but from console? I need to figure out whatever policy isSCHED_FIFO, SCHED_RR or SCHED_OTHER.
The commandps -eLfcwill give you a list of threads running along with their scheduling policy under the row titledCLS. RR (Round Robin), TS (Time Sharing) are some of the scheduling policies that may be present. If you want to start a process and mention a particular scheduling policy for its threads then you can use ...
I am having a two c program filetemp1.candtemp2.c. I compiled and generateddot ofiles for thistemp1.oandtemp2.o. After that I genratedfinal.oandfinal.aby combining these twodot ofiles. Now these two static libraries are working fine. Now nm report offinal.ais displaying all file names and symbols. But nm report offin...
If we create.afile from.ofiles(temp1.oandtemp2.o) then the.awill have the file name of all.ofiles and its content. But while creating.ofrom some.ofiles, then it will contain only content of all.ofiles and the file names of each.owill not be present.
I'm writing by hand an application that useGtk+. I'm using aGtkGridto hold myGtkWidgets, but I can't put aGtkWidgetinto specific colum, as the second parameter ofgtk_grid_attach()function says. E.g, the last element was placed into the 4-column, if I try to put into the 6-column it does not works; theGtkWidgetis auto ...
You can't just "skip" a column, this has no meaning. An empty column is just 0 pixels wide. You need to put something there, either in the same row, or in another, if you want it to have a width > 0. You can just put a GtkFixed widget there if you want, but if this is just to separate 2 widgets, you may want to use th...
I'm looking into visualizing a large amount of C code, preferably having its state machine reverse engineered and graphed out for me diagrammatically. I've looked into Graphviz and Dot, and it appears that I could probably stitch something together from the API to do the job. But honestly I kind of expected that it ...
You can try the Enterprise Architect but that's really not a good idea and in any case you'll need to do a lot of manual changes to the result. It's more or less like relying on an automatic translator to speak for you in the language you don't know. It's especially problematic for procedural type of code, like you pr...
I have a__m128iregister with 8 bit values with the content: ``` {-4,10,10,10,10,10,10,-4,-4,10,10,10,10,10,10,-4} ``` Now I want to convert it to eight 16 bit values in a_m128iregister. It should look like: ``` {-4,10,10,10,10,10,10,-4} ``` How is this possible with the least amount of instructions as possible? I...
Assuming you just want the first 8 values out of the 16 and are going to ignore the other 8 (the example data you give is somewhat ambiguous) then you can do it with SSE2 like this: ``` v = _mm_srai_epi16(_mm_unpacklo_epi8(v, v), 8); ```
I want to declare character array and later want to fill it. But getting error: ``` char line[BUFSIZE+1]; strcpy(line,"Memory is Full", sizeof(line)); ``` Error is: ``` wrong number of arguments in call to strcpy. ``` Is there any alternative to achive this?
If you have it, usestrlcpy(). It does what you might expectstrncpy()to do. Failing that, I would recommend usingsnprintf(), if you have it.
I have a question to ask, which occurred when reading the concept of static variables. If I create an allocated block of memory in a function, usingmalloc, and then the function returns tomain, without having usedfree()on the allocated memory, will that memory block be susceptible to changes in the course of the progr...
Once youmalloced a certain num ber of bytes, it's going to be alive throughout your program's lifetime unless you explicitlyfreeit. It doesn't matter in which function you did themalloc, the memory is going to be alive for you to use anywhere in your program provided you have a valid pointer to themalloced memory.
How can I inspect end of file in next code. I try to write function that can read wchar_t symbols one by one while some define earlier symbol be read, but if EOF be read function must stop. ``` wchar_t wchr[1]; BOOL b = TRUE; do { b = ReadFile(hReadFile, wchr, sizeof(wchar_t), &dw, NULL); if(!b)break; ...
The way to check ifReadFileis at the end of the file is to check how many bytes it has read vs how many you requested. That is: ``` if(!b)break; ``` should read: ``` if(dw != sizeof(wchar_t)) break; ```
For a second I was hoping to get away withsed'sa\command, butsed(in my hands, anyway) isn't really a fan of keeping state (inserts after every #include). So is there a way to do this withsed? Is there asmartway of doing this? I'll resort to writing a regular Python/Ruby script if that's the way to go, but this seems...
Before applying your sed you can reverse the file line by line with the command tac and then let sed do aninsertinstead of append. And of course make sure that sed only does this insert once. Like this: ``` tac file | sed '1,/#include/ {/#include/i\ #include whatever }' | tac ``` That should do the trick.
``` int myatoi(const char* string) { int i; i = 0; while(*string) { i = (i << 3) + (i<<1) + (*string -'0'); string++; } return i; } int main() { int i = myatoi("10101"); printf("%d\n",i); char a = (char)(((int)'0')+i); printf("%c\n",a); return 0; } ``` my output turns out to be 10101 � how to fix this ...
What do you expect to have happen? Your code correctly converts the string"10101"into the integer10101, and prints it. That looks fine. You then compute10101+(int)'0'which is probably 10149 (in ascii or unicode,(int)'0'is 48). Converting that to acharprobably gives you 165 (or perhaps -91) which probably doesn't c...
This question already has answers here:Closed10 years ago. Possible Duplicate:pow() isn’t defined ``` void octal2decimal(char *octal, char *decimal) { int oct = atoi(octal); int dec = 0; int p = 0; while (oct!=0) { dec = dec + (oct%10) * pow(8,p++); //since oct is base 8 oct/=10; } *decimal = (char)dec; *...
Math library is not part of the standard C library which is included by default. Link with the math library: ``` gcc file.c -o file -lm ```
What is the format specifier for an _int8 data type? I am using "%hd" but it is giving me an error about stack corruption. Thanks :) This is a snippet of the code: ``` signed _int8 answer; printf("----Technology Quiz----\n\n"); printf("The IPad came out in which year?\n"); printf("Year: "); scanf("%hd", &answer); ...
man scanf:%hhd"... but the next pointer is a pointer to a signed char or unsigned char". An_int8is equivalent to asigned charin any system you're going to be doingscanfon. ``` signed _int8 answer; scanf("%hhd", &answer); printf("You entered %d\n\n", answer); ```
vxTypes.h ``` #if !defined(__RTP__) #ifdef _TYPE_fpos_t #define _FPOS_T _TYPE_fpos_t; #undef _TYPE_fpos_t #endif #endif /* __RTP__ */ ``` UPDATE 00: stdio.h ``` typedef struct fpos_t { /* file position */ long _Off; /* can be system dependent */ _Mbstatet _Wstate; } fpos_t ``` and i have a comp...
I had the same problem. Assuming you're using the gcc toolset, use "-nostdinc" compiler option to prevent GCC from using the default search path. (The diab toolset should have a similar option.) Your project makefile should already contain a list of "-Idir" entries that should make system headers visible to the compil...
I try to output the list of characters with C:http://www.alt-codes.net/ ``` for (i=0; i<len; i++){ printf("%d\t: %c", i, i); } ``` The problem that for all non-ASCII chars I got ? working on Ubuntu. How can I output them in nice manner.
The formatting will be poor, but apart from that the code you posted works. ASCII characters 0-31 are various space characters and there is no standardized way to print them. The link you posted is a common, yet non-standard "extended ASCII table". There is no guarantee that those exact symbols will be printed on you...
This is my code: ``` char str[] =""; scanf("%s",&str); char * pch; pch = strtok (str,"#"); printf ("%s\n",pch); return 0; ``` I need to render an input of "1#2#3" to three integers first, second and third. My code above tackles only the first variable and prints the first string "1" but i want to save it to an int v...
If you know the precise layout of the input, and the exact number ofints, you can simplify this greatly: ``` scanf("%d#%d#%d", &a, &b, &c); ``` Here is alink to a demo on ideone.
Why does the heap get corrupted when executing this code? I didn't work with memory allocation that much, yet. ``` #include <stdlib.h> void main() { char **field, x, _fieldsX, _fieldsY; _fieldsX = 8; _fieldsY = 16; // Allocation field = malloc(sizeof(char*) * _fieldsX); for (x = 0; x < _fie...
You get out of the bounds of the allocated area in the first loop: ``` field = malloc(sizeof(char*) * _fieldsX); for (x = 0; x < _fieldsY; x++) field[x] = malloc(sizeof(char) * _fieldsY); ``` Notice that you are allocating_fieldsXitems, but the loop goes_fieldsYtimes over that area.
I need to convert 24 bit RGB(888) image data to PNG or JPEG image (whichever possible). Need simpler approach to do this same like converting RGB888 to BMP without any compression. Would be great if it is something like adding PNG/JPEG headers to the RGB data with/without little modification. Ready to provide more det...
Useminiz- a.k.a single C source file Deflate/Inflate compression library with zlib-compatible API, ZIP archive reading/writing, PNG writing.
Is there any way (or a useful function) to know whether interrupts are disabled or not?
You can useirqs_disabled()function: ``` #include <linux/irqflags.h> int i = irqs_disabled(); ```
What will be the output ofprintf("%d");orprintf("%p");statement? Of course I know that I should pass argument as printf is expecting one but assuming that I will leave this empty what will happen? I know that this will print some value read from stack (from the place where function argument should be placed). Assumi...
This is simply undefined behaviour. Anything could happen. It's impossible to give a more accurate answer. The details depend on howprintfis implemented by the library, and how variable arguments are implemented by your compiler. Look at the source of the library and/or the generated assembly to find out what's happe...
I am currently working on some C code and I am trying to convert a human readable date into an epoch time stamp (unix timestamp). However, its always returning a negative number. I'm usingstruct tmand hard coding the values of the date until I get it working properly. Below is the code ``` struct tm t; time_t t_of_da...
2012 - 1970computes to 42. And year 1942 is before 1/1/1970. That is normal thatmktime()result into a negative timestamp though. from mktime man page: ``` tm_year The number of years since 1900. ``` change your year calculation to2012 - 1900and you should be fine.
``` int myatoi(const char* string) { int i; i = 0; while(*string) { i = (i << 3) + (i<<1) + (*string -'0'); string++; } return i; } int main() { int i = myatoi("10101"); printf("%d\n",i); char a = (char)(((int)'0')+i); printf("%c\n",a); return 0; } ``` my output turns out to be 10101 � how to fix this ...
What do you expect to have happen? Your code correctly converts the string"10101"into the integer10101, and prints it. That looks fine. You then compute10101+(int)'0'which is probably 10149 (in ascii or unicode,(int)'0'is 48). Converting that to acharprobably gives you 165 (or perhaps -91) which probably doesn't c...
This question already has answers here:Closed10 years ago. Possible Duplicate:pow() isn’t defined ``` void octal2decimal(char *octal, char *decimal) { int oct = atoi(octal); int dec = 0; int p = 0; while (oct!=0) { dec = dec + (oct%10) * pow(8,p++); //since oct is base 8 oct/=10; } *decimal = (char)dec; *...
Math library is not part of the standard C library which is included by default. Link with the math library: ``` gcc file.c -o file -lm ```
What is the format specifier for an _int8 data type? I am using "%hd" but it is giving me an error about stack corruption. Thanks :) This is a snippet of the code: ``` signed _int8 answer; printf("----Technology Quiz----\n\n"); printf("The IPad came out in which year?\n"); printf("Year: "); scanf("%hd", &answer); ...
man scanf:%hhd"... but the next pointer is a pointer to a signed char or unsigned char". An_int8is equivalent to asigned charin any system you're going to be doingscanfon. ``` signed _int8 answer; scanf("%hhd", &answer); printf("You entered %d\n\n", answer); ```
vxTypes.h ``` #if !defined(__RTP__) #ifdef _TYPE_fpos_t #define _FPOS_T _TYPE_fpos_t; #undef _TYPE_fpos_t #endif #endif /* __RTP__ */ ``` UPDATE 00: stdio.h ``` typedef struct fpos_t { /* file position */ long _Off; /* can be system dependent */ _Mbstatet _Wstate; } fpos_t ``` and i have a comp...
I had the same problem. Assuming you're using the gcc toolset, use "-nostdinc" compiler option to prevent GCC from using the default search path. (The diab toolset should have a similar option.) Your project makefile should already contain a list of "-Idir" entries that should make system headers visible to the compil...
I try to output the list of characters with C:http://www.alt-codes.net/ ``` for (i=0; i<len; i++){ printf("%d\t: %c", i, i); } ``` The problem that for all non-ASCII chars I got ? working on Ubuntu. How can I output them in nice manner.
The formatting will be poor, but apart from that the code you posted works. ASCII characters 0-31 are various space characters and there is no standardized way to print them. The link you posted is a common, yet non-standard "extended ASCII table". There is no guarantee that those exact symbols will be printed on you...
This is my code: ``` char str[] =""; scanf("%s",&str); char * pch; pch = strtok (str,"#"); printf ("%s\n",pch); return 0; ``` I need to render an input of "1#2#3" to three integers first, second and third. My code above tackles only the first variable and prints the first string "1" but i want to save it to an int v...
If you know the precise layout of the input, and the exact number ofints, you can simplify this greatly: ``` scanf("%d#%d#%d", &a, &b, &c); ``` Here is alink to a demo on ideone.
Why does the heap get corrupted when executing this code? I didn't work with memory allocation that much, yet. ``` #include <stdlib.h> void main() { char **field, x, _fieldsX, _fieldsY; _fieldsX = 8; _fieldsY = 16; // Allocation field = malloc(sizeof(char*) * _fieldsX); for (x = 0; x < _fie...
You get out of the bounds of the allocated area in the first loop: ``` field = malloc(sizeof(char*) * _fieldsX); for (x = 0; x < _fieldsY; x++) field[x] = malloc(sizeof(char) * _fieldsY); ``` Notice that you are allocating_fieldsXitems, but the loop goes_fieldsYtimes over that area.
I need to convert 24 bit RGB(888) image data to PNG or JPEG image (whichever possible). Need simpler approach to do this same like converting RGB888 to BMP without any compression. Would be great if it is something like adding PNG/JPEG headers to the RGB data with/without little modification. Ready to provide more det...
Useminiz- a.k.a single C source file Deflate/Inflate compression library with zlib-compatible API, ZIP archive reading/writing, PNG writing.
Is there any way (or a useful function) to know whether interrupts are disabled or not?
You can useirqs_disabled()function: ``` #include <linux/irqflags.h> int i = irqs_disabled(); ```
What will be the output ofprintf("%d");orprintf("%p");statement? Of course I know that I should pass argument as printf is expecting one but assuming that I will leave this empty what will happen? I know that this will print some value read from stack (from the place where function argument should be placed). Assumi...
This is simply undefined behaviour. Anything could happen. It's impossible to give a more accurate answer. The details depend on howprintfis implemented by the library, and how variable arguments are implemented by your compiler. Look at the source of the library and/or the generated assembly to find out what's happe...
I am currently working on some C code and I am trying to convert a human readable date into an epoch time stamp (unix timestamp). However, its always returning a negative number. I'm usingstruct tmand hard coding the values of the date until I get it working properly. Below is the code ``` struct tm t; time_t t_of_da...
2012 - 1970computes to 42. And year 1942 is before 1/1/1970. That is normal thatmktime()result into a negative timestamp though. from mktime man page: ``` tm_year The number of years since 1900. ``` change your year calculation to2012 - 1900and you should be fine.
The mkfifo function takes 2 arguments, path and mode. But I don't know what is the format of the path that it uses. I am writing a small program to create a named pipe and as path in themkfifo. Using/home/username/Documentsfor example, but it always returns -1 with the messageError creating the named pipe.: File e...
You gavemkfifo()the name of anexistingdirectory, thus the error. You must give it the name of a non-existing file, e.g. ``` mkfifo("/home/username/Documents/myfifo", 0600); ```
I know that in winapi existReadFile()function for reading data from file, but I don't know how can I set the position of reading from file. Can I do this using WinAPI?
Yes, you can do that withSetFilePointerEx. However, unless you have a good reason for using the raw WinAPI, it's generally a better idea to use a cross-platform I/O library, such as C's stdio library or C++'s iostream library. That way, your code is portable to any platform.
If I have auint64_t originaland two regular four byte ints, (which are signed), I would like to store the value in the two ints and recover the unsigned 64 byte later. This should be possible because we have 64 bits available in both cases. I was thinking something along the lines of: ``` uint64_t test = 135064080721...
Instead of doing a lot of error-prone bit-twiddling you could just use a union: ``` union { uint64_t u64; int32_t s32[2]; } u; u.u64 = 1350640807215539000ULL; printf("a = %d\n", u.s32[0]); printf("b = %d\n", u.s32[1]); ```
Is there any way to identify if a buffer was allocated by 'malloc'? like a function with the following signature: ``` bool is_malloced(void *buf); ``` Does such a mechanism exist in posix?
Nope. Neither C11 nor POSIX provide any such mechanism.
What I saw in an if statement was like this. ``` if((var = someFunc()) == 0){ ... } ``` Will the statement ``` (var = someFunc()) ``` always return the final value of var no matter what environment we are in?
That is just a one-line way of assigning to a variable and comparing the returned value at the same time. You need the parentheses around the assignment because the comparison operators have higher precedence than the assignment operator, otherwisevarwould be assigned the value ofsomeFunc() == 0.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. When we perform substitution, can o...
Substitution of one type for another is purely dependent on your requirement. You can alsotypedefthe given type or you can make your own type. You can perform type substitution usingtemplatealso Btw your question is little incomplete to give accurate answer , what exactly you want to ask?
I am trying to get all the physical drives available on local machine. I tried to useGetLogicalDrives()but when i'm using this function it gets me also drives that physically not available on the machine, for example floppy drive A. Here is my code: ``` void FindDrives() { DWORD drives = GetLogicalDrives(); ...
Try usingwmic ``` wmic diskdrive list ``` for less info ``` wmic diskdrive list brief ``` Alternatively in c use GetLogicalDrives() first to get all of the drives mapped in the system, and then GetDriveType() to find out which sort of drive each one is. Then sort it out as you want to.
I have the following code: ``` volatile unsigned int * address; char * array="0x10000008"; ``` Please tell me, what is a correct way of writing the "array" value to "address" variable?
You could usesscanf: ``` #include <stdio.h> sscanf(array, "%p", &address); ``` orstrtoull: ``` #include <stdlib.h> address = (unsigned int *)strtoull(array, NULL, 0); ```
I have made a basic client and server in C using BSD sockets. I am able to bind to a port number above 65535, and the client can connect to it. What am I doing wrong here? Code: ``` int port = 999999; ... serverAddr.sin_port = htons(port); ```
Because htons takes a 16 bit argument and its input will be truncated. Try this and see what you get: ``` #include <stdio.h> #include <arpa/inet.h> int main(int argc, char **argv) { int foo = 999999; int bar = ntohs(htons(foo)); printf("%d\n", bar); return 0; } ```
What I saw in an if statement was like this. ``` if((var = someFunc()) == 0){ ... } ``` Will the statement ``` (var = someFunc()) ``` always return the final value of var no matter what environment we are in?
That is just a one-line way of assigning to a variable and comparing the returned value at the same time. You need the parentheses around the assignment because the comparison operators have higher precedence than the assignment operator, otherwisevarwould be assigned the value ofsomeFunc() == 0.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. When we perform substitution, can o...
Substitution of one type for another is purely dependent on your requirement. You can alsotypedefthe given type or you can make your own type. You can perform type substitution usingtemplatealso Btw your question is little incomplete to give accurate answer , what exactly you want to ask?
I am trying to get all the physical drives available on local machine. I tried to useGetLogicalDrives()but when i'm using this function it gets me also drives that physically not available on the machine, for example floppy drive A. Here is my code: ``` void FindDrives() { DWORD drives = GetLogicalDrives(); ...
Try usingwmic ``` wmic diskdrive list ``` for less info ``` wmic diskdrive list brief ``` Alternatively in c use GetLogicalDrives() first to get all of the drives mapped in the system, and then GetDriveType() to find out which sort of drive each one is. Then sort it out as you want to.
I have the following code: ``` volatile unsigned int * address; char * array="0x10000008"; ``` Please tell me, what is a correct way of writing the "array" value to "address" variable?
You could usesscanf: ``` #include <stdio.h> sscanf(array, "%p", &address); ``` orstrtoull: ``` #include <stdlib.h> address = (unsigned int *)strtoull(array, NULL, 0); ```
I have made a basic client and server in C using BSD sockets. I am able to bind to a port number above 65535, and the client can connect to it. What am I doing wrong here? Code: ``` int port = 999999; ... serverAddr.sin_port = htons(port); ```
Because htons takes a 16 bit argument and its input will be truncated. Try this and see what you get: ``` #include <stdio.h> #include <arpa/inet.h> int main(int argc, char **argv) { int foo = 999999; int bar = ntohs(htons(foo)); printf("%d\n", bar); return 0; } ```
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago. My file A.txt reside in particular ...
If the whole file won't fit in memory, don't slurp the whole file into memory; process it one line at a time. Or get more memory.
I have these variables: ``` char* name = "bobsux"; int score = 100; char* scoreHash = "f899139df5e1059396431415e770c6dd"; ``` Printing these using format specifiers and printf, returns this: ``` printf("name=%s&score=%d&score_hash=%s", name, score, scoreHash); => name=bobsux&score=100&score_hash=f899139df5e1059...
You usesnprintf()to format the text into a character array: ``` char scoreData[128]; snprintf(scoreData, sizeof scoreData, "name=%s&score=%d&score_hash=%s\n", name, score, scoreHash); ```
In C (before C99), booleans are usually represented as ``` typedef int bool; #define true 1 #define false 0 ``` Why it is represented as 'int' rather than 'float'? This is an interview question, even I wonder why such question is asked! Any convincing answers?
boolvalues are mostly used in comparisons, and using theinttype uses theinteger ALUfor these comparisons. It is very fast, as it's in the CPU's normal pipeline. If you were to use thefloattype, then it would have to use the floating-point unit, which would take more cycles. Also, if you wanted to support using your...
I get this problem while compiling my code. ``` Error 14 error LNK2019: unresolved external symbol _findFuncs referenced in function _main H:\pshtoolkit_v1.4-src\whosthere\whosthere.obj whoisthere-alt ``` What libraries should I link with visual studio in order to resolve the error?
What libraries should I link with visual studio: The library containing _findFuncs. OK, not helpful I know, but presumably you know what findFuncs is and you are calling it for a reason. Where did you find out about it? Do you have any documentation? Maybe you have a typo calling this function (case?), e.g. should...