question
stringlengths
25
894
answer
stringlengths
4
863
I am using espeak on BSD to output text as sound. My problem is that I want it to take it as a .mp3 but I am having little luck. I tried piping the output to tee but I guess that only works with stdout not just playing a sound. Any ideas? My last resort would be recompiling my own version of espeak that allows me to ...
you can write it as wave and then convert it withffmpeg: ``` espeak "HelloWorld" -w <file>.wav ``` Or pipe toffmpeg ``` espeak "HelloWorld" --stdout | ffmpeg -i pipe:0 output.mp3 ```
I'm creating the following buffer: ``` char *buffer; int buffer_size = 1024; buffer = (char*) ( malloc(buffer_size * sizeof(char) ); ``` Then when I do: ``` int actual_size = sizeof(buffer); printf("Size: %d", actual_size); ``` What it prints is: ``` size: 4 ``` While I would expect it to be 1024, why is this?
This does not work like that ``` sizeof(buffer); ``` returns the size ofbufferwhich is a pointer, not an array. If you have an array such as the following ``` char szArray[100]; ``` then ``` sizeof(szArray); ``` would return 100 becauseszArrayis an array, but apointeris not an array.
I have partition structure like : ``` $ df Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda6 51606140 16939248 34142692 34% / /dev/sda5 495844 72969 397275 16% /boot /dev/sda7 113022648 57515608 49765728 50% /home /dev/sda8 113022648 57515608 49765728 4% /mnt ``...
you can just do ``` df <file_name> ``` that will give you the device and partition for the particuar file
I read tons of tutos and snippets, but I still don't understand why I get a segfault with this: ``` int fun(char **p) { int i; *p = malloc(2); *p[0]=10; *p[1]=20; // segfault NULL pointer printf("fun()/n"); for (i=0; i<2; i++) printf("%d ",*p[i]); } int main(int argc, const char *argv[]) { char* ...
You mean(*p)[1]. What you said is*(p[1]).
Can the following macro bring problems? ``` #define sq(x) x*x ``` If yes, then how and why?please help.
Yes, it can present problems. Other than the obvious fact that macros don't respect namespaces at all (which means you can't call anything elsesq), try the following: ``` int result = sq(4) / sq(4); ``` You should surroundx * xwith parenthesis so it becomes((x) * (x)). Another problem: ``` int a = 0; int result = ...
Is it safe to assume that the condition(int)(i * 1.0f) == iis true for any integeri?
No. Ifiis sufficiently large thatint(float(i)) != i(assuming float is IEEE-754 single precision,i = 0x1000001suffices to exhibit this) then this is false, because multiplication by1.0fforces a conversion tofloat, which changes the value even though the subsequent multiplication does not. However, ifiis a 32-bit inte...
Say I have a string likeab234cid*(s349*(20kdand I want to extract all the numbers234, 349, 20, what should I do ?
You can do it withstrtol, like this: ``` char *str = "ab234cid*(s349*(20kd", *p = str; while (*p) { // While there are more characters to process... if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) { // Found a number long val = strtol(p, &p, 10); // Read number printf("%ld\n...
What I was always doing is: ``` int arr[] = {2, 3, 4}; ``` and it always worked. I've heard of a better way to initialize new array, using the pointer: ``` int *arr = {2, 3, 4}; ``` However, it doesn't work in any IDE, it throws some errors likeint differs in levels of indirection from int, ortoo many initializer...
``` int arr[] = {2, 3, 4}; ``` is just fine, and completely correct. No need to change.
How do I programmatically get the core a given thread is running on? Something like Unix'sgetcpuid. This is for Linux, and C.
Doessched_getcpu()not give you a different value for the cores?
How to insert time/date received into time_t structure into column which has 'timestamp without timezone' type? Previously I was using int8 as data type and time_t perfectly fits but I would like to know how to do it with timestamp field(preferably without casting time_t to string from caller program) using PQexecPar...
Use theto_timestampfunction. Example: ``` select to_timestamp(1000000000)::timestamp; ``` Result: ``` to_timestamp --------------------- 2001-09-09 03:46:40 1 row) ```
I would like to store the user's mouse click position on two variables ``` float x,y; ``` I'm using openGL withC. I already have a mouse function using glut, but when I try to print x and y, it gives me values likex = 134; y = 150, while my screen ortho is between 0 and 1. I want to get the exact points to draw a p...
you need to register a mouse callback function it has the following signature: ``` void glutMouseFunc(void (*func)(int button, int state, int x, int y)); ``` There's a tutorial that covers some basicshere Edit: If you want the position to be normalized (0.0 - 1.0) divide by the width...
I know that many basic operations like addition or division can also be implemented in C using only bitwise operators. How can I do the same with the greater than or equal sign (>=)? ``` if (x >= 0) { ... } ```
Simplest solution I can come up with: ``` #include <limits.h> if ((x & INT_MAX) == x) // if (x >= 0) ... ``` If you don't like the==then use XOR to do the equals test: ``` #include <limits.h> if ((x & INT_MAX) ^ x) // if (x < 0) ... else // else x >= 0 ... ```
As we all know we can have/dev/video0as a directory for receiving the output of a webcam. Is it possible to create a fake/dev/somethingdirectory through aCprogram and continuously output there the contents of some created png files in order to create afake webcamfor example? I will then read thelivestream for an oth...
If all you need is a place in the filesystem where some application can read some specific data, usemkfifoto create it. Then you can write a producer that writes whatever you need at whatever bitrate to it and have a consumer reading from it. If you output what the consumer expects, you might be able to get something...
I get 2 double numbers -basicandpow, and I have to calculatebasic^power. My problem is that there is cases should throw error - like if thepowis a fraction like odd/even and the basic is a negative - for examplebasic=(-2)andpow=0.75=(3\4)So it should be(-2)^3=-8and thenroot 4 of -8means error . so how can I detect ...
From the man page ofpow(): pow(x, y) returns a NaN and raises the "invalid" floating-point exception for finite x < 0 and finite non-integer y. So check for this.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
Unless I am misunderstanding the question: ``` function atoi($string) { return (int) $string; } ``` It sounds like a trick question to see if you understand the concept of php as a loosely typed language. So yes, it's fair to ask.
Lets say I do something like this ``` int *array; array = new int[10]; ``` How is memory set up for this array? What type isarray[0]? (a pointer? an int?)
This code first allocates room for a pointer called array. This memory is allocated on the stack. Next, it allocates a block of memory from the heap to hold 10 integers and assigns the address toarray. array[0]will refer to the first integer in the block of 10. The subscript makes it a value instead of a pointer. A...
I am writing a heap data structure in C. Theres one thing that I can't decide on. I am implementing it as an array. The way it works, is that function "insert" takes a pointer to some data and copies all bytes of that data, pointed to, into the array, is that a good approach? Or should I just store the pointer itself,...
Well, you have to consider that the memory pointed to will probably be changed or become invalid, for example when it's a variable on the stack. So in most cases, it would not be a good idea to just store the pointer. If youmusthave a function insert() there is no way around copying the memory - although this is slow....
issprintfthread safe ? ``` //Global log buffer char logBuffer[20]; logStatus (char * status, int length) { snprintf(logBuffer, 19, status); printf ("%s\n", logBuffer); } ``` The thread safety of this function totally depends upon the thread safety ofsnprintf/sprintf. Updates :thanks for ur answers . i dont m...
There is no problem usingsnprintf()in multiple threads. But here you are writing to a shared string buffer, which I assume is shared across threads. Soyour useof this function wouldnotbe thread safe.
This question already has answers here:Closed10 years ago. Possible Duplicate:Why does printf not flush after the call unless a newline is in the format string? When I run something like ``` for (i = 1; i <= 10; i++) { sleep(1); printf("."); } ``` then what I would expect is one dot per second ten times. W...
Theprintf()is buffering the data, you can force it to flush that data withfflush(stdout): ``` for (i = 1; i<=10; i++) { sleep(1); printf("."); fflush(stdout); } ```
I had no luck finding precompiled packages of glibc for apple darwin. I could not compile gcc from source, and I'm assuming that compiling glibc will also be very difficult. What I want: Configuring the darwin system so that it only uses the GNU C runtime libraries, along with gcc. I can specify more if needed.
I still haven't found a solution to this problem, but that is irrelevant now. The segmentation fault can only be reproduced in the 64 bit darwin libc. Furthermore, running the program with valgrind on the darwin suppresses the fault. This led me to the conclusion that the problem is in the code, rather than the libra...
I want to add a standard header to a file (or group of files) using C. These files could be quite large, so it would be a bad idea to load them into memory, or copy them into temporary files (I think). Is there a way to simply prepend the header directly to each file? The header itself is quite small, not more than ...
You cannot insert data into a file. However, there is no need to load the entire file in memory. Just create a new file, write the data you are inserting, then copy the contents of the original file to the new file (do it block by block instead of loading the entire file into memory). Finally, delete the original fi...
This question already has answers here:Closed10 years ago. I'd like to know, how to calculate integer values of strings in single quotes' '. My sample code is: ``` #include <stdio.h> int main() { int c = 'aA'; int d = 'Aa'; printf( "%d %d" , c, d); return 0; } ``` And the output is: ``` 24897 1...
These are: not strings!multibyte integers, of which the value is implementation-defined, but it is usually calculated using this formula:integer value of 1st character multiplied by (2 << CHAR_BITS) + integer value of 2nd character So, assuming your C locale uses ASCII and you have 8-bit bytes,'aA'becomes ``` 97 * ...
If I have a C string that contains *'s and I want to find the position of the 3 star in this string. What is the best/ more efficient way to do it other than going through a loop and checking char by char? Thanks
You probably want to do the searching withstrchr. Since you want the third instance of the character, you'll still execute that in a loop. Whether this will actually be more efficient than writing a loop on your own may be open to some question, but it probably won't be any slower, and the intent will be more clear t...
My code is something like this:- ``` for() //outer for { for() //inner for { if() { break; } } } ``` If the break statement executes the next execution will be of which for loop? I know this is a very abstract question but I really don't have time to write the full code. Thanks.
breakwill break the inner for**loop**only.It breaks the closest loop ONLY where it was called. In your example, if yourifcondition is satisfied, it will stop iterations of the inner for loop and move back(continue) the outer for loop.
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. I am trying to compile a C project ...
The problem is that the command CLS does only exist on Windows. For Linux, the command you want is:clear. Anyway, that will only partially solve the problem: a) you'll have the same problem if you port your program to a windows machine, and b) there is no reason for that to produce a segmentation fault.
I was wondering if you can do something like: ``` printf("\nEnter kwh used (for 7 economy tariff, enter Peak usage)\n"); scanf("%d",&kwh,&peak); ``` I guess it won't work but is there any way to get similar effect. I hope you know what I mean. I'm trying to get either one (peak or kwh) out of one scanf so it can lat...
If you want the same value in both variables, you should do that yourself: ``` int kwh, peak; if (scanf("%d",&kwh) == 1) { peak = kwh; } else { // complain } ```
Hi fellow stackoverflowers, I want to compile a SWIG project with g++ using following command: ``` g++ -shared python/swig_wrap.o -IC:/Python27/include/ -lpython2.7 -o python/_lib.so ``` Unfortunately, g++ or rather ld.exe complains that it can't find -lpython2.7 ``` c:/mingw/bin/../lib/gcc/mingw32/4.7.2/../../.....
Try : ``` g++ -shared python/swig_wrap.o -IC:/Python27/include/ -LC:/Python27/libs -lpython27 -o python/_lib.so ``` It should normally work.
Is there any inbuilt function in c++ or c libraries that can be used to find distance between two points in 2-D space PS: I know how to implement it myself.
Well, you can use arithmetic oncomplex numbers: ``` using point_t = std::complex<int>; double distance(point_t a, point_t b) { return std::abs(b - a); } ``` I realise that this doesn’tquitefulfil your requirement of not writing your own function but the actual distance logic is implemented in thestd::normfuncti...
I have two variables:bufandlength(char buf[BUFSIZE], int length).Bufcontains DNS messages sent with UDP protocol and inlengththere is length of that message. Now I need to changebufso I can use it with TCP protocol and send it to DNS server and get response and that response change back to UDP protocol. I know I shou...
You need to open a second socket of type SOCK_STREAM and then use send() to send the content ofbuf: ``` sock = socket( AF_INET, SOCK_STREAM, 0 ); connect(...); send( sock, buf, length, 0 ); ``` This works because when working with sockets, you usually don't get the protocol headers, just the UDP/TCP payload.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he...
If you're comfortable with Eclipse, you can use that just fine in any linux distro as well. You may also want to have a look atcscopeandctags, two command line tools that can be integrated into most editors and IDE's you may choose to use. They can of course be used standalone as well.
``` static TCHAR szWindowClass[] = L"foo"; ``` Lis "glued" to the string"foo". How come? A function or a macro as I am used to is something likeL("foo"); Can anyone explain me how come L be glued to the string?
Lis not a macro, it's just the standard prefix for wide (wchar_t, "Unicode") string literals; the concept is similar to theLsuffix forlong intliterals,fsuffix forfloatliterals and so on1. By the way, if you are usingTCHARs you shouldn't be usingLdirectly; instead, you should use the_T()orTEXT()macro, that addsLat the...
im writting program in ANSI C, and and have one function, where im passing pointer to semaphores arraystruct sembuf semb[5]. Now header of that function looks like: ``` void setOperations(struct sembuf * op[5], int nr, int oper) ``` But im getting warning: ``` safe.c:20: note: expected ‘struct sembuf **’ but argu...
This is how the function should be declared if you want to pass a pointer to an array and not an array of pointers: ``` void setOperations(struct sembuf (*op)[5], int nr, int oper); ```
I can't reproduce this with a simple program, but somewhere in my program I have something like: ``` float e = f(...); if (e > 0.0f) { ... ``` printf("%f", e)shows thateis0.000000, yete > 0.0fis true... So ise > 0ande > 0.0. What am I missing?
The floating point value is larger than zero, but less than 1e-7. It's printing issue. Use scientific notation printf("%e", value); or "%g" for shortest notation.
How do you compile a C application with Ruby embedded? What's the-lflag? Is there something else that i'm missing (linking to an exact ruby version)
Embedding a language usually links the interpreter with the binary that embeds it,-llinks a library with the program, you could try: ``` gcc -Wall -I/usr/include/ruby-1.9.1/ myprog.c -o myprog -lruby ``` Note you may need to include this too, or similar on your platform: ``` -I/usr/include/ruby-1.9.1/x86_64-linux/ ...
given the following code: ``` const myStr codesArr[] = {"AA","BB", "CC"}; ``` myStr is a class the wrapschar*. I need to loop over all the items in the array but i don't know the number of items. I don't want to define aconstvalue that will represent the size (in this case 3) Is it safe to use something like: ``...
The safe and clear way to do this is to usestd::extent(since C++11): ``` const size_t size = std::extent<decltype(codesArr)>::value; ```
I want to useenumas function return type or as a argument. But when I give it as is, it's giving error message. But if Itypedefthe same, it's working fine. ``` #include <stdio.h> enum // if *typedef enum* is used instead, it's working fine { _false, _true, } bool; bool func1(bool ); int main() { ...
You are not making a newtypebool, instead you are declaring avariablenamedbool.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen...
The basic entry point of hardware input/output control isioctl(orDeviceIoControlon Windows, described on the same Wikipedia article).
I don't manage to remove awarning C4018: '<' : signed/unsigned mismatchfrom this code: ``` SOCKET s; fd_set set; FD_CLR(s,&set); ``` It seems to me that the problem is inside the implementation of VS2005's FD_CLR, and actually it's not a big issue, just quite annoying. Is there a portable equivalent version of this ...
Instead of disabling the warning globally, or locally every time you callFD_CLR(), perhaps write a wrapper for that call that disables that particular warning locally for you.
When i'm not calling the same function in my code everything works well but when the function returns from a recursion suddenly the variablepchis NULL: ``` void someFunction() { char * pch; char tempDependencies[100*64+100]; strcpy(tempDependencies,map[j].filesNeeded); pch = strto...
strtok()is not reentrant. If you want use it in a recursive function you must usestrtok_r(). See also:strtok, strtok_r
``` void testFunc(int); int main(int argc, char** argv) { testFunc(1); testFunc(2); testFunc(3); return (EXIT_SUCCESS); } void testFunc(int another) { int num; printf("num: %i\n", num); num = another; } ``` output: num: 127383283 num: 1 num: 2 If I am printing the variable before I as...
Youaregetting garbage values - it just so happens that in this case those garbage values happen to be the value that you assigned in the previous invocation of the function. If you call another function in between the calls totestFunc(), or compile with higher optimisation settings, or with a different compiler, you'...
When writing my server code I have this line: ``` newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen); ``` When I run the program I get no errors, but the program just freezes, and I put a print statement at the first line of themain()(so it should run before anything runs) but the print statement nev...
Since this was apparently the answer, I'll write it here: If yourprintfformat strings don't end with "\n", then they'll be buffered until either you do print a newline or your program exits. (I'm simplifying a bit.) Since youracceptcall stopped your program after that output was buffered, you couldn't see the output e...
I'm using sockets to connect and the client needs the hostname of the server. I'm running it all on the same machine and my hostname worked. The problem was that my hostname was REALLY long and I didn't want to spend all that time typing it out. So, What I did was I sudo su'd and did ``` hostname brandon ``` I then ...
it's/etc/hostsinstead of/etc/hostname You could add a line in /etc/hosts file to resolve the hostname lookup ``` xxx.xxx.xx.xxx brandon ``` replacexxx.xxx.xx.xxxwith the real ip address
I am trying to convert decimal number into its fraction. Decimal numbers will be having a maximum 4 digits after the decimal place. example:- 12.34 = 1234/100 12.3456 = 123456/10000 my code :- ``` #include <stdio.h> int main(void) { double a=12.34; int c=10000; double b=(a-floor(a))*c; int d=(int)floor(a)*c+...
If your floating point number isx, then the numerator of the fraction over 10000 will be the integral part of(x + 0.00005) * 10000. It's up to you whether you want to reduce the fraction to simplest terms (i.e. divide out by the gcd of the numerator and denominator).
i try to print all the letter from A to Z and from a to z and their ascii codes but i end up with an infinite loop when i am trying to run it ,so where is the mistake ? ``` #include <stdio.h> int main(void) { int i; char ch_1,ch_2; for (ch_1='A'; ch_1<='Z'; ch_1++) printf("letter: %c ASCII code:%d\n",ch_1,ch_1);...
``` for (ch_2='a'; ch_2<='z'; ch_2++) ``` and not ``` for (ch_2='a'; ch_1<='z'; ch_2++) ```
This question already has answers here:Closed10 years ago. Possible Duplicate:Difference between different integer types What is the difference betweenuint32anduint32_tin C/C++? Are they OS-dependent? In which case should I use one or another?
uint32_tis standard,uint32is not. That is, if you include<inttypes.h>or<stdint.h>, you will get a definition ofuint32_t.uint32is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
The output of the code below is "Overflow", but I didn't explicitly call thefuncfunction. How does it work? ``` #include<stdio.h> #include<string.h> #include<stdlib.h> int copy(char *input) { char var[20]; strcpy(var, input); return 0; } int func(void) { printf("Overflow\n"); return 0; } int ma...
Thecopyfunction overflows thevarbuffer in thecopyfunction and overwrites themainreturn address with the address of thefuncfunction. Whencopyfunction returns, instead of returning tomainafter thecopyfunction call, it returns tofuncfunction.
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. I'm looking for Xlib function or ma...
Doing a quick search tells me it's not possible directly with xlib. However it seems possible using the XRandR extension, with the functionXRRConfigRates.
I'm reading this text from a file: ``` file1: file2,file3,file4 file10: testfile.h file1: file9 ``` and splitting it ``` while(fscanf(fp,"%[^:]: %s",map[i].name, map[i].filesNeeded) == 2) { printf("%s %s",map[i].name, map[i].filesNeeded); i++; } ``` The problem is that the second and third variables are sa...
add space for" %[^:]: %s " ``` while(fscanf(fp," %[^:]: %s ",map[i].name, map[i].filesNeeded) == 2) ``` the space in the scanf absorbs the space characters, tabulation characters, new line characters
Can I use pipe between two process without using fork and share file descriptors with for example socket ? I don't need another solution, I need pipe between two process that not forked.
You could use a named pipe (FIFO): if you domkfifo <common path>, you an use this path in both processes, one for reading and one for writing. Then you have the same behaviour as with a normal pipe.
I'm messing with the pty with C, but for some reason the code doesnt compiles ``` #include <pty.h> #include <stdlib.h> #include <stdio.h> void main(){ int fd; ptyfork(&fd,NULL,NULL,NULL); } ``` I compiled with -lutil, and outputs the next error: ``` gcc -lutil test3.c -o test3 /tmp/ccgTfZvt.o: In function ...
The function isforkpty, notptyfork. See thedocumentation.
This is the line i'm trying to split, from the start until the:, eat any whitespace and from there onwards: ``` file1: file2,file3,file4 ``` And my code is: ``` while(fscanf(fp,"%s: %s",map[i].name, map[i].filesNeeded) == 1) { printf("%s %s\n",map[i].name, map[i].filesNeeded); i++; } ``` The second parameter...
Firstly, fscanf will increment the return for each item matched, so it should be == 2. Also, you will want to use %[^:] instead of %s as the %s won't know when to stop. ``` int main(int argc, char** argv) { char test[] = "one: two,three"; char part1[20]; char part2[20]; printf("%i\n", sscanf(test, "%[^:]: ...
I ran into a very strange problem. I think I am missing some very basic thing here. When I do this: ``` char buffer[1] = {0xA0}; int value=0; value = (int)buffer[0]; printf("Array : %d\n",value); ``` I get result as -96, which shouldnt happen. It should give me 160, as hexa number 0xA0 means 160 in decim...
charis signed -128 to 127 Declarebufferasunsigned charor cast tounsigned char: ``` char buffer[1] = {0xA0}; int value=0; value = (unsigned char)buffer[0]; printf("Array : %d\n",value); ```
The size of the test.bin is 7,01,760 bytes. I am trying to read date from this file as "short" in a buffer bufferPointer. ``` short * bufferPointer=NULL; // ==> ANSWER WAS ADDING: bufferPointer = ( short*)malloc(350880); <== FILE *fp=fopen(" test.bin","rb"); fread(bufferPointer,sizeof(short),350880 ,fp); fclose(fp)...
You allocated 350880 bytes for your buffer but tried to read 350880 shorts. Try ``` bufferPointer = malloc(350880 * sizeof *bufferPointer); ``` (Note that casting malloc isn't necessary, and is frowned upon because it can hide bugs.) You should also check your malloc, fopen, and fread calls for errors.
i thought short is 1? why did it increase by 8, from 16 to 24?
This is a question of data typealignment. Can someone explain to me why the offset is 0, 4, 8 16 and 24? The first item is always going to be at the beginning of the structure (offset 0). Thechartakes up one byte, so the next offset would be 1. However, thedouble*is 4-byte aligned (for performance), so it goes to t...
I need to return two arrays of integers in a C-language function for postgresql. Afaik, the best way to return two arrays of integers in a postgresql function is to declare the function with OUT parameters. But how to return two output parameters in a C-language function for postgresql? Should I return a tuple of two ...
You have to return tuple of two arrays. In reality Postgresql's function returns only one parameter every time. It is relative complex task, but it is possible. You can find some examples - google keyword is PG_RETURN_HEAPTUPLEHEADER
This question already has answers here:Closed10 years ago. Possible Duplicate:What the pointer size in 64 bits computer in C++? I'm studing C at The University. I try to setup an environment for programming on Windows 7/8 and have a problem This code: ``` int main() int *p; printf("%d",sizeof(p)); return 0;...
You probably compile the code into 32 bit application. You need to compile it as 64 bit application. Check your compiler settings. It does not matter that your OS is 64 bit.
Is there a debugger (free if possible) that can visualize image buffers during debugging sessions. Something like: I stop at breakpoint.Then I select an image buffer, give directions of what the data is - RBG, CMYK, 8bit, float, whatever.I am shown an image (or it is saved) made from the data.
If you are using gdb to debug your program, you can call your own(or some other library functions) that can visualize the image buffer for you(possibly in a separate window) from the gdb prompt once you reach a breakpoint.
I am trying to find an example code which usesllvm::CloneBasicBlock, but can't find it. I am having problems with PHI nodes and problem with instruction domination. So I'll appreciate any good example code which teach how to usellvm::CloneBasicBlockproperly.
What's wrong with looking in the LLVM source itself?CloneBasicBlockis used in a number of places. The simplest is probablyllvm::CloneFunctionInto; it should probably be enough to demonstrate how to correctly use the function (in terms of what arguments to pass, etc.) A more interesting example is inllvm::LoopUnroll, ...
I am working with Ubuntu 12.04. I want to use the AUX library for OpenGL. Can anybody tell me what steps are involved in getting the AUX library for my system?
I want to use the AUX library for OpenGL. No, you don't! GlAux is unmaintained and a most annoying PITA. You want to use GLFW, SDL, SMFL, or maybe FreeGLUT.
I'm going to write a code which will extensively execute other programs. I don't want it to have root privileges if someone set a set-user-id bit(and root is an owner). So I'm going to drop privileges at startup. My question is: How can I understand from within the program whether it run inset-user-idmode?
You can compare result ofgetuid()andgeteuid()library calls. Ifgeteuid()returns 0 (root), butgetuid()returns not 0, you can say that suid is active.
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. I want to save a location in file, ...
Seethis pagefor information about theftellandfseekfunctions. These will allow you to retrieve and set the position of the file pointer, respectively. ``` long int originalPos = ftell(fp); // do stuff with file fseek(fp, originalPos, SEEK_SET); ```
I know we can useWriteFileto write something to a file: ``` BOOL WINAPI WriteFile (HANDLE hFile, LPCVOID lpBuffer, DWORD numOfBytesToWrite, LPDOWRD lpNumOfBytesWritten, LPOVERLAPPED lpOverlapped); ``` But how can we write A...
Usually something like this: ``` WriteFile(your_file, your_string, strlen(your_string), &written, NULL); ``` You usually don't want to do this though -- unless your strings are pretty long, it'll almost always be more efficient (i.e., faster) if you use something likefprintforfputsto take advantage of the buffering ...
I am not able to understand the output of the following C code : ``` #include<stdio.h> main() { char * something = "something"; printf("%c", *something++); // s printf("%c", *something); // o printf("%c", *++something); // m printf("%c", *something++); // m } ``` Please help :)
Seehttp://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedencefor details ``` printf("%c", *something++); ``` Gets the char at *something and then increments it ('s') ``` printf("%c", *something); ``` Just get the char (now the second, due to the increment in the last statement ('o') ``` printf("%...
I'm playing around with strncpy in C and am having some trouble. The code is as follows: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char src[] = "Benjamin Franklin"; char dest[5]; strncpy(src, dest, sizeof(dest) / sizeof(char)); dest[5] = '\0'; printf("%s\n",...
Your parameters are backwards.strncpycopies the second string into the first string, like so. ``` strncpy(dest, src, sizeof(dest) / sizeof(char)); ```
I'm working on Fedora 17 and I want to program with libpcap. The problem is that my computer isn't finding pcap.h, which is really wierd since I've installed libpcap and libpcap-devel. Also wireshark and snort works on my station which I believe uses that library. So when I compile my code with ... ``` #include <pcap...
Your library might be missing, install it and link it ``` yum install libpcap-devel ``` In your makefile add: ``` -L/usr/lib -lpcap ```
I have this function that takes a char** and a char* as parameters and it's supposed to return either the index of the char* in char** or return -1 if it's not in the string array. The error I'm sure is thewhile(arr[i] != NULL)...but I'm not sure how else to do it. ``` int isInArray(char** arr, char* str) { i...
You probably forgot to set the lastchar*element ofarrto NULL. If you can't do that, then you should introduce a third argumentsize_t arr_lento pass the length ofarr. Unrelated tip: since you're not modifying*stror*arr, be const-correct and use: ``` int isInArray(const char* const* arr, const char* str) ```
I usually get a warning from the compiler if I tell it to return anything else.
This is the exit code provided to whoever called your program. Non-zero value usually signifies error.
Is it possible to tell GCC to usewarn_unused_resultflag for all function even not having the corresponding attribute? Because if I can forget to check for return value, I can also forget to add the GCC specific attribute. I've seen it to be possible with some other compilers.
No, you can only tell gcc to ignore allwarn_unused_resultflags with-Wno-unused-resultbut the respective-Wunused-resultonly sets the default (to warn only on flags). Compiling with-Wall -Wextra -pedanticshould have triggered a warning if it can be activated but it doesn't, so it cannot. Besides that, I wonder why you ...
I am not able to understand the output of the following C code : ``` #include<stdio.h> main() { char * something = "something"; printf("%c", *something++); // s printf("%c", *something); // o printf("%c", *++something); // m printf("%c", *something++); // m } ``` Please help :)
Seehttp://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedencefor details ``` printf("%c", *something++); ``` Gets the char at *something and then increments it ('s') ``` printf("%c", *something); ``` Just get the char (now the second, due to the increment in the last statement ('o') ``` printf("%...
I'm playing around with strncpy in C and am having some trouble. The code is as follows: ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char src[] = "Benjamin Franklin"; char dest[5]; strncpy(src, dest, sizeof(dest) / sizeof(char)); dest[5] = '\0'; printf("%s\n",...
Your parameters are backwards.strncpycopies the second string into the first string, like so. ``` strncpy(dest, src, sizeof(dest) / sizeof(char)); ```
I'm working on Fedora 17 and I want to program with libpcap. The problem is that my computer isn't finding pcap.h, which is really wierd since I've installed libpcap and libpcap-devel. Also wireshark and snort works on my station which I believe uses that library. So when I compile my code with ... ``` #include <pcap...
Your library might be missing, install it and link it ``` yum install libpcap-devel ``` In your makefile add: ``` -L/usr/lib -lpcap ```
I have this function that takes a char** and a char* as parameters and it's supposed to return either the index of the char* in char** or return -1 if it's not in the string array. The error I'm sure is thewhile(arr[i] != NULL)...but I'm not sure how else to do it. ``` int isInArray(char** arr, char* str) { i...
You probably forgot to set the lastchar*element ofarrto NULL. If you can't do that, then you should introduce a third argumentsize_t arr_lento pass the length ofarr. Unrelated tip: since you're not modifying*stror*arr, be const-correct and use: ``` int isInArray(const char* const* arr, const char* str) ```
I usually get a warning from the compiler if I tell it to return anything else.
This is the exit code provided to whoever called your program. Non-zero value usually signifies error.
Is it possible to tell GCC to usewarn_unused_resultflag for all function even not having the corresponding attribute? Because if I can forget to check for return value, I can also forget to add the GCC specific attribute. I've seen it to be possible with some other compilers.
No, you can only tell gcc to ignore allwarn_unused_resultflags with-Wno-unused-resultbut the respective-Wunused-resultonly sets the default (to warn only on flags). Compiling with-Wall -Wextra -pedanticshould have triggered a warning if it can be activated but it doesn't, so it cannot. Besides that, I wonder why you ...
Linux buffers all received messages received on a socket. But before receiving, this messages had a beginning and an end. Linux writes this messages sequentially in the buffer, loosing therefore the information of the end of the message. I know that in Linux I could use cmsg_header.But Windows does not offer send-/re...
I am not sure that TCP/IP connections are exchanging well delimited messages. Routers could fragment packets. (Socmsg_headercould be unreliable). All TCP/IP based protocols I know about (HTTP, SMTP, X11, RPCXDR) are handling message organization at the application level. Your application library need to know somehow ...
I want to write a C++ wrapper for the Linux Socket API. In the socket() ctor the adress family (AF) is requested. I dont want to require the AF in the connect() signature again, becuase it has been already given in the constructor of socket. So how do I get the AF from an existing socket?
Damn. Searched about half an hour. Now after posting this question I found immiediately the answer. getsockopt([...])with option SO_DOMAIN (seesocket options)
I am trying to loop a char*str use this to find out how many lines: ``` char *str = "test1\ntest2\ntest3"; int lines = 0; for(int i = 0 ; i < ?? ; i ++ ) { if(str[i] == '\n') { lines++; } } ``` I am not sure what to put at the ??, the question is : 1.I mean do I need to use strlen(str) + 1 ? 2.w...
every literal string ends with\0which is a null character..It depicts the end of the string So, You can do this ``` for(int i = 0 ; str[i]!='\0' ; i ++ ) ```
I need to make a rule in my lex file that will identify the start of a newline and a sequence of spaces I did this^( )*but the compiler says it is wrong what is the right way to define it?
Try something like this: ``` ^[\n\t ]+ ```
This question already has answers here:C program to convert Fahrenheit to Celsius always prints zero(6 answers)Why does division result in zero instead of a decimal?(5 answers)Closed5 years ago. I am trying to calculatep1=(1/1)*(1/2)*...*(1/n)but something is wrong and theprintfgives me0.000...0 ``` #include <stdio....
``` (1/i) ``` iis anint, so that's integer division, resulting in 0 ifi > 1. Use1.0/ito get floating point division.
So all I need is simple: if object color is (255, 10, 10) then each visible point of it shall be rendered as (255, 10, 10). No lights, no shadows, no shades, no reflections/refractions and no transparency. I only want to provide vertex meshes and colors for them and see them rendered. Can such thing be implemented wit...
You need to disable the lighting : ``` glDisable(GL_LIGHTING); ```
I'm writing a program searching a file in Mac OS filesystem. I would like to how to pop up the GUI folder with finder once my program found the file. Is this possible? Is there any system calls I can using to open a directory with finder? It is written in C Thanks for any input!
I think you want to use theopencommand. You can useopen .to open the finder window corresponding to the current directory, oropen document.pdfto open a particular document with its corresponding default application.
Could you post some examples how to read list of meanings from/procfiles? ``` list_head* get_from_proc_file() { struct file* file = fopen("example","r"); seq_open(file, &seq_ops); struct seq_file *p = file->private_data; READ LIST OF DATA????? } ```
You can't usefopenas this is a libc function. The example bellow shows how to read a file from the kernel. http://www.wasm.ru/forum/viewtopic.php?pid=467952#p467952
when I click the properties of .Dll -> Details , I get this window: I want to access this information and change \ add File version and Product Name Can I get some help with it ? how can I access it ? I saw that in C# I can use : ``` string fileVersion = FileVersionInfo.GetVersionInfo(file).FileVersion; string prod...
Version information is kept as resource files in Windows. You can check the source code of thistoolfor how to change the resource in a file.
Is this possible? Or is there gonna be a lost list? Cause I can't check if its working or not ``` void FreeRecurs(struct nodeTag *pFirst) { if(pFirst != NULL) { FreeRecurs(pFirst -> pNext); free(pFirst); } } ```
That will work, but on long lists, you may get a stack overflow because you're recursing a lot and are not using tail recursion. I'd move to an iterative version: While the current node is not NULL:Store a pointer to the next node.Free the current node.Start working on the next node using the pointer you stored just ...
For homework I have to read from the standard input, save it to a file and then read the file in another process. However, I'm confused as to why this code does not work: ``` while((n = read(0,buf,sizeof(buf))) > 0) { int tempfile = open("testfile", O_TRUNC | O_CREAT, 0666); write ( tempfile , buf , s...
You've specifiedO_TRUNC | O_CREATfor the open flags, but you've failed to specifyO_RDWRorO_WRONLY. You also probably want to writenbytes, notsizeof(buf), as the remainingsizeof(buf) - nbytes are uninitialized.
What's the usefulness of the functionmemset()?. Definition: Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char). Does this mean it hard codes a value in a memory address? memset(&serv_addr,0,sizeof(serv_addr)is the example that I'm trying to unde...
memset()is a very fast version of a relatively simple operation: ``` void* memset(void* b, int c, size_t len) { char* p = (char*)b; for (size_t i = 0; i != len; ++i) { p[i] = c; } return b; } ``` That is,memset(b, c, l)set thelbytes starting at addressbto the valuec. It just does it much fast...
``` while(getline (&line, &line_size, f) != -1){} ``` I'm using this function to read line line. But i want to know when i'm reading a blank line. Can someone help?
so as H2CO3 already mentioned you can use the line length for this: ``` while (getline (&line, &line_size, f) != -1) { if (strlen(line) == 1) { printf("H2CO3 spotted a blank line\n"); } /* or alternatively */ if ('\n' == line[0]) { printf("Ed Heal also spotted the blank line\n"); ...
I am trying to write simple pgm file reading C program. I had to create simple structure: ``` typedef struct pgmImage { int R; //rows int C; //collumns int G; //grey scale int **pix; // array of pixels }Image; ``` Now i have to initialize empty Image structure.I need one to set all variables based on *....
If you want a pointer to Image you have to initialize like this. ``` Image *x = NULL; ``` Accessing the image (x) camps like this : ``` x-> C = 0; x-> ... x->pix = NULL; ``` But first you need to allocate memory to your image. ``` x = (Image*) malloc(sizeof(Image)); ```
For a project I am working on I use magic numbers. This macro is used to define one ``` #define BOOTSIGNATURE 0xAA55 ``` However, when I HEXDUMP the resulting file, where it should say AA55 it says 55 AA. Is GCC Mixing up endianness, or am I? This project is for the x86 processor. AA 55 needs to be in that specific...
0xAA55is anintand so you are subject to the endianness of your machine. I would store this as a char array: ``` const unsigned char BOOTSIGNATURE[] = {0xAA, 0x55}; ```
I am trying to make an object file via "cc -c -o " but I get the following statement ,what should I do to solve this,thanks in advance ``` ~/hedor1>lex -t example.l > example.c ~/hedor1>cc -c -o example.o example.l cc: example.l: linker input file unused because linking not done ``` the first line to produce the exa...
You are passing the flex source to the compiler, which apparently interprets it as being a linker input file, and complains because you told the compiler not to do the linking step. The second command should have been: ``` cc -c -o example.o example.c ```
I have a task... 1.- I am displaying a matrix array using openGL each value is a intensity and its done. 2.- I need to refresh this windows with a new values, BUT theglutMainLoop()does not help... the code is: void graphfunct(void) ``` { /*Here print the array just once and I cannot do the second T_T*/ } ``` I...
Use GLUT timers to callglutPostRedisplay()on a schedule or put one at the end ofgraphfunct()to redraw as fast as possible.
Is there any way to extrude gluPartialDisk in OpenGL - have been looking around but cant seem to find one. If there isn't any way is there something similar I can look at.
There is no function in OpenGL to do this (note: gluPartialDisk is not an OpenGL function. It's a GLU function, which is not part of OpenGL itself). So if you want to do extrusion, you'll have to compute the vertices yourself.
is there a way to disable the storage functionality of an usb stick and autostarting a specific program when plugging it it? (so that the storage is all reserved for the program in question)
No. There is no way to do this without putting malware that cripples the host OS on the USB stick and relying on the host's OS to automatically run the malware the first time the device is inserted. This is of course frowned upon, both on Stack Overflow, and in general.
For a project I am working on I use magic numbers. This macro is used to define one ``` #define BOOTSIGNATURE 0xAA55 ``` However, when I HEXDUMP the resulting file, where it should say AA55 it says 55 AA. Is GCC Mixing up endianness, or am I? This project is for the x86 processor. AA 55 needs to be in that specific...
0xAA55is anintand so you are subject to the endianness of your machine. I would store this as a char array: ``` const unsigned char BOOTSIGNATURE[] = {0xAA, 0x55}; ```
I am trying to make an object file via "cc -c -o " but I get the following statement ,what should I do to solve this,thanks in advance ``` ~/hedor1>lex -t example.l > example.c ~/hedor1>cc -c -o example.o example.l cc: example.l: linker input file unused because linking not done ``` the first line to produce the exa...
You are passing the flex source to the compiler, which apparently interprets it as being a linker input file, and complains because you told the compiler not to do the linking step. The second command should have been: ``` cc -c -o example.o example.c ```
This is the OpenGL version I have: ``` Video Card Vendor: Intel Renderer: Intel(R) HD Graphics OpenGL Version: 2.1.0 - Build 8.15.10.2622 GLU Version: 1.2.2.0 Microsoft Corporation ``` I'd like to learn the latest OpenGL API. But my card supports only 2.1 (and I cant update). Is it poss...
AshleysBrain's answer is not quite correct. You can use a software implementation of OpenGL such asMesa3Dwhich can execute newer code using your CPU instead of your GPU. It will be slower but will allow you to compile and runyour 4+ code against itOpenGL 3.1 code against it. Edit: just checked, it seems Mesa only sup...
I'm using Visual Studio 2012 to develop simple Win32 C programs. I know that the VS compiler only supports C89, but I'd like to know if there is a way to override this limitation. In particular I'd like to declare variables anywhere in my code, instead of only at the beginning of scope blocks (as C89 requires). Than...
The choices I see: stick with MSVC and switch to C++stick with MSVC and use a precompiler that translates C99 to C90 (Comeau,c99-to-c89)switch to a toolchain that supports more recent revisions of the C language (Intel, MinGW, Clang, Pelles-C,...)
In LLVM, how can I have generate a branch instruction that jumps directly, rather than having if-else. I know there is LLVM::BranchInst class, but don't know how to use it for this purpose, or do I need to use some other class?
You need an unconditional branch: ``` static BranchInst * llvm::BranchInst::Create(BasicBlock *IfTrue, Instruction *InsertBefore = 0) static BranchInst * llvm::BranchInst::Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) ```...
Why would you do this: ``` void f(Struct** struct) { ... } ``` If I wish to operate on a list of structs, is it not enough to pass in aStruct*? This way I can dostruct++to address the next struct or am I very confused here? :) Wouldn't it only be useful if I want to rearrange the list of structs in some way? How...
It depends on what your data structure looks like. Assuming thatpis a null-terminated array of pointers tostruct s, you can run through it using a loop like this: ``` void f(struct s **p) { while (*p != NULL) { /* some stuff */ (*p)++; } } ``` Generally, use a pointer to a pointer is useful o...
For a basic block I want to change conditional jump to an unconditional jump. So if a basic block had two successors I want to remove the edge to one of the successor. I want the basic block to directly jump to one of the successor. How can I do that? To illustrate my point, I want to change ``` A / \ / \...
I think the simplest way will be just to create a new unconditional branch instruction, then replace the old one with it. So, something like: ``` #include "llvm/Transforms/Utils/BasicBlockUtils.h" BranchInst* Old = ... BranchInst* New = BranchInst::Create(Old->getSuccessor(X)); ReplaceInstWithInst(Old, New); ``` Wh...