question
stringlengths
24
425
answer
stringlengths
5
405
When I doing my assigment , I am string to use this formatscanf("%[^\n]%*c",s);in putty but it said ``` writing into constant object (argument 2) [-Wformat=] scanf("%[^\n]%*c",s); ``` I want to input string with white space: ``` const s[10000]; ```
Changeconst char s[10000]-->char s[10000] Code cannot write to aconstarray. It is not a format issue forscanf().
``` int num = 65537; char p = (char)num; //char = 1; ``` Whats going on here? Is itp=num%(127+128)-1orp=num%256or something else? I need to know why p is equal to 1. thanks!
since 65537 is00000000 00000001 00000000 00000001in binary, but the char type has only 1 byte, the last byte is considered for the char value, wich is00000001 = 1
``` function(void * p) ``` pis an address containing an address to a struct. I cannot get from the given address to the address within to display the data that it points to. There is a really simple solution to do this, however I do not know how to dereference from the given address, and use the information I get as a new address.
Just cast to the type you're looking for. ``` MyStruct **pps = (MyStruct**)p; (**pps).Member = ... ```
``` function(void * p) ``` pis an address containing an address to a struct. I cannot get from the given address to the address within to display the data that it points to. There is a really simple solution to do this, however I do not know how to dereference from the given address, and use the information I get as a new address.
Just cast to the type you're looking for. ``` MyStruct **pps = (MyStruct**)p; (**pps).Member = ... ```
Specifically, I'm storing URLs and ports and storing them in a table. A pair would be ("www.beej.us", 80) or ("8.8.8.8", 22). Does it make sense to append the integer onto the string and hash on the final string? Thanks for the help!
For better performance and minimizing collisions, you would better write a hash function as follows: ``` hash(host) * prime_greater_than_65536 + port ```
This question already has answers here:String literals: Where do they go?(8 answers)Closed8 years ago. For example this code here: ``` char *s = "Hello"; ``` Where is "Hello" being stored? Is it stored the same in memory just anonymously?
String literals have static storage duration and are allocated in the static memory that is neither on the stack nor in the heap. For example they can be allocated in a read only data segment.
This question already has answers here:String literals: Where do they go?(8 answers)Closed8 years ago. For example this code here: ``` char *s = "Hello"; ``` Where is "Hello" being stored? Is it stored the same in memory just anonymously?
String literals have static storage duration and are allocated in the static memory that is neither on the stack nor in the heap. For example they can be allocated in a read only data segment.
Q:Could someone give a hint, why inside my program here are conflicting types, even if its the same?
If you call a function before it is defined (i.e. earlier in the file than the definition), the compiler won't know the argument types and return type. You need to have a function prototype before the function is called. Usually people put function prototypes in header files, but you could just add one near the top of your file.
Q:Could someone give a hint, why inside my program here are conflicting types, even if its the same?
If you call a function before it is defined (i.e. earlier in the file than the definition), the compiler won't know the argument types and return type. You need to have a function prototype before the function is called. Usually people put function prototypes in header files, but you could just add one near the top of your file.
Hi I program in c and I like using clion. Is there a way to change how the default files it creates in a new project? I would like it to create a main.c and the make file to reflect that.
ReadHow to create a C project with CLion. It's not possible to create a C project by default, but you could use the info of that post to prepare CMakeLists.txt.
I have a server program running. I want to connect 1000 clients to it and observe how the server is working. I also want to save the output to a file for analyzing. My server is just an echo server.
You can use netcat: ``` for ii in {1..1000}; do (echo "testing"; sleep 5; echo "goodbye") | nc localhost 12345 > out.$ii & done wait # for all to finish ```
In Linux I can do this by checking the /proc/pid/status file and looking for a line: Threads: 1 (or any number). How can I achieve the same in FreeBSD? I am not interested in any interactive tool. Is there any C function, or a system file? I have tried BSD's procfs and and linprocfs and I could not find any similair feature there.
You want: procstat -t <pid> This answer is short, but I'm typing more to get the answer up to the minimum length.
Is the memory lost until a reboot or does VS have some safe-mechanism to handle that? I've always wondered...
The leaked memory will be freed when the process leaking the memory is closed and the operating system cleans up.
I have achar *p = "abcd", how can I access the elements'a','b','c','d'using only C(not C++)? Any help would be appreciated .
You can use indexing: ``` char a = p[0]; char b = p[1]; /* and so on */ ``` Equivalently you can use pointer arithmetic, but I find it less readable: ``` char a = *p; char b = *(p+1); ``` If you really want to surprise someone you can also write this: ``` char a = 0[p]; char b = 1[p]; /* and so on */ ```
``` typedef struct A { int* whatever; } A; int main(void) { A* foo = (A)malloc(sizeof(A)); foo->whatever = (int)malloc(sizeof(int)); free(A); // leak? (foo->whatever) return 0; } ``` Do I have to free each component of a struct / composite data type, or can I just free the struct?
Anything that is malloc'd needs to be freed
I want to test my c code for big endian on Windows (On x86-64). How can we do this?
Assuming that you don't have any actual big-endian hardware to hand, your best bet is to use a virtual machine such asQEMUto emulate a big-endian architecture such asSPARCorPowerPC. You'll then need to install a suitable operating system on your VM - perhapsDebianwould suit your needs.
I want to test my c code for big endian on Windows (On x86-64). How can we do this?
Assuming that you don't have any actual big-endian hardware to hand, your best bet is to use a virtual machine such asQEMUto emulate a big-endian architecture such asSPARCorPowerPC. You'll then need to install a suitable operating system on your VM - perhapsDebianwould suit your needs.
``` int i=0; int array[1000]={0}; srandom(23523); a0=random(); a1=random(); a2=random(); .... a999=random(); //a0,a1,...a999 are some random numbers for(i=0;i<999;i++){ .... //array[0]=a0 array[1]=a1 array[2]=a2....array[999]=a999 } ``` My goal is to change the values in array to a0, a1...a999. How to do it by using for loop in C?
If you already know the values you don't need a loop. ``` int array[3]= { 0, 14, 22 }; ```
Using C in a Windows in a Kernel Mode Driver using KMDF, how do I determine the owner a of file? I searched high and low but could not find any hint. Only C++ and of course Csharp.
After opening a handle to a file, you can use the kernel-modeZwQuerySecurityObjectto get the owner information (and full DACL).
I'm learning on how to use signals in C with POSIX threads. I know how to signal threads from main, but how to signal my main from the thread to notify it that it has finished some job? I need the PID of my main. How should I go about doing it? How can I let my threads know mains PID to send a signal to it?
In the main threadgetpid() == gettid(), so, you can usegetpid()orgettid()to get PID of main thread.
I'm learning on how to use signals in C with POSIX threads. I know how to signal threads from main, but how to signal my main from the thread to notify it that it has finished some job? I need the PID of my main. How should I go about doing it? How can I let my threads know mains PID to send a signal to it?
In the main threadgetpid() == gettid(), so, you can usegetpid()orgettid()to get PID of main thread.
Is there anyway to open an sqlite database in c without having to have the sqlite exes and dlls. Is there a lib to do this. I only want to read the database, not write.
Have you taken a look at theSQLite3 C/C++ interface? (See the second bulletpoint of the section titled "Write Programs that use SQLite" at the bottom ofthis pagefor a quick example on how to use it.)
I want to know how to get all data from a gtk treeview (row and column) and put it in a logfile, I know how to create the log, my problem is getting all data, I already know how to get the selected row, but not all rows at once.
gtk_tree_model_foreach is your friend.
If I have this code block ``` char *array[] = {"element1" , "eLement2"}; char *p ; char *pc; ``` How can I point*pto the first String"element 1"andhow can I point*pcto the second character of the second StringLand then print those two using printf
p = array[0] pc = array[1]+1 This should do the trick
If I have this code block ``` char *array[] = {"element1" , "eLement2"}; char *p ; char *pc; ``` How can I point*pto the first String"element 1"andhow can I point*pcto the second character of the second StringLand then print those two using printf
p = array[0] pc = array[1]+1 This should do the trick
If I have this code block ``` char *array[] = {"element1" , "eLement2"}; char *p ; char *pc; ``` How can I point*pto the first String"element 1"andhow can I point*pcto the second character of the second StringLand then print those two using printf
p = array[0] pc = array[1]+1 This should do the trick
I want to pack the lowest two bytes of an integer into another in integer, an stuck at this ``` for ( int i = 0; i < 8 ; i ++){ if ((bitmask & ( 1 << i))) result |= 1 >> i; } ```
Endian-independent solution: ``` x = ((y >> 0) & 0xFF) | ((y >> 8) & 0xFF); ```
I am using a macro defined in the same source file as: ``` #define MY_MACRO (a, b,...) (...) ``` The macro is being used later in the file. However, the compiler complains: error: a undeclared (first use in this function). It's really weird.. am I missing something obvious?
I think the problem is that there is a SPACE betweenMY_MACROand(a, b, ...). It should be like this: ``` #define MY_MACRO(a, b,...) (...) ```
I am writing some C code with Eclipse + CDT + MinGW. The compilation output always shows: ``` Info: Internal Builder is used for build gcc -O0 -g3 -Wall -c -fmessage-length=0 -o Math.o "..\\Math.c" ``` How can I change the command line parameters such as -O0, -Wall? (I am new to Eclipse IDE.)
For GCC, the setting is in project properties => C/C++ Build => Settings => GCC C Compiler => Optimization.
I am writing some C code with Eclipse + CDT + MinGW. The compilation output always shows: ``` Info: Internal Builder is used for build gcc -O0 -g3 -Wall -c -fmessage-length=0 -o Math.o "..\\Math.c" ``` How can I change the command line parameters such as -O0, -Wall? (I am new to Eclipse IDE.)
For GCC, the setting is in project properties => C/C++ Build => Settings => GCC C Compiler => Optimization.
Suppose I want to generate a very long, repetitive string, such as ``` "foo bar bar bar bar ... bar" ``` wherebaroccurs 1,000 times in the final result. What would be the easiest way to do this without having memory leaks?
The first thing that came to my mind is: ``` char *string = malloc(4004); int i; strcpy(string, "foo"); for(i = 0; i < 1000; i++) strcat(string, " bar"); ```
I need to initialize a typedef struct pointer in header file, ``` typedef struct { DWORD RxBuf[4]; DWORD Tr0c; } t, *p_t; ``` In the cpp file, ``` static p_t p1 = { {0x00,0x00,0x00,0x00}, 0 }; ```
Just a guess, I believe you want to do: ``` static t tNull = { {0x00,0x00,0x00,0x00}, 0 }; static p_t p1 = &tNull; ```
I need to initialize a typedef struct pointer in header file, ``` typedef struct { DWORD RxBuf[4]; DWORD Tr0c; } t, *p_t; ``` In the cpp file, ``` static p_t p1 = { {0x00,0x00,0x00,0x00}, 0 }; ```
Just a guess, I believe you want to do: ``` static t tNull = { {0x00,0x00,0x00,0x00}, 0 }; static p_t p1 = &tNull; ```
Now, when I print each element in my block array, each one has the same address. For example: ``` ints: 20 bytes stored at 0xbffa84fc doubles: 80 bytes stored at 0xbffa84fc chars: 8 bytes stored at 0xbffa84fc Students: 1008 bytes stored at 0xbffa84fc ```
``` blk->addr = &blk; ``` The address of the allocated memory actually isblkitself. But here, you are using&blk, i.e, the address ofblk.
So far, I can print in one column quite nicely : ``` for (i = 0 ; i < *lengthOfFile ; i++) { fprintf(myFile, "%d\n", thisArray[i]); } ``` Easy enough. However, how would I go about printing in columns of ten if say I have 20 or 100 or 10000 or more numbers? Anything would help very much, thank you!
You can print "%d\t" instead of "%d\n", and move the "\n" into its own print statement that only occurs when (i % 10) == 0.
If I have an array declared as ``` char arr[1] = ""; ``` What is actually stored in memory? What will a[0] be?
Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e,'\0'. ``` char arr[1] = ""; ``` is equivalent to: ``` char arr[1] = {'\0'}; ``` You can imagine how it's stored in the memory from this.
If I have an array declared as ``` char arr[1] = ""; ``` What is actually stored in memory? What will a[0] be?
Strings are null-terminated. An empty string contains one element, the null-terminator itself, i.e,'\0'. ``` char arr[1] = ""; ``` is equivalent to: ``` char arr[1] = {'\0'}; ``` You can imagine how it's stored in the memory from this.
Why does this hang without first printing? ``` #include <stdio.h> void main() { printf("hello world"); while (1) {} } ```
Because you haven't flushed the standard output. Tryfflush. Even better, for C++ use... ``` std::cout << "hello world" << std::endl; ``` Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.
Why does this hang without first printing? ``` #include <stdio.h> void main() { printf("hello world"); while (1) {} } ```
Because you haven't flushed the standard output. Tryfflush. Even better, for C++ use... ``` std::cout << "hello world" << std::endl; ``` Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.
Why does this hang without first printing? ``` #include <stdio.h> void main() { printf("hello world"); while (1) {} } ```
Because you haven't flushed the standard output. Tryfflush. Even better, for C++ use... ``` std::cout << "hello world" << std::endl; ``` Separately, you'd have a better chance of it flushing itself if you added a\n, but not all implementations follow the Standard when it comes to such things.
I'v been use some module manager like npm for node.js or apt-get in ubuntu, I find it's really easy to build more. And I just want to know is there a cpm for module manage in c programming?
clibmay be the answer.https://github.com/clibs/clibit is proposed to offer some stand-alone "micro c libraries".
Is there an option that I can use to separate parts of my GUI with lines in Glade 3? I want some widgets to be separated from the others; for example I would like to put them in a box.
Use GtkSeparator; its icon is the vertical line in the Control and Display section of the tool palette.
I developed a program in which I use a http client with libcurl. I want to find out the source tcp port used by libcurl in a tcp session. How can I do that ?
curl_easy_getinfowith theCURLINFO_LOCALPORToption!
Glibc provides the very handybacktrace()andbacktrace_symbols()functions, which can help getting the stack trace of the current function programmatically (see here). Does the Windows API provide any similar functions?
Yes, take a look at the functionCaptureStackBackTrace(). UseSymFromAddr()and its counterparts to get meaningful symbol names.
Given an API like this : write_data(uint32_t address,uint8_t *data) how can I transmit a constant to my embedded device, like 0x001 ?
You create a variable and assign the constant to it. Then you pass a pointer to the variable.
This question already has answers here:What does void mean in C, C++, and C#?(15 answers)Closed8 years ago. What is the value that is stored in void()? Basically it is used before a function which doesnot return anything. But does simply void holds any value?
Void is an incomplete type which, by definition, can't be an lvalue. That means it can't get assigned a value. So it also can't hold any value.
This is my program : ``` #include<stdio.h> int main() { int *n; int var; scanf("%d",n); printf("%d",*n); } ``` asscanfstores the value at specified address I am giving the address .Then I am trying to print value at address but its giving segfault.
You should allocate memory for pointers like this: ``` int* n = (int*)malloc(sizeof(int)) ```
I am working on a project in which If I could include a header file at runtime, it would save some programming effort. I google'd about it, but all in vain. My question is :Can we include header files in a C program at runtime ?If yes, how?If not, why?
In C the source files are only read compile-time, so the answer to your question isnot. Runtime there is only the executable binary, which has nothing to do with your source code headers.
i have created macro as following ``` #define log printf("(%s):(%d) ",__FUNCTION__, __LINE__);printf ``` And i am using it in main function for logging ``` log("Hello world\n"); ``` it is resulting in run time error as "lldb". Error in IDE is displaying "called object type 'int' is not a function or function pointer in x code"
Try: ``` #define LOG( s ) printf( "(%s):(%d)%s\n", __FUNCTION__, __LINE__, s ); ```
I see many programmers that include "utils.h" to their program. Tried to search for what it is exactly and what is the proper use of utils.h, but all I found was different versions of the file. So what is it exactly?
Many programmers define common functionalities inutils.cand declare them inutils.h. You could implement for example command line parsing methods in utils.h / utils.c. But utils.h is no standard file to be included.
I see many programmers that include "utils.h" to their program. Tried to search for what it is exactly and what is the proper use of utils.h, but all I found was different versions of the file. So what is it exactly?
Many programmers define common functionalities inutils.cand declare them inutils.h. You could implement for example command line parsing methods in utils.h / utils.c. But utils.h is no standard file to be included.
How do I write nothing inifpart if the condition is true? For example: ``` if(true) // I want to keep this space blank or want compiler to do nothing here else break; ``` How do I do this?
Typically, this is written by negating the condition: ``` if (not true) break; ```
How can I write three different matrices of different sizes say A, B and C using C? The doubt being that once a particular row is printed the cursor is in the bottom most position, now how do we bring it back up?
You don't. you plan in advanced the rows and then print each row (one you go down - you can't go up....) If you can't handle the logic - use a 2d array to store everything and then print it.
How do I write nothing inifpart if the condition is true? For example: ``` if(true) // I want to keep this space blank or want compiler to do nothing here else break; ``` How do I do this?
Typically, this is written by negating the condition: ``` if (not true) break; ```
How can I write three different matrices of different sizes say A, B and C using C? The doubt being that once a particular row is printed the cursor is in the bottom most position, now how do we bring it back up?
You don't. you plan in advanced the rows and then print each row (one you go down - you can't go up....) If you can't handle the logic - use a 2d array to store everything and then print it.
What is the unary-& doing here? ``` int * a = 1990; int result = &5[a]; ``` If you were to printresultyou would get the value 2010. You have to compile it with-fpermissiveor it will stop due to errors.
In C, x [y] and y [x] are identical. So &5[a] is the same as &a[5].
Is it possible to intercept primitive operations (+,-,% etc.) like this one, with LD_PRELOAD? ``` int64_t endWhenNsec = startWhenNsec + gTimeLimitSec; ``` If not, any way to achieve something similar?
No. Primitive operators are compiled directly to machine code. There is no library involved, so preloading libraries cannot alter their behavior. What a mess if it could!
Is there any way to do this withstrtokfunction? or any suggestions ? Example : ``` Insert "hello world" to dbms ``` Result: ``` Insert "hello world" to dbms ```
strtokor any other function in the standard C library can't do this for you. To get it, you have to write code for it yourself, or you have to find some existing code in some external library.
According to the man page for pause, it returns -1 and sets errno to EINTR. Why does it do this? I understood -1 to mean a failure, not something operating as normal.
The only timepause()stops pausing is when it is interrupted, and that is a return on failure (to continue pausing). So, correctly, it returns -1 to indicate that it failed to continue pausing.
Is it possible to clear the output at the command prompt using C on windows? For example, on linux I could do ``` printf("\033[2J"); ``` But as far as I know windows doesn't recognise the ANSI escape codes Thanks. EDIT: I guess I'll also need to get the cursor back to 0,0 fo r the next output after the clear...
There are many way to do that on windows. You includeconio.hand call_clrscr(); Or you can callsystem("cls");
I have the following function in assembly, but I need it in C. The code is: ``` push ebp mov ebp, esp mov eax, DWORD PTR [ebp+8] add eax, 1667940388 pop ebp ret ``` Could anybody translate this into C for me. Thanks.
Sorry for the silly mistake on theeaxreturn value ... its' fixed now ... my assembly is a little rusty :) ``` int function(int value) { return value + 1667940388; } ```
I have the following function in assembly, but I need it in C. The code is: ``` push ebp mov ebp, esp mov eax, DWORD PTR [ebp+8] add eax, 1667940388 pop ebp ret ``` Could anybody translate this into C for me. Thanks.
Sorry for the silly mistake on theeaxreturn value ... its' fixed now ... my assembly is a little rusty :) ``` int function(int value) { return value + 1667940388; } ```
I have the following function in assembly, but I need it in C. The code is: ``` push ebp mov ebp, esp mov eax, DWORD PTR [ebp+8] add eax, 1667940388 pop ebp ret ``` Could anybody translate this into C for me. Thanks.
Sorry for the silly mistake on theeaxreturn value ... its' fixed now ... my assembly is a little rusty :) ``` int function(int value) { return value + 1667940388; } ```
How do I create a soft link programmatically in C/C++? link() system call in freebsd will create a hard link.
The system call you want issymlink(2). ``` #include <unistd.h> int symlink(const char *name1, const char *name2); ``` A symbolic linkname2is created toname1
What could be the simplest way to split strings in an array and put it to array of array of strings in C. For example ``` ["this is a test", "this is also a test"] ``` into ``` [["this", "is", "a", "test"], ["this", "is", "also", "a", "test"]] ```
Usestrtokfunction from the C library. The function splits a string into a serie of tokens. http://man7.org/linux/man-pages/man3/strtok.3.html
How can I set the socket buffer size for a UNIX socket file descriptor in C? I understand setsockopt is probably the system call involved... Can anyone give an example of how to use it, the one's I have found do not explain how to set the buffer size?
On Ubuntu 14.04 Linux check outman 7 socket, and specifically look atSO_RCVBUFandSO_SNDBUF.
Is there a way using the OpenLDAP API to set a particular network interface address to be used for socket bind on the LDAP client on a multi homed machine; like you do with the LDAP_OPT_SOCKET_BIND_ADDRESSES option with Microsoft's LDAP client.
You can do it by creating and binding and connecting the socket yourself and then calling ldap_init_fd() to turn it into an LDAP connection.
I'm developing in c, using visual studio 2013. I wonder if there is a way in visual studio, or a plugin, that enable to refactor names of variable/functions ... If not, Is there any other recommended IDE that enables refactoring with C? Thanks.
Visual Assist(commercial) andVisual C++ Refactoring(free) extensions for VS 2013 support the rename refactoring for C.
How to generate random numbers with rand() and srand() without time.h in C ?
You could try givin another seed to the random generator like the program's pid. ``` srand(getpid()); int num = rand(); ```
``` for (int i = 0; i< n; i++) arr[arr[i]%k] += k; ``` I'm new to programming and I came across this piece of codehere. Can anyone explain what it does?
Translate to: ``` for (int i = 0; i< n; i++) { int temp1 = arr[i]; int temp2 = temp1%k; int temp3 = arr[temp2]; arr[temp2] = temp3+k; } ``` Edit: thanks for the correction @R Sahu
Does K&R 2nd edition explain the usage of typedefs to make declaration and use of function pointers easier? I lost my copy and can't recollect of it does or it does not. Thanks.
Yes, this is explained in section 6.7, "Typedefs".
How can I tell what version of the C library python's zlib module was built with? Specifically, I want to tell whether it was a new enough version to support ZLIB_RSYNC=1 This is different than the version of the zlib pythonmodule, but instead the version of the underlying C library
It iszlib.ZLIB_VERSION: ``` >>> import zlib >>> zlib.ZLIB_VERSION '1.2.7' ```
How can I tell what version of the C library python's zlib module was built with? Specifically, I want to tell whether it was a new enough version to support ZLIB_RSYNC=1 This is different than the version of the zlib pythonmodule, but instead the version of the underlying C library
It iszlib.ZLIB_VERSION: ``` >>> import zlib >>> zlib.ZLIB_VERSION '1.2.7' ```
From which file ifconfig command takes input for displaying ip address, inet addr and h/w addr ?. I want this information for my presentation. Any file apart from /etc/network/interfaces is there ? Looking foreword for help.
It's in the manual man. just run commandman ifconfigin your terminal and at bottom it says it comes from these three files: ``` FILES /proc/net/socket /proc/net/dev /proc/net/if_inet6 ``` Hope it works.
If the following array contained shell code in a C program on a LINUX machine ``` char buf [100] ``` then how does the following execute this shell code : ``` ((void(*)())buf)() ```
Simple. It castsbufto a pointer-to-function taking no arguments and returningvoid, and then invokes that function. However, that probably won't work since the page containingbufis highly unlikely to be marked as executable.
I am reading the current directory and printing it out using ``` printf("%s\n", file->d_name); ``` but it also prints out "." and ".." files. How can I exclude them?
The simple way: just make sure the file name isn't"."or".."before you display it. :P ``` if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) { printf("%s\n", file->d_name); } ```
I'm trying to create a game for my CS assignment and I'm stuck with this for loop that won't end my game even though the lives are already at zero. ``` for(life = 3, ai_life = 3; ai_life != 0, life != 0; --ai_life, --life) ```
Please read up what thecomma operatordoes ``` for(life = 3, ai_life = 3; ai_life != 0 && life != 0; --ai_life, --life) ```
Lets say I am in /home/myuser there are 90,000 files there inside 3000 directories. How can I write a bash function or with linux commands to get one random file? It could be C as well I suppose
You can list all your files and then pick a random line between them: ``` find /home/myuser | sort -R | head -n1 ``` However this is not very efficient, and could take a while, but is easy to understand. You can work from here.
I am reading the current directory and printing it out using ``` printf("%s\n", file->d_name); ``` but it also prints out "." and ".." files. How can I exclude them?
The simple way: just make sure the file name isn't"."or".."before you display it. :P ``` if (strcmp(file->d_name, ".") && strcmp(file->d_name, "..")) { printf("%s\n", file->d_name); } ```
I'm trying to create a game for my CS assignment and I'm stuck with this for loop that won't end my game even though the lives are already at zero. ``` for(life = 3, ai_life = 3; ai_life != 0, life != 0; --ai_life, --life) ```
Please read up what thecomma operatordoes ``` for(life = 3, ai_life = 3; ai_life != 0 && life != 0; --ai_life, --life) ```
``` int gcd(int x, int y) { int t; while (y) { t = x; x = y; y = t % y; } return x; } ``` Does it stop when y = 0? I thought the loop stops when y isn't defined.
Yes, it stops when y is 0, what you have ``` while (y) ``` is short hand for ``` while (y != 0) ```
``` int foo(int n) { int sum = 0; for(int k=1; k <= n; k = k * 2) { sum += k; } return sum; } ``` I have the following function. Now, according to me the runtime complexity of foo(n) should be big-o(logn). Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should it be? According to me, it should be, big-o(logn) only. Am I right in saying this?
It is O(log n4) → O(4 log n) → O(log n)
``` int foo(int n) { int sum = 0; for(int k=1; k <= n; k = k * 2) { sum += k; } return sum; } ``` I have the following function. Now, according to me the runtime complexity of foo(n) should be big-o(logn). Now, I am asked to find out the run time complexity of foo(n*n*n*n). What should it be? According to me, it should be, big-o(logn) only. Am I right in saying this?
It is O(log n4) → O(4 log n) → O(log n)
``` int main() { int a,i; char b; for(i=0;i<3;i++) scanf("%c %d",&a,&b); ``` } The program only scans twice (each for char and int) and then terminates. OUTPUT r 3 4 t Now program is terminating rather than scanning two more times(one char and one int)
``` scanf(" %c %d",&a,&b); ``` solves the problem
``` int main() { int a,i; char b; for(i=0;i<3;i++) scanf("%c %d",&a,&b); ``` } The program only scans twice (each for char and int) and then terminates. OUTPUT r 3 4 t Now program is terminating rather than scanning two more times(one char and one int)
``` scanf(" %c %d",&a,&b); ``` solves the problem
please could you help me understand what's __format in printf prototype for? extern int printf (const char *__restrict __format, ...); How can I find set of these in documentation? Thanks!
as per the ISO/IEC 9899:1999 declaration, int printf(const char * restrict format, ... ); using the__is a variable nomenclature.
This question already has answers here:!! c operator, is a two NOT?(4 answers)Closed9 years ago. While going over infrastructure code, I found this: ``` return !!(fin.flags & FIN_ACCEPT); ``` Does this has a meaning other than two logical nots in succession?
!is logical negation.!!is logical negation applied twice. It is typically used to normalise a boolean expression value to be either0or1.
``` struct tree{ #ifdef A #define TREE_GET(x,y) &x->y #else #define TREE_GET(x,y) x->y #endif }; ``` I want to know whether macro A was defined . Is there any command I can use in gdb .
In compilation time we pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information. For example,g++ -gdwarf-2 -g3 program.cpp -o program C Preprocessor Macros
``` struct tree{ #ifdef A #define TREE_GET(x,y) &x->y #else #define TREE_GET(x,y) x->y #endif }; ``` I want to know whether macro A was defined . Is there any command I can use in gdb .
In compilation time we pass the -gdwarf-2 and -g3 flags to ensure the compiler includes information about preprocessor macros in the debugging information. For example,g++ -gdwarf-2 -g3 program.cpp -o program C Preprocessor Macros
``` int main() { static int fun(){} return 0; } ``` ** If we define a function into another then why this code is giving following error:** Error: invalid storage class for function ‘fun’
This is called "nested function". It's not supported in C. Some compilers, such asgcc, offer it as language extension. You do not need thestatickeyword though.
What happens if you callopendir(argv[i])andargv[i]is the name of atextfile, not adirectory?
Fromman opendir: Return ValueTheopendir()andfdopendir()functions return a pointer to the directory stream. On error,NULLis returned, anderrnois set appropriately. In this case,errnowould beENOTDIR: name is not a directory.
I initialized my array like this:char x[]={'m'}; It worked. But for the following lines i got error:Size of the type is unknown or zero ``` char x[][]={{'m'},{'m'}}; ``` or ``` char x[][]={{'m'}}; ``` I am unable to find the reason of the error.
While defining a 2D array, specifying the column size is mandatory. ``` char x[][1]={{'m'}}; ```
I initialized my array like this:char x[]={'m'}; It worked. But for the following lines i got error:Size of the type is unknown or zero ``` char x[][]={{'m'},{'m'}}; ``` or ``` char x[][]={{'m'}}; ``` I am unable to find the reason of the error.
While defining a 2D array, specifying the column size is mandatory. ``` char x[][1]={{'m'}}; ```
I would like to initialize an array of strings with \0. Is it right to do it like this? ``` char first[1024][1024] = {'\0'}; ```
For a 2d array is better to use: ``` char first[1024][1024] = {{'\0'},{'\0'}}; ``` or better yet (as suggested by @haccks): ``` char first[1024][1024] = {{'\0'}}; ``` in order to avoid warnings.
i need to put many symbols in one array of char. This is my code, I have problem with the single quote symbol, "'" : ``` int main() { int i, j; int a; char alph[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','.',',',':','?','=','-','(',')','"',''','/','%','@','!'}; } ```
You can escape the quote with a backslash, i.e.'\''
I have a simple program like : ``` #include <stdio.h> int main(void){ *(int*) 1 = 1; return 0; } ``` but why it is giving me Segmentation fault?
This will most likely crash no most systems. The assignment ``` *(int*)1 = 1; ``` tries to assign 1 to the location in memory with address 1. This is very undefined behaviour, and in most of systems the memory protection mechanism raises an error when you try it.
I want to remove or hide some components from my window (button, combobox, etc). How can I do that?
So, I've found answer on pelles-c forum:http://forum.pellesc.de/index.php?topic=6382.0 ``` ShowWindow(hWnd, SW_HIDE); // where hWnd - is some component ```
I have a simple program like : ``` #include <stdio.h> int main(void){ *(int*) 1 = 1; return 0; } ``` but why it is giving me Segmentation fault?
This will most likely crash no most systems. The assignment ``` *(int*)1 = 1; ``` tries to assign 1 to the location in memory with address 1. This is very undefined behaviour, and in most of systems the memory protection mechanism raises an error when you try it.
I want to remove or hide some components from my window (button, combobox, etc). How can I do that?
So, I've found answer on pelles-c forum:http://forum.pellesc.de/index.php?topic=6382.0 ``` ShowWindow(hWnd, SW_HIDE); // where hWnd - is some component ```
This question already has answers here:Command-line Parameters in C program?(5 answers)Closed9 years ago. How can I send parameters to main in C(Linux): first one is -c or -d second is a string like file. How I'm doing that?
First, send data to your program using command line argument Like @haccks said Second, get the arguments in your code using : ``` int main(int argc, char **argv) ``` Tutorial Here