question
stringlengths
25
894
answer
stringlengths
4
863
I noticed that on a single threaded application, SDL still spawns some threads on initialization. It's usually not of my concern by I noticed cURL requires its initialization to be done before any thread creation for thread-safety. Can they generally be ignored [for cURL initialization] or not? [Also, are they just a sign of using an external library etc.?]
grepping the source, it looks like the audio subsystem can utilize threading on most platforms, as well as the event subsystem on some platforms (mostly X11 it seems).
This is my code: ``` wchar_t wbuffer[512]; wchar_t* wc = (wchar_t*) malloc(buffer_size); int buflen = 0; // ... stuff // inside the while loop wbuffer[buflen] = (wchar_t)wc; ``` what is wrong with this?
Dereference wc within your loop. ``` wbuffer[buflen] = *wc; ```
Is there a standard C function that allows you to build strings using format specifiers? Right now I'm doing this: ``` char buffer[256]; char *name = "Fred"; strcpy(buffer, "Hello, "); strcat(buffer, name); strcat(buffer, ". How are you today?\n"); ``` Is there a way to add the message to buffer in one function? Something like this: ``` makestr(buffer, "Hello, %s. How are you today?\n", name); ```
sprintf Be careful when using it because sprintf is not a safe function and can suffer frombuffer overflows.
Sometimes I seem to get 0, which means that all I got was a header, does that mean I should assume that I received a FIN and close that socket? Thanks in advance!
Yes. Zero means, generically, end-of-file. What "end of file" means depends on what kind of file descriptor you are using. In the context of a TCP socket, the only way that I know of that you can read zero is if a FIN is received. By contrast, if a RST is receivedread()would return-1witherrno == ECONNRESET.
Is there any way to find a unique hardware ID to a computer in C? (Windows)
How exactly would you define the "computer"? The CPU? What about the same CPU in a different MoBo?The MoBo? What if it gets a new BIOS? a new CPU?The graphics card? What if the machine has more than 1 GPU? and it gets upgraded? Once you define exactly what you're asking, you'll be much closer to an answer
Or should one first look at the drivers involved (e.g. OpenGL drivers in a game) or the X server, or a kernel bug? The example case is simple, two threads may be writing the same variable at the same time. Can that trigger such a massive lock up?
Of a decent operating system, definitely not. Any threading issues should be isolated to the current process only. Assuming that process itself isn't inherently dangerous (elevated privileges, kernel mode code and so forth), it should not be able to bring the OS itself down.
Why is output of this code ``` 1234567890asdfg asdfg ``` (i can't use string class) ``` #include <stdio.h> #include <stdlib.h> #include <string.h> struct S { char a[10]; char b[20]; }; int main() { struct S* test = (S*)malloc(sizeof(S)); strcpy(test->a, "1234567890"); strcpy(test->b, "asdfg"); printf("%s\n%s", test->a, test->b); return 0; } ```
The string you've put intest->ais eleven characters long including the terminating null character:1234567890\0. When you copy it intoa, that null character ends up in the first character ofb. You then overwrite it with the string you copy intob, so that in memory you have: ``` a - - - - - - - - - b - - - - - - - - - - - - - - - - - - - 1 2 3 4 5 6 7 8 9 0 a s d f g \0 ^ | a's terminating null was here. ``` You then printa(starting from the'1'), andb(starting from the'a'), producing that output.
This question already has answers here:Closed12 years ago. Possible Duplicate:stdout thread-safe in C on Linux? Say thread1 and thread2 are similar and at the end of their jobs they both printf. Is it thread safe or do they have to lock printf somehow? Is it related to stdout? What if one does fflush(stdout) after each printf? Does it change anything?
The POSIX.1 and C-language functions that operate on character streams (represented by pointers to objects of type FILE) are required by POSIX.1c to be implemented in such a way that reentrancy is achieved (see ISO/IEC 9945:1-1996, §8.2). refer toThread-safety and POSIX.1 Note: Some functions can be reentrant or non-reentrant, depending on their arguments.
This might be very basic or even silly to experts here but I wanted to get my head around this. Most of the times I generally write hex values like this in C: ``` unsigned int a = 0xFFFF1232; ``` Let's say I am trying to extract the first and last 16-bits then I can simply do: ``` unsigned short high = a >> 16; // Gives me 0xFFFF unsigned short low = a & 0x0000FFFF; // Gives me 0x00001232 which is then stored as 0x1232 ``` In some of the code I am reading I have come across the following: ``` unsigned short high = a >> 16; unsigned short low = a & 0xFFFF; ``` I have two questions When you areANDing a 32-bit value with a mask, why do people write0xFFFFinstead of0x0000FFFF? Is it to keep it compact?Is it always safe to write0x0000FFFFas0xFFFF? Is it interpreted differently in any context?
They're completely synonymous. Leaving out the leading zeros makes it a little more readable.
In a CUDA program, I recently switched from testing for inifinity using ``` return x==INFINITY || x==-INFINITY; ``` whereINFINITYis from math.h, to ``` return !isfinite(x); ``` and was quite surprised to get different results.gnu.orgsuggests that they actually should behave similarly. Am I missing something? Is it not allowed to useINFINITYin a CUDA kernel? Edit:I just discoveredisinfand noticed that checking using ``` return isinf(x); ``` gives the same result as the INFINITY check. Why isn'tisfinite(x)==!isinf(x)?
isfinite(a)is the same as!isnan(a) && !isinf(a). Ifxis NaN, then bothisfinite(x)andisinf(x)are false.
is there a easy way to form a long long variable from 8 consecutive bytes.... ``` TotalSectors = sector[0x28]| sector[0x28+1] << 8 | sector[0x28+2] << 16 | sector[0x28+3] << 24 | sector[0x28+4] << 32 | sector[0x28+5] << 40 | sector[0x28+6] << 48 | sector[0x28+7] << 56; ``` Where TotalSectors is a long long variable.... I am working on windows platform and win32 api is my main choice..... any existing macro for this work would be helpful.... Thanks in advance...
Endianness is good. So just cast: ``` TotalSectors = *(long long*)&sector[0x28]; ```
Update turns out this is just another case of "c++ is not c blues" What I want ``` const char hex[16] = "0123456789ABCDEF"; ``` the only thing that works ``` char hex[16] = "0123456789ABCDE"; hex[15] = "F"; ``` are there any compiler options or something I can do to make strings not null terminated in the gcc compiler. so that I can make a(n) constant array
No need for a compiler option, it'salreadynon-NUL terminated. The standard says a NUL should only be added if it can fit, otherwise it would be an overflow. It may just be that the next byte in memory past your array is\0 § 6.7.8p14An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is roomor if the array is of unknown size) initialize the elements of the array.
I am having a problem with QDevelop version 0.27. When I debug the location pointer jumps around without the IDE following it and showing me where it went. I have to manually click through the source file tabs to find where it went sometimes scrolling up and down through the code to find where it is. Once I get to one point I can no longer find where it sent. At one point in debugging the location pointer jumps to a location and there is a split in the IDE windowed area and I see the pointer but it's like two different files are merging graphically. Very weird issue.
Uhh well mysteriously the issue just up and disappeared without me doing a single thing.
I need to modify trackers in torrent files using C, What type of encoding do they use?? When I just print characters in ascii they print gibberish. Or is there a direct way of adding trackers to a torrent file using C?
Have you tried documenting yourself regarding .torrent file format ? TheWikipedia articleseems to be pretty complete on this question.
I am reusing a legacy C library in an iOS app and in an Android app. I want to customize some macro definitions (e.g. for logging). Are there standard defines to check for (using #ifdef) whether the code is being compiled for iOS or Android/NDK?
__ANDROID__orANDROIDfor Android (compilation with the NDK) and__APPLE__on Apple platforms (iOS or OSX)
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question I was thinking about writing a program to automatically change the gear of my bike. It may require a microprocessor, so the question which I had in my mind was: is there any different language for programming a microprocessor or can this be done using C and C++? Another thing is, regarding the program, can aswitchstatement do my work or do I need a pointer or linked list because the gear works both ways, up and down? I was a bit confused with theswitchstatement thing!
You don't need the switch statement, just use the shift operator: Shift up: gear <<= 1; Shift down: gear >>= 1;
I'm desperately looking for some C sample source code that describes how to implement a HID client using Bluez. More specifically, I would like to know how to write an application that sends keyboard inputs over bluetooth to another Linux system. (Really, the fact that the receiver is running Linux/Bluez shouldn't matter.) -Cheers
hidclienthttp://anselm.hoffmeister.be/computer/hidclient/index.html.en?
I was taking a look at the Quake 1 GPL Code and I came across various similar header files, the purpose or use of which I don't seem to understand. They look like tables of some sorts and are structured like this ``` {1, 0}, {1, -1}, {1, -2}, {1, -3}, {1, -4}, {1, -5},[...] ``` Without anything before or after them. I understand they define something but I've never come across this kind of notation in C. You can read one of the header files I'm referring tohere. My question is: what are those...things? The ASM is actually giving me less problems than that stuff.
These are probably multi-use includes. They can be used like so: ``` struct {int y; int y;} points[] = { #include <points.inl> }; ```
I am trying to write this code, but it gives me segmentation fault after running the program, could you please help to sort it out? ``` #include <stdio.h> #include <string.h> typedef struct{ int salary; char* name; } employee ; int main(){ employee p[2]; int i; for(i=0;i<2; i++){ printf("enter sal "); scanf("%d", &p[i].salary); printf("enter name "); scanf("%s", &p[i].name); } for(i=0;i<2; i++){ printf("p %d",p[i].salary); printf("p %s",p[i].name); } return 0; } ```
You need to allocate memory for the name field:p[i].name = (char*)malloc(MAX_NAME_LEN)Also, thescanf("%s", &p[i].name)should readscanf("%s", p[i].name).
I am writing a RFID device driver and encounter an compiling error below: ``` [root@localhost kernel]# make modules CHK include/linux/version.h make[1]: `arch/arm/kernel/asm-offsets.s' is up to date. make[1]: `include/asm-arm/mach-types.h' is up to date. CC [M] drivers/char/gpio_led.o CC [M] drivers/char/rf531_drv.o drivers/char/rf531_drv.c:35: error: parse error before "Ioff_t" drivers/char/rf531_drv.c:35: warning: function declaration isn't a prototype drivers/char/rf531_drv.c:36: error: parse error before "Ioff_t" drivers/char/rf531_drv.c:36: warning: function declaration isn't a prototype ``` Then I find the type Ioff_t is defined in $(srctree)/include/linux/types.h,so I added the #include header to the source code rf531_drv.c,but the error still there.Anyone had encountered this kind of problem? Could you give some suggestions and help?
That'sloff_twith a lowercase "L", notIoff_t.
Good day! I need to use malloc in creating a student list system.... In order to be efficient, our professor asked us to use it on a struct so i created a struct as follows: ``` struct student { char studentID[6]; char name[31]; char course [6]; }; struct student *array[30]; ``` everytime i add a record, that is when i use malloc... ``` array[recordCtr]=(struct student*)malloc(sizeof(struct student)); recordCtr++; ``` then i free it like this. ``` for(i = 0; i < recordCtr; i++){ free(array[i]); } ``` Am i using malloc properly??? what is the effect if i free it like this instead of the loop above. ``` free(array); ``` Thanks in advance. Your opinion will be highly appreciated.
You are doing fine. free(array);would be undefined behavior becausearrayitself was not allocated viamalloctherefore you can'tfreeit and don't need to - the memory will be managed by the compiler.
I've the following code: ``` void funcA(void* pArg) { STRUCTA abc; . . // Some processing here . if (pArg) (STRUCTA *)pArg = abc; } ``` the problem is, this code is throwing up the following warning: warning: target of assignment not really an lvalue; this will be a hard error in the future Without the cast, I'll get another warning that I'm trying to dereference a void pointer... As warnings are being treated as errors, I can't use this code - But I really can't use any other pointer type than void* as the argument. Is there an elegant solution I'm missing? Is there any way to make this work?
(STRUCTA *)pArgis of pointer type, whileabcisn't. You need to dereference the pointer: ``` *(STRUCTA *)pArg = abc; ```
How can I execute shell from a C code? My shell is placed in/bin/sh Following didn't seem to work for me ``` system("/bin/sh"); exec("/bin/sh"); ```
Maybe you need to tell the shell it should be interactive: ``` system("/bin/sh -i"); ``` However, I believe that your originalsystem()call should have produced a shell prompt too. Both notations (with and without the '-i') in this program give me a shell prompt (return to the previous shell by typing 'exit' andRETURNorControl-D): ``` #include <stdlib.h> int main(void) { system("/bin/sh -i"); return 0; } ```
I am looking for a way to code a program which will multiply an integer to an exponent using only a recursion loop. I have a very limited understanding of recursion, but have been able to code something to give a factorial: ``` int fac2(int n) { if (n == 1){ return 1; } else { return n*fac2(n-1); } } ``` I have a way to find a power already, but it uses aforloop: ``` int my_power(int x, int e) { int i, total; total = 1; for (i = 1; i <= e; i++){ total *= x; } return total; } ``` How can I replace this for loop using recursion?
``` int my_power (int x, int e) { if (e == 0) return 1; return x * my_power(x, e-1); } ```
I'm searching for theomp.hfile for using it in eclipse. I failed to find it in openmp.org. Where do I findomp.h? thanks.
Under Linux, you can find a file by ``` locate omp.h ``` Have you tried to simply use it with ``` #include <omp.h> ``` and add the openmp flag to your g++ compiler flag? ``` g++ -fopenmp sample.c ```
I was wondering if the WinAPI or something has a way to get the raw data from a USB device, or something that would lead me in the right direction for this sort of thing. for example, for an midi device, this data might be the velocity, and which note was hit. Thanks
Not directly but you can now useusblibon windows
I am writing an command line application in C and from within the program, I would like to call other command-line applications. For example (and only as a clear example!), say the I would like to write a C app that calls the java compiler. For one, how would I do this? Is there a C function that directly calls the command line of something? For two, how would I take the normal text output that the java compiler displays and display it through the c program? I'm sorry if this sounds a bit crazy, but I am very new to C and I have never done anything like this before. I would love to start writing a few of these utility style apps. If it matters any, I am currently running Windows, but would prefer a platform-independent method if possible, as I do use Linux from time to time.
You might look intosystem. I think you can use it in Windows as well as UNIX/Linux systems.
I need to modify trackers in torrent files using C, What type of encoding do they use?? When I just print characters in ascii they print gibberish. Or is there a direct way of adding trackers to a torrent file using C?
Have you tried documenting yourself regarding .torrent file format ? TheWikipedia articleseems to be pretty complete on this question.
I am reusing a legacy C library in an iOS app and in an Android app. I want to customize some macro definitions (e.g. for logging). Are there standard defines to check for (using #ifdef) whether the code is being compiled for iOS or Android/NDK?
__ANDROID__orANDROIDfor Android (compilation with the NDK) and__APPLE__on Apple platforms (iOS or OSX)
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed2 years ago.Improve this question I was thinking about writing a program to automatically change the gear of my bike. It may require a microprocessor, so the question which I had in my mind was: is there any different language for programming a microprocessor or can this be done using C and C++? Another thing is, regarding the program, can aswitchstatement do my work or do I need a pointer or linked list because the gear works both ways, up and down? I was a bit confused with theswitchstatement thing!
You don't need the switch statement, just use the shift operator: Shift up: gear <<= 1; Shift down: gear >>= 1;
I'm desperately looking for some C sample source code that describes how to implement a HID client using Bluez. More specifically, I would like to know how to write an application that sends keyboard inputs over bluetooth to another Linux system. (Really, the fact that the receiver is running Linux/Bluez shouldn't matter.) -Cheers
hidclienthttp://anselm.hoffmeister.be/computer/hidclient/index.html.en?
I was taking a look at the Quake 1 GPL Code and I came across various similar header files, the purpose or use of which I don't seem to understand. They look like tables of some sorts and are structured like this ``` {1, 0}, {1, -1}, {1, -2}, {1, -3}, {1, -4}, {1, -5},[...] ``` Without anything before or after them. I understand they define something but I've never come across this kind of notation in C. You can read one of the header files I'm referring tohere. My question is: what are those...things? The ASM is actually giving me less problems than that stuff.
These are probably multi-use includes. They can be used like so: ``` struct {int y; int y;} points[] = { #include <points.inl> }; ```
I am trying to write this code, but it gives me segmentation fault after running the program, could you please help to sort it out? ``` #include <stdio.h> #include <string.h> typedef struct{ int salary; char* name; } employee ; int main(){ employee p[2]; int i; for(i=0;i<2; i++){ printf("enter sal "); scanf("%d", &p[i].salary); printf("enter name "); scanf("%s", &p[i].name); } for(i=0;i<2; i++){ printf("p %d",p[i].salary); printf("p %s",p[i].name); } return 0; } ```
You need to allocate memory for the name field:p[i].name = (char*)malloc(MAX_NAME_LEN)Also, thescanf("%s", &p[i].name)should readscanf("%s", p[i].name).
I am writing a RFID device driver and encounter an compiling error below: ``` [root@localhost kernel]# make modules CHK include/linux/version.h make[1]: `arch/arm/kernel/asm-offsets.s' is up to date. make[1]: `include/asm-arm/mach-types.h' is up to date. CC [M] drivers/char/gpio_led.o CC [M] drivers/char/rf531_drv.o drivers/char/rf531_drv.c:35: error: parse error before "Ioff_t" drivers/char/rf531_drv.c:35: warning: function declaration isn't a prototype drivers/char/rf531_drv.c:36: error: parse error before "Ioff_t" drivers/char/rf531_drv.c:36: warning: function declaration isn't a prototype ``` Then I find the type Ioff_t is defined in $(srctree)/include/linux/types.h,so I added the #include header to the source code rf531_drv.c,but the error still there.Anyone had encountered this kind of problem? Could you give some suggestions and help?
That'sloff_twith a lowercase "L", notIoff_t.
Good day! I need to use malloc in creating a student list system.... In order to be efficient, our professor asked us to use it on a struct so i created a struct as follows: ``` struct student { char studentID[6]; char name[31]; char course [6]; }; struct student *array[30]; ``` everytime i add a record, that is when i use malloc... ``` array[recordCtr]=(struct student*)malloc(sizeof(struct student)); recordCtr++; ``` then i free it like this. ``` for(i = 0; i < recordCtr; i++){ free(array[i]); } ``` Am i using malloc properly??? what is the effect if i free it like this instead of the loop above. ``` free(array); ``` Thanks in advance. Your opinion will be highly appreciated.
You are doing fine. free(array);would be undefined behavior becausearrayitself was not allocated viamalloctherefore you can'tfreeit and don't need to - the memory will be managed by the compiler.
I've the following code: ``` void funcA(void* pArg) { STRUCTA abc; . . // Some processing here . if (pArg) (STRUCTA *)pArg = abc; } ``` the problem is, this code is throwing up the following warning: warning: target of assignment not really an lvalue; this will be a hard error in the future Without the cast, I'll get another warning that I'm trying to dereference a void pointer... As warnings are being treated as errors, I can't use this code - But I really can't use any other pointer type than void* as the argument. Is there an elegant solution I'm missing? Is there any way to make this work?
(STRUCTA *)pArgis of pointer type, whileabcisn't. You need to dereference the pointer: ``` *(STRUCTA *)pArg = abc; ```
How can I execute shell from a C code? My shell is placed in/bin/sh Following didn't seem to work for me ``` system("/bin/sh"); exec("/bin/sh"); ```
Maybe you need to tell the shell it should be interactive: ``` system("/bin/sh -i"); ``` However, I believe that your originalsystem()call should have produced a shell prompt too. Both notations (with and without the '-i') in this program give me a shell prompt (return to the previous shell by typing 'exit' andRETURNorControl-D): ``` #include <stdlib.h> int main(void) { system("/bin/sh -i"); return 0; } ```
I am looking for a way to code a program which will multiply an integer to an exponent using only a recursion loop. I have a very limited understanding of recursion, but have been able to code something to give a factorial: ``` int fac2(int n) { if (n == 1){ return 1; } else { return n*fac2(n-1); } } ``` I have a way to find a power already, but it uses aforloop: ``` int my_power(int x, int e) { int i, total; total = 1; for (i = 1; i <= e; i++){ total *= x; } return total; } ``` How can I replace this for loop using recursion?
``` int my_power (int x, int e) { if (e == 0) return 1; return x * my_power(x, e-1); } ```
I'm searching for theomp.hfile for using it in eclipse. I failed to find it in openmp.org. Where do I findomp.h? thanks.
Under Linux, you can find a file by ``` locate omp.h ``` Have you tried to simply use it with ``` #include <omp.h> ``` and add the openmp flag to your g++ compiler flag? ``` g++ -fopenmp sample.c ```
I was wondering if the WinAPI or something has a way to get the raw data from a USB device, or something that would lead me in the right direction for this sort of thing. for example, for an midi device, this data might be the velocity, and which note was hit. Thanks
Not directly but you can now useusblibon windows
I am writing an command line application in C and from within the program, I would like to call other command-line applications. For example (and only as a clear example!), say the I would like to write a C app that calls the java compiler. For one, how would I do this? Is there a C function that directly calls the command line of something? For two, how would I take the normal text output that the java compiler displays and display it through the c program? I'm sorry if this sounds a bit crazy, but I am very new to C and I have never done anything like this before. I would love to start writing a few of these utility style apps. If it matters any, I am currently running Windows, but would prefer a platform-independent method if possible, as I do use Linux from time to time.
You might look intosystem. I think you can use it in Windows as well as UNIX/Linux systems.
I have a program written in C that operates similar to the below output. ``` WELCOME TO PROGRAM. Hit 1 to do task 1. Hit 2 to do task 2. Hit q to quit. ``` What i need is a bash shell script that start the program, then enters 1, 2 and q into the program so i can test all the functionality in one command. I would assume it to look similar to the following ``` #!/bin/bash ./start kernel 1 2 q ```
You can use a "here document" . The syntax looks like this: ``` ./start kernel <<EOF 1 2 q EOF ``` "EOF" can be whatever unique word you want, as long as it isn't something you'll actually need in the input.
I may have missed something but I see here on header files all kinds of functions to move text around in C++ but not on the C API. How is it done? EDIT: Pixmap fonts for example.
TryglTranslatef()orglRasterPos2f(). Also, what documentation are you looking at?I'm not seeing any positioning functionality.
Having an untyped pointer pointing to some buffer which can hold either ANSI or Unicode string, how do I tell whether the current string it holds is multibyte or not?
Unless the string itself contains information about its format (e.g. a header ora byte order mark) then there is no foolproof way to detect if a string is ANSI or Unicode. The Windows API includes a function calledIsTextUnicode()that basically guesses if a string is ANSI or Unicode, butthen you run into this problembecause you'reforced to guess. Why do you have an untyped pointer to a string in the first place? You must know exactly what and how your data is representing information, either by using a typed pointer in the first place or provide an ANSI/Unicode flag or something. A string of bytes is meaningless unless you know exactly what it represents.
I have two C files. I want to declare a variable in one, then be able to access it from another C file. My definition of theexamplestring might not be perfect, but you get the idea. ``` //file1.c char *hello="hello"; ``` ``` //file2.c printf("%s",hello); ```
``` // file1.h #ifndef FILE1_H #define FILE1_H extern char* hello; #endif // file1.c // as before // file2.c #include "file1.h" // the rest as before ```
If I have ``` char input[50] = "xFFFF"; int a; ``` How can I store the numerical value of input in a? the language is C.
One way to do it might be: ``` if (sscanf(input, "x%x", &a) == 0) { /* matching failed */ } ``` If your input uses a real hex specifier (like "0xFFFF") you can just use %i: ``` if (sscanf(input, "%i", &a) == 0) { /* matching failed */ } ```
total newbie here. i was trying to replace a character in char * but my program gives error ``` #include <stdio.h> int main(int argc, char **argv) { char *mystring ="love is alweys better yoe"; int count = 1; for (count ; count < 23; count++) { if ((mystring[count] == 0x65 )) //&& ((mystring[count+1] > 0x41) && (mystring[count+1] < 0x7A))) { mystring[count] = 0x45; //here occur the freezing printf ("%c\n", mystring[count]); //break; }; }; printf("%s\n",mystring); return 0; } ```
The ``` char *mystring ="love is alweys better yoe" ``` makes mystring read-only you need to copy the string into a buffer before you can change it e.g. ``` char mystring[128]; strcpy( mystring , "love is alweys better yoe" ); ```
I want to print a string backwards. But my code seems to count down the alphabet from the last letter in the array to the first letter in the array instead of counting down the array itself and spitting out each letter in the array. My code, ``` #include <stdio.h> #include <string.h> int main(void) { char word[50]; char end; char x; printf("Enter a word and I'll give it to you backwards: "); scanf("%s", word); end = strlen(word) - 1; for (x = word[end]; x >= word[0]; x--) { printf("%c", x); } return 0; } ``` Any suggestions? Thank you.
What you have loops between the array element values. You want to loop between the array indexes. Update your loop to the following: ``` for (x = end; x >= 0; --x) { printf("%c", word[x]); } ``` Note that this goes from the last index to zero and output the character at that index. Also a micro-optimization in the for loop using pre-decrement.
What is the best way to keep unacknowledged data buffer (sender's buffer) in TCP? I am thinking between keeping data itself, and keeping packets(header + data)? It seems retransmission of packets would be hard if I keep just data bytes as opposed to keeping packets. Language: C
Packet boundaries are meaningless in TCP: it's possible for half of a packet's data to be acknowledged (say due to fragmentation) and then you would have to retransmit the remaining half. So the answer is: you should keep raw data, not packets. The real question you should be asking is: how do I know what data has been acknowledged. You need a bit-mask for each byte of data in your window, and you could mark acknowledged data as 1 and the rest as 0. Whenever you find that a contiguous block of data from the beginning of your window has been acknowledged, that portion can be slid out.
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 help centerfor guidance.Closed12 years ago. Which is more clear to someone reading code? "long" or "long int". "long int" is more descriptive, but "long" is more succinct.
"Long int" is more descriptive, but "long" is more succinct.
I have a following sturcture for creating linked list, how can I free the allocated memeory? ``` typedef struct linked_list { struct linkedl_ist *number; POINTER house; } list; typedef list *LIST; typedef void pointer ``` i have following list ``` LIST l1; l1 = some_function(pointer); ``` Thesel1is constructed using some variables. This is a linked list data structure as i mentioned. How can I free the memory allocated forl1? [EDIT] l1holds a memory of 8 byte.
l1doesn't need to be freed. It's on the stack. Return from the function you're in and it will automatically go away. The way to free whatl1points to is the same as the way to free the rest of the elements of the list: walk the list (using->number) and free each element as you go. ``` LIST node = l1; LIST next; while (node != NULL) { next = node->number; free(node); node = next; } ```
When i run the above program in gcc complier(www.codepad.org) i get the output as Disallowed system call: SYS_socketcall Could anyone please clear why this error/output comes? ``` int main() { int i=8; int *p=&i; printf("\n%d",*p); *++p=2; printf("\n%d",i); printf("\n%d",*p); printf("\n%d",*(&i+1)); return 0; } ``` what i have observed is i becomes inaccessible after i execute *++p=2;WHY?
When you do*p = &i, you makeppoint to the single integeri.++pincrementspto point to the "next" integer, but sinceiis not an array, the result is undefined.
This question already has answers here:Closed12 years ago. Possible Duplicate:C programming : How does free know how much to free? In this snippet ``` void main() { void *p = malloc(300); printf("%d",sizeof(*p)); free(p); } ``` How does free know much memory it is supposed release from the void pointer? I figure, if there is an internal table/function, it should be available to find out sizes of any kind of objects, whereas the output of theprintfis1
malloc and free do their own hidden accounting so they can do the correct thing. The reason the sizeof() does not use this accounting information is that sizeof() is a compile time operator, and the malloc/free information is not available until runtime.
I want to create a function in C programming, which will test for the embedded spaces in C. if it found embedded spaces in a string it will return 1 else 0 examples: ``` 'sjdfnsdj' >>>>> return 0 'sdsd sdsdf' >>>>> return 1 ' ssadsa' >>> return 0 'dfjksdnf sdfsdfdf' >>>> return 1 ' sadf asdad' >>>> return 1 ``` Embedded spaces means spaces between two strings or after the string but NOT before a string
You could usestrchrto scan the string for a space character after you you skipped leading spaces. Assuming char buf[] holds the string to test ``` int i=0; while ( buf[i] == ' ' && buf[i] != '\0' ) i++; return strchr( &buf[i], ' ' ) != NULL; ``` EDIT: The post has been retagged with homework. Instead of using strchr you can also do another loop like the one to skip the leading spaces. To find out whether there are further spaces after the first non space char.
How can I set a breakpoint in C or C++ code programatically that will work for gdb on Linux? I.e.: ``` int main(int argc, char** argv) { /* set breakpoint here! */ int a = 3; a++; /* In gdb> print a; expect result to be 3 */ return 0; } ```
One way is to signal an interrupt: ``` #include <csignal> // Generate an interrupt std::raise(SIGINT); ``` In C: ``` #include <signal.h> raise(SIGINT); ``` UPDATE:Microsoft Docssays that Windows doesn't really supportSIGINT, so if portability is a concern, you're probably better off usingSIGABRT. SIGINT is not supported for any Win32 application. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application, such as one in UNIX, to become multithreaded and cause unexpected behavior.
An attempt to change the linkage of a nameiis made in this code. Is it legal in C/C++? ``` static int i = 2; int i; int main() { return 0; } ```
In C++ your code is ill-formed (you have multipledefinitionsof variablei) i.e a standard conformant compiler is required to issue an error message $3.2.1 (C++03) No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template. In C99 your code invokes Undefined Behaviour because 6.2.2/7 says If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior isundefined.
When you have aGtkButtonin GTK and it is thedefaultfor some window (will be activated when you press Enter), a tiny border is draw around it to inform the user that the button is the default button. How to remove this border ? I already tried:default-borderanddefault-outside-borderstyle properties.
After hours finding for this, I've discovered it: ``` gtk_button_set_relief(GTK_BUTTON(button_widget), GTK_RELIEF_HALF); ``` GTK should have a gallery showing how this changes the button behavior.
I'm wondering how multiple pointers should/could be handled by a high level application. I'm mostly interested about how MPX (Multi Pointer X - for Xorg) works. What GUI libraries support it? It seems like latest versions of Qt and GTK should support it, but cannot find any demo, tutorial or documentation.
Experimental support for MPX in GTK+ can be foundhere. Since that's a work in progress, documentation is very scarce but still might get you started. There's documentation about MPX itselfhere. Note that existing applications using only one pointer will be able to run unchanged on an MPX-aware server. If you want your app to take advantage of multiple pointers, you'll need to callgdk_enable_multidevice()beforegtk_init()and handle per-device enter/leave events and grabs.
I have a c program with say n number of for loops. How many processes and child processes will be running for this program and how?
A for loop does not fork a new process. N number of for loop should run in a single process.
While reading some random code, I happen to encounter aprintf()expression which is a bit strange to me, the statement is like this ``` void PrintDiceFace(int n){ printf("%d 0 %d\n%d %d %3$d\n%2$d 0 %1$d\n\n",n>50,51%n%2,n>53,n%2); } ``` This is actually obfuscated version of snippet which actually prints the face of the electronicdice. Forexample. Please explain thisprintf()statement in detail. http://en.wikipedia.org/wiki/Dice
POSIX/SUSprintf()allows a number followed by$after the%in order to indicate that a specific argument from the varargs should be picked. ``` printf("%2$s, %1$s!\n", "world", "Hello"); ```
I have to call a c function declared in a lib file from c++. What instructions/attributes/configuration I have to set for this?
Do you have a header file for the library? If so it should have ``` extern "C" { blah blah } ``` stuff in it to allow it to be used by C programs. If not, then you can put that around the include statement for the header in your own code. E.g. ``` extern "C" { #include "imported_c_library.h" } ```
Is there any analog of PHP's system in C? man systemsays, thatsystemreturn status of the command, but I need the output (like in PHP). Of course, I can use pipes for this, but is there any standard way?
You can make use ofpopenand related function as: ``` // command to be run. char *cmd = "date"; // open pipe stream. FILE *fp = popen(cmd,"r"); int ch; // error checking. if(!fp) { fprintf(stderr,"Error popen with %s\n",cmd); exit(1); } // read from the process and print. while((ch = fgetc(fp)) != EOF) { putchar(ch); } // close the stream. pclose(fp); ``` Ideone link
Simple Question. Imagine this in ANSI-C: ``` int i; for(i=0 ; i<5 ; i++){ //Something... } printf("i is %d\n", i); ``` Will this output "i is 5" ? Isipreserved or is the value ofiundefined after the loop?
Yes. If i is declared outside of the for loop it remains in scope after the loop exits. It retains whatever value it had at the point the loop exited. If you declatred I in the loop: ``` for (int i = 0 ; i < 5 ; i++) { } ``` Then i is undefined after the loop exit.
i am using gdb command "attach" to debug a proceess but after the process crash (sigkill) i can not see the stack trace ("bt" command in gdb) : (gdb) bt No stack. how can i see the stack trace after the process is killed?
Set your shell to dump core by making sureulimit -cdoesn't show a core size of 0. If it does say 0 then runulimit -c unlimited. Next, re-run your program until it crashes and dumps core then call: gdb /path/to/executable /path/to/coreand typebtto get the stack trace. Also, you'll want to compile your executable with debugging info turned on. If you're usinggccthen I would suggest you use-ggdb3to do this.
My C++ compiler complains when i try to initialize a int member variable in class definition. It tells "only static const integral data members can be initialized within a class". Can you please explain the rationale behind this restriction (if possible with example).
Because it's not allowed in the current standard.According to Bjarne, you will be able to do this in C++0x. If you really need it, try setting the compiler to C++0x (-std=c++0xin GCC) and see if your compiler supports it.
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 help centerfor guidance.Closed11 years ago. In the internet there are databases(mysql, oracle etc.) where I can send the informations submitted by the HTML input fields with PHP or any other server side language. How is this working in C/C++? How can I let a user input something and them save the inputted value?
You can either: Make use of the standard file handlingfunctions/classes.Embed atiny database.Talk to a database server usinga standard interface. BTW, these are common for all languages.
I have a char * array like ``` char *options[n] ; // n = 2 just for example . options[0] = "How to"; options[1] = "Send"; ``` How do I send "options" from server to client , using just one function call like send. Since the prototype of send is like thisint send(int sockfd, const void *msg, int len, int flags);andreceive is int recv(int sockfd, void *buf, int len, int flags);I am not sure how to cast "options" such that send and receive can take place in one function call.
You have to send the actual character strings. The pointers are memory addresses on you machine and are only accesable/meanaingful inside your program. Even if the client and server were on the same machine the OS would block any attempt to access the client programs memory.
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.Closed12 years ago. In the internet there is CSS, how is this working in C, and C++? For example how can I create ared box with 200px width and height?
There is nothing in the ISO standards for these languages to deliver this sort of functionality. The I/O model is a pretty basic text-only one. Platformssuch as Windows or X or Gnome or KDE will generally provide this sort of functionality as part of their libraries since that's what they're meant for.
I have some code that uses gcc intrinsics. I would like to include code in case the intrinsic is missing. How can I do this? ``` #ifdef __builtin_ctzll ``` does not work.
With recent versions of clang it is now possible to check if builtin intrinsics exist using the__has_builtin()macro e.g. ``` int popcount(int x) { #if __has_builtin(__builtin_popcount) return __builtin_popcount(x); #else int count = 0; for (; x != 0; x &= x - 1) count++; return count; #endif } ``` Let's hope GCC will also support__has_builtin()in the future.
I know my way around ruby pretty well and am teaching myself C starting with a few toy programs. This one is just to calculate the average of a string of numbers I enter as an argument. ``` #include <stdio.h> #include <string.h> main(int argc, char *argv[]) { char *token; int sum = 0; int count = 0; token = strtok(argv[1],","); while (token != NULL) { count++; sum += (int)*token; token = strtok(NULL, ","); } printf("Avg: %d", sum/count); printf("\n"); return 0; } ``` The output is: ``` mike@sleepycat:~/projects/cee$ ./avg 1,1 Avg: 49 ``` Which clearly needs some adjustment. Any improvements and an explanation would be appreciated.
Look forsscanforatoias functions to convert from a string (array of characters) to an integer. Unlike higher-level languages, C doesn't automatically convert between string and integral/real data types.
I need to intake a number like: 200939915 After doing this, which I know how, I need to remove the first number so it becomes: 00939915 What is the best way to do this?
``` char *c = "200939915"; char *d = c + 1; ```
Ok, so for a program I need to know two facts, the length of input and which highest number this length is closest to that is divisible by 4. For example. If the length is 1, I want to record 4. If the length is 3, I want to record 4. If the length is 5, I want to record 8. Mathematically I can divide the length by 4, this gives a decimal. If I round it up and times by 4 it gives me the answer I need. So, how do I get C to round up the contents of an int? I may be overcomplicating this so please say if I have missed something simple to do this. Edit: I should add, I already know the length, this is something I would enter myself.
(length+3)/4*4
i couldnt make my program sleep() after using kill(pid,SIGTERM) what can i do ? The code i'm using: ``` kill(PID_of_Process_to_be_killed,SIGTERM); sleep(5); --> this is not working sleep(5); --> this is working ``` the solution for now is: ``` kill(PID_of_Process_to_be_killed,SIGTERM); sleep(sleep(5)); ``` but why the first sleep after kill return 0 ?
Yoursleep()call may be terminating early due to receiving a signal. Check the return value. If it's positive, you might want tosleep()again on that value. Fromhttp://www.manpagez.com/man/3/Sleep/: If the sleep() function returns because the requested time has elapsed, the value returned will be zero.If the sleep() function returns due to the delivery of a signal, the value returned will be the unslept amount (the requested time minus the time actually slept) in seconds
well i'm using while loop: while(fgets(pclientRow, 1024 , f) != NULL) in other classes it works ok, but in one of them, when i'm reading from file line by line, it won't get out of the loop even when the lines end, i saw that in the debugger. why is it? and it was working even in that class before and now i dont know why it keep bringing empty lines untill it's crshing.. any idea?
fgets in a standard ANSI C function, see documentation: Here fgets read max. 1023 character up to next '\n' or EOF. Your lines are longer than 1023 character or the last line has no terminating newline.
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 help centerfor guidance.Closed11 years ago. In the internet there are databases(mysql, oracle etc.) where I can send the informations submitted by the HTML input fields with PHP or any other server side language. How is this working in C/C++? How can I let a user input something and them save the inputted value?
You can either: Make use of the standard file handlingfunctions/classes.Embed atiny database.Talk to a database server usinga standard interface. BTW, these are common for all languages.
I have a char * array like ``` char *options[n] ; // n = 2 just for example . options[0] = "How to"; options[1] = "Send"; ``` How do I send "options" from server to client , using just one function call like send. Since the prototype of send is like thisint send(int sockfd, const void *msg, int len, int flags);andreceive is int recv(int sockfd, void *buf, int len, int flags);I am not sure how to cast "options" such that send and receive can take place in one function call.
You have to send the actual character strings. The pointers are memory addresses on you machine and are only accesable/meanaingful inside your program. Even if the client and server were on the same machine the OS would block any attempt to access the client programs memory.
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.Closed12 years ago. In the internet there is CSS, how is this working in C, and C++? For example how can I create ared box with 200px width and height?
There is nothing in the ISO standards for these languages to deliver this sort of functionality. The I/O model is a pretty basic text-only one. Platformssuch as Windows or X or Gnome or KDE will generally provide this sort of functionality as part of their libraries since that's what they're meant for.
I have some code that uses gcc intrinsics. I would like to include code in case the intrinsic is missing. How can I do this? ``` #ifdef __builtin_ctzll ``` does not work.
With recent versions of clang it is now possible to check if builtin intrinsics exist using the__has_builtin()macro e.g. ``` int popcount(int x) { #if __has_builtin(__builtin_popcount) return __builtin_popcount(x); #else int count = 0; for (; x != 0; x &= x - 1) count++; return count; #endif } ``` Let's hope GCC will also support__has_builtin()in the future.
I know my way around ruby pretty well and am teaching myself C starting with a few toy programs. This one is just to calculate the average of a string of numbers I enter as an argument. ``` #include <stdio.h> #include <string.h> main(int argc, char *argv[]) { char *token; int sum = 0; int count = 0; token = strtok(argv[1],","); while (token != NULL) { count++; sum += (int)*token; token = strtok(NULL, ","); } printf("Avg: %d", sum/count); printf("\n"); return 0; } ``` The output is: ``` mike@sleepycat:~/projects/cee$ ./avg 1,1 Avg: 49 ``` Which clearly needs some adjustment. Any improvements and an explanation would be appreciated.
Look forsscanforatoias functions to convert from a string (array of characters) to an integer. Unlike higher-level languages, C doesn't automatically convert between string and integral/real data types.
I need to intake a number like: 200939915 After doing this, which I know how, I need to remove the first number so it becomes: 00939915 What is the best way to do this?
``` char *c = "200939915"; char *d = c + 1; ```
Ok, so for a program I need to know two facts, the length of input and which highest number this length is closest to that is divisible by 4. For example. If the length is 1, I want to record 4. If the length is 3, I want to record 4. If the length is 5, I want to record 8. Mathematically I can divide the length by 4, this gives a decimal. If I round it up and times by 4 it gives me the answer I need. So, how do I get C to round up the contents of an int? I may be overcomplicating this so please say if I have missed something simple to do this. Edit: I should add, I already know the length, this is something I would enter myself.
(length+3)/4*4
i couldnt make my program sleep() after using kill(pid,SIGTERM) what can i do ? The code i'm using: ``` kill(PID_of_Process_to_be_killed,SIGTERM); sleep(5); --> this is not working sleep(5); --> this is working ``` the solution for now is: ``` kill(PID_of_Process_to_be_killed,SIGTERM); sleep(sleep(5)); ``` but why the first sleep after kill return 0 ?
Yoursleep()call may be terminating early due to receiving a signal. Check the return value. If it's positive, you might want tosleep()again on that value. Fromhttp://www.manpagez.com/man/3/Sleep/: If the sleep() function returns because the requested time has elapsed, the value returned will be zero.If the sleep() function returns due to the delivery of a signal, the value returned will be the unslept amount (the requested time minus the time actually slept) in seconds
well i'm using while loop: while(fgets(pclientRow, 1024 , f) != NULL) in other classes it works ok, but in one of them, when i'm reading from file line by line, it won't get out of the loop even when the lines end, i saw that in the debugger. why is it? and it was working even in that class before and now i dont know why it keep bringing empty lines untill it's crshing.. any idea?
fgets in a standard ANSI C function, see documentation: Here fgets read max. 1023 character up to next '\n' or EOF. Your lines are longer than 1023 character or the last line has no terminating newline.
I have a custom driver I have written. Here is the source code to communicate to the driver in C: ``` #include <windows.h> #include <stdio.h> /********************************************************* * Main Function Entry * *********************************************************/ int _cdecl main(void) { HANDLE hFile; DWORD dwReturn; hFile = CreateFile("\\\\.\\Example", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if(hFile) { WriteFile(hFile, "Hello from user mode!", sizeof("Hello from user mode!"), &dwReturn, NULL); CloseHandle(hFile); } return 0; } ``` I want to be able to do this in .NET preferaly in VB.NET. Does anyone know how to do the conversion?
The simplest is to use P/Invoke toOpenFile,WriteFileandCloseHandle.
``` #include <semaphore.h> sem_t mutex; int main (int argc, char * argv[]) { sem_init (&mutex,0,1); } ``` I'm getting: ``` /tmp/ccAMFxDX.o: In function `main': programaservidor.c:(.text+0x86): undefined reference to `sem_init' collect2: ld returned 1 exit status ```
Per the sem_init() man page Link with -lrt or -pthread. As ingcc your_code.c -lpthread -o your_code
I know that if the data type declaration is omitted in C/C++ code in such way:unsigned test=5;, the compiler automatically makes this variable an int (an unsigned int in this case). I've heard that it's a C standard and it will work in all compilers. ButI've also heard that doing this is considered a bad practice. What do you think? Should I really typeunsigned intinstead of justunsigned? Areshort,longandlong longalso datatypes?
unsignedis a data type! And it happens to alias tounsigned int. When you’re writingunsigned x;you arenotomitting any data type. This is completely different from “defaultint” which exists in C (but not in C++!) where you really omit the type on a declaration and C automatically infers that type to beint. As for style, I personally prefer to be explicit and thus to writeunsigned int. On the other hand, I’m currently involved in a library where it’s convention to just writeunsigned, so I do that instead.
I'm programming for a µC, i have following data Structure: ``` typedef struct { RF12Head head; typedef union { uint8_t raw[40]; typedef struct { node_id nodeId; uint8_t hierachyDepth; } MessageNodeFound; } data; } RF12Message; ``` A RF12Message contains a header an an data part. Now i want to have different message formats. I want to be able to do something like this: ``` RF12Message msg; memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly //or indirectly: msg.data.MessageNodeFound.nodeId = 3; msg.data.MessageNodeFound.hierachyDepth = 2; ``` but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why? thank you!
You have too manytypedefs in your code. Try this: http://codepad.org/frysgQte
Everything is the title. My team and I are currently working on a project and we are using MPI. In one place, we are doing a MPI_send resquesting for a resource with a timeout. If the resource is available, we return 1 and if not and the timeout ended, we return 0. We tried using the signals like SIGALRM, but it doesn't work because every new request cancel the old ones by setting a new alarm. Thanks for your answer !!
You should investigate the non-blocking point-to-point communication primitives such asMPI_Isend,MPI_IrecvandMPI_Iprobe. You can then implement the timeout yourself, and useMPI_Cancelif you wish.
To use pthreads, I used as input a char* that was cast to void* as input. If it's later cast to (char*) it can be printed and used normally ( (char*)var ). However, if one does (char*)var[i], where 'i' will help us reference a character, it doesn't. Why? e.g. MS says 'expression must be a pointer to a complete object type'.
Because of operator precedence: the cast comes after the subscript operator. You have to write((char*)var)[i];.
I have weird string that I want to inspect by printing its characters one by one. How can this be done? I'm worried in case it has any special characters that may obstruct its printing. Can they be 'escaped'?
You could loop over the string, printing the characters one by one, and conditionally choosing to print the character or an escape sequence: ``` char *str, // the original string *tmp; for(tmp = str; *tmp; tmp++) { printf((iscntrl(*tmp) ? "%02x\n" : "'%c'\n"), *tmp); } ``` This prints one character per line, with control characters printed in hex format.
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 center.Closed10 years ago. please can anybody help me to implementsizeof()operator in c.. i know the usage .. but i was not able to implement it.
You cannot implementsizeof()as a library function, it is a compiler intrinsic. Are you writing a compiler?
I will be continually splitting strings in a multithreaded application, I've read thatstrtokis not suitable for this, but why? Should I consider using a semaphore around the portion of my code that callsstrtok?
You should consider not usingstrtokorstrtok_rat all. It's trivial to write your own functions similar to these but better-tailored to the exact way you want to use them, and of course have the caller store all the state and pass a pointer to the state for thread-safety/reentrancy. As for your question about using a semaphore (or other locking primitive) around calls tostrtok, that will not help if you just put it around the actual call. You'd have to hold the lock during the whole process of parsing the string to protect the internal state ofstrtok. I believe this is what many people refer to aslocking code in place of dataand it's generally consideredA Bad Thing.
I'm writing an algorithm in C with netbeans to find asterisks in a string. ``` int main() { int M=0, i, j; scanf("%i",&M); int pos[M]; char c[M]; scanf("%s", c); i=0; j=1; while(c[i] != '\0'){ if(c[i]=='*'){ pos[j] = i; j++; } i++; } printf("Asterisks in positions: \n\n"); for(j=1; j<=i; j++){ printf("%i", pos[j]); } return 0; } ``` But it doesn't work, it prints a lot of numbers even if M is a small number.
The problem seems to be you never take into account the number of characters found. You print the whole vector, usingiinstead ofjto iterate. It'sjthat holds the number of matches. Also, try usingstrchr, from cstring :) Get the first position, then search again from the next character until null is returned.
I am having some trouble with a basic file opening. I can't successfully initiate the filestream. It keeps coming back NULL... Can anyone tell me what I'm missing? I created a "test.dat" file in the same directory that the source code lives. ``` #include <stdio.h> #include <stdlib.h> int main (void) { if((cfPtr = fopen("test.dat", "rb+")) == NULL) { printf("File could not be opened.\n"); } return 0; } ```
Try moving thetest.datfile to the directory where the compiled .exe lives, or if the current directory for the application is somewhere else, place the file in that directory.
``` //CHILD typedef struct Child{ int id; }Child; Child* newChild(){ Child *aChild = malloc(sizeof(Child)); aChild->id = 0; return aChild; } //PARENT typedef struct Parent{ int id; Child **children; }Parent; Parent* newParent(){ Parent *aParent = malloc(sizeof(Parent)); aParent->id = 0; aParent->children = malloc(sizeof(Child*) * 5);//ARRAY OF 5 CHILDREN? for(i=0; i<5; i++){ aParent->children[i] = newChild(); } return aParent; } ``` Is the newParent() function a correct way to create a struct with an array children? My main concern is the line: ``` aParent->children = malloc(sizeof(Child*) * 5); ```
You should check ifmallocactually succeeded, but other than that, the code is OK.
Here's what I tried... but failed: ``` void testfunc(...){ printf(...); } ```
This will create a function that is equivalent toprintf. Note that you cannot blindly print out arguments, since you somehow need to know what type each argument is in advance. Theformatargument to printf informs it what arguments to expect and what types they will be. ``` #include <stdargs.h> void testfunc(const char *format, ...) { va_list ap; va_start(ap, format); vprintf(format, ap); va_end(ap); } ```
A newbie question: I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code: ``` #include <stdio.h> int main (void) { char * option_string = NULL; option_string = (char*)malloc(sizeof(5)); memset(option_string, 0, sizeof(char) * 5); int j; for ( j = 0; j < 5; j++) { *option_string++ = 'a'; } printf("print options_string: %s\n", option_string); //!nothing was printed out! free(option_string); return 0; } ``` Thanks in advance!
You increment the pointeroption_stringwhich in turn makes it point past the end of string. Try malloc(6); ``` for ( j = 0; j < 5; j++) { option_string[j] = 'a'; } ``` instead.
I have a C++ program with the following in the header file:#define VARIABLE_X 100 Also, a JavaScript file with the global:VARIABLE_X = 100; These values will always need to be the same. Instead of having to change them in both places (.h and .js), I need a common file where both can get this value, thus only needing to be changed in one place. How can I create a common file between JavaScript and C/C++........ for a #define/constant ? Thank You.
You have an actual script-driven build process, right? Just stick a rule in your makefile that regeneratesconstants.hifconstants.jshas been changed.
Is there any way to speed up getting an array size in C? Typing outsizeof(array)/sizeof(int)every time gets old. Do any C libraries have something like.lengthor is there some way I can definesizeof(array)/sizeof(int)as a shorter constant of some sort (possible also using dot notation)?
You can usesizeof(array)/sizeof(*array)and make a macro. ``` #define length(array) (sizeof(array)/sizeof(*(array))) ```
I have been looking through the Lua source code, and I think that is how it works.
Lua and C use a stack to exchange arguments. Many script languages use this way to communicate with C program.