question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This question already has answers here:In C storing values that start with zero get mutated, why?(4 answers)Closed4 years ago.
So I have the following code:
```
#define x 010000
```
My intention is to define x as '10000' in decimal but when I print out the above code it gets printed as 4096.
I dont understand how is that being translated to 4096.
Could anyone please explain?
|
Numbers starting with a 0 are treated as octal in C.010000is an integer literal written in the octal notation. Its value is8**4=4096. Remove the first 0.
|
I'm trying to run a small piece of code for 3 seconds:
Example:
```
WHILE(3 SECONDS){
printf("Hey");
}
```
I've tried to use time_t, counting some time till I reach a limit, like this:
```
time_t endwait;
time_t atual = (unsigned int)time(NULL);
time_t duration = secs;
while(atual < endwait){
printf("Hey");
}
```
But it's not working, the program is stuck in a loop printing "Hey".
|
The short version:
```
time_t endwait = time(NULL) + secs;
while(time(NULL) < endwait){
printf("Hey");
}
```
Or even:
```
for(time_t start = time(NULL);time(NULL)-start < secs;) printf("Hey");
```
|
I need to create a program in c and then build some code in the way that allows me to see what the metadata is in a file, not creating a header, just from any file. I've been searching this all around but still didn't find anything. I need to create a program in c able to read file system information about that file, size, type of file (normal, diredctory, link, etc.), i-node, owner, creation time and last modification. I know how to open the file and such, but I have no idea how to read that metadata. I appreciate de help. Also it's in linux
|
Did you try fstat()?
Man page link:https://linux.die.net/man/2/fstat
|
```
int a = 0;
#pragma omp parallel private(a)
{
a++;
printf ("%d", a);
}
```
I got an exercise where I have to say what the output of printf is but it shows "
main.c:13:1: error: expected identifier or ‘(’ before ‘{’ token "
and I do not know what to do :( sorry I am a noob to c
|
You need to wrap your instructions in a function, in this casemain(which is the function which will be run first in your program):
```
int a = 0;
#pragma omp parallel private(a)
int main()
{
a++;
printf("%d", a);
}
```
|
```
int a = 0;
#pragma omp parallel private(a)
{
a++;
printf ("%d", a);
}
```
I got an exercise where I have to say what the output of printf is but it shows "
main.c:13:1: error: expected identifier or ‘(’ before ‘{’ token "
and I do not know what to do :( sorry I am a noob to c
|
You need to wrap your instructions in a function, in this casemain(which is the function which will be run first in your program):
```
int a = 0;
#pragma omp parallel private(a)
int main()
{
a++;
printf("%d", a);
}
```
|
Below is a toy example of the C/Fortran files I want to compile together.
The C file
```
void testfunc();
int main(void)
{
testfunc();
}
```
The Fortran file
```
subroutine testfunc() bind (C, name = "testfunc")
write(*,*) "Hello World!"
end subroutine
```
Using gcc, I can generate a binary with the command
```
gfortran -o my_prog main.c testfunc.f90
```
However, when I try the same with pgf90
```
pgf90 -o my_prog main.c testfunc.f90
```
I get the following error message:
```
main.obj : error LNK2005: main already defined in f90main.obj
f90main.obj : error LNK2019: unresolved external symbol MAIN_ referenced in function main
```
Is there a standard procedure for compiling C+Fortran with pgi on Windows?
|
Add the flag "-Mnomain" to the link to have the compiler not include the F90 main object to the link and instead use the user supplied C main.
|
I need to download a file from an ftp server and I found this example using libcurlftpget.c. It works great in Linux with gcc, but I want my program to work in Windows as well. I noticed there's a port in vcpkg so I installed it withvcpkg install curl[*]:x64-windowswithout any error. However, the problem is that this version of libcurl doesn't seem to support ftp as it just says* Protocol "ftp" not supported or disabled in libcurland fails. If I use http or even https it works just fine. I don't know if ftp is simply not supported or if I need to enable it somewhere. I opened an issue on vcpkg github page but didn't get any reply.
|
vcpkg install curl[non-http]:x64-windowssolved my problem thanks tomyd7349.I guess I didvcpkg install curl:x64-windowsinstead previously and by defaultUSE_HTTP_ONLYis set for some reason so other protocols are all disabled.
|
I want to use semaphores for "consumer-producer" problem using C in windows.
in file (afile.c) I globally declared a handle to semaphore:
```
HANDLE empty;
```
in the same file (afile.c), inside one of the functions, I created the semaphore:
```
empty = CreateSemaphore(NULL,size, size, NULL);
```
and used it in some functions. after finished using, i relesed it using:
```
ReleaseSemaphore(empty,1,NULL);
```
I want to use this semaphore in another file (bfile.c), so i included (afile.h) in (bfile.c)
```
#include "afile.h"
```
bfile.c cant recognize this semaphore.
any suggestions for solving this problem, or, help in undestanding how to make use of semaphores from multiple files?
|
In afile.c you should have:
```
HANDLE empty = INVALID_HANDLE_VALUE;
```
In afile.h you should have:
```
extern HANDLE empty;
```
|
Need to implement one api which has some parameters;which has input's type (const void*), output's type (void**); the api wants to assign input with some offset to the output; for example,
```
void getOffset(const void* a, void** b)
{
int offset = getsomeoffset();
*b = a + offset;
}
```
This will have some complain in the compiler. What's the correct way to write this code? The input's type can be float, int, double.
|
You cannot apply pointer arithmetics on avoid *pointer. The target pointed to does not have any type and hence no size which could be used to calculate the offset.
Therefore you need to cast your pointer before applying the offset:
```
*b = ((char *)a) + offset;
```
With this statement the offset is interpreted as number of bytes.
|
I need to retrieve the socket object in an apache C module. I have read the documentation and didn't find a way to retrieve this.
However, I can get theapr_sockaddr_tobject for a request
|
Here is a way to do it :
```
apr_socket_t *asock = ap_get_conn_socket(req->connection);
int fd = 0;
apr_os_sock_get(&fd, asock);
char buf[1024] = "HTTP/1.1 200 OK\r\nContent-Length: 34\r\nContent-Type: text/html\r\nHost: localhost\r\n\r\nHELLO WORLD FROM AN AWESOME SOCKET";
write(fd, buf, strlen(buf));
close(fd);
```
|
I'm currently trying to include thelibsshlibrary on Visual Studio 2017.
I already downloadedlibsshbut I don't know exactly what am I supposed to do with cmake. Where should I include files in Visual studio?
|
What you downloaded is the source code of libssh. So before you can link it to any of your own projects, you need to build libssh first. This werecmakecomes in.CMakeis the build system used for libssh.
In the source tree, which you have downloaded, you will find a file namedINSTALL. It contains descriptions about all the prerequisites and a how you can usecmaketo build libssh yourself.
If you prefer it, you can alternatively download a prebuilt version of libssh fromhttps://www.libssh.org/files/win32/0.5/. The downside is, this is a quite dated version.
|
Hey I searched it but I can't find... I need a function to get information from user in switch case.
```
switch (/* FUNCTION */) {
```
How can functions can be use in this situation?
|
So long at the function returns an integer type, you can do that. So given:
```
int someFunction( void ) ;
```
Then:
```
switch( someFunction() )
{
...
```
is valid. It is little different than:
```
int x = someFunction() ;
switch( x )
{
...
```
but the latter is arguably easier to debug. For example, you can single-step the latter and know from the value ofxwhich case will be entered, and have the opportunity of modifyingxto force an alternative path. The former has little merit other than succinctness.
|
I am really confused with structs in C. I am trying to make an array of words which I store in pointer. I then set the args field of line to the pointer. I have the following code:
```
typedef struct line{
char *args[MAX_INPUT];
struct line *next;
} line;
void read_line(){
line l1;
char *pointer = (char *)malloc(1024);
l1.args = pointer;
}
```
|
If you want to break a line into words, you need a loop:
```
void read_line(){
line l1;
// Some kind of a loop: while or for - with a loop variable i
// For each fragment:
{
char *pointer = malloc(1024);
l1.args[i] = pointer;
// Here, copy the next fragment into l1.args[i]
...
}
}
```
|
I want to use a bubble sort method for my homework and it doesn't work, I can't find the mistake
```
void bubbleSort(int arr[], int n)
{
int i,j;
for (i = 0; i < n-1; i++)
// last i elements are already in place
for (j = 0; j < n-i; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
```
Can someone help me? Thanks in advance
|
Notice the second loop stop condition should be n - i - 1
```
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already in place
for (j = 0; j < n - i - 1; j++) // **Added n - i - 1**
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
```
more on bubble sort here:Link
|
When I declare or just write a function which takes a 2-dimensionalchar-array in C, Visual Studio tells me I have to put a value in the columns parameter, for example:
```
void board(char mat[][MAX_COLUMNS]);
```
so my question is why do I even need to tell C one dimension of the 2 dimensional array, and why does it have to be the number of columns specifically.
|
Because arrays are not first class objects in C. When you pass an array to a function, itdecaysto a pointer and the callee cannot guess the size. For a 1D array, it still allows to access elements through pointer arithmetics. But for a 2D array (an array of array) pointer arithmetics require that the size of the second level object (here a row) is known. That is the reason why the number of columns must be explicit.
In addition, Microsoft C does not support Variable Length Array, so the number of columns must be a constant.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed4 years ago.
```
int main(){
static int a[20];
int i = 1;
a[i] = i++;
printf("\n %d %d %d \n",a[0],a[1],i);
return 0;}
```
Output is 0,0,2
Why a[1] is not 1 as i is 1.
while if I change i with i++
```
int main(){
static int a[20];
int i = 1;
a[i] = i;
printf("\n %d %d %d \n",a[0],a[1],i);
return 0;}
```
output is 0,1,1
Gcc version is 6.3.0
|
The language does not define whether a[i] is computed before or after i is incremented. Your code therefore has undefined behavior.
|
I am usingNtQueryInformationProcess:ProcessConsoleHostProcessto query the process ID of the conhost.exe process that is associated with a console application in Windows 10 x64. The function returns a success status code, but I always get anodd number, which is always one more than the actual PID. See thescreenshot. My code is complied for x64.
Is there anything wrong with this?
|
From memory, process ids are a multiple of 4. It wouldn't surprise me that the low two bits are being borrowed for some reason.
|
I am attempting to use a variable to store a conditional statement's result:
```
int age = 40;
int validAge = age > 40;
if (validAge) { /* ... */ }
```
Is the above code example allowed in C? If so, what type should I set these conditional variables?
|
This is valid.
The expressionage > 40evaluates to either 0 or 1, so you can use any integer type (char,short,int,long, either signed or unsigned) to store it.
|
If I have this .txt file containing Integers :
```
- //firstRow 14 5
- //secondRow 5
- //fourthRow 3
- //fourthRow 3
```
How can I readsecondIntegerfrom thefirst row?
Thank you
|
fscanf(fptr, "[^\n]", file);
The scanf functions are hard to understand when first encountered. Yourformat string(2nd parameter) is wrong. You want something more like
```
int a, b, n;
while( (n = fscanf(fptr, "%d%d", &a, &b)) != EOF ) {
if( n == 2 ) { ... your code here ... }
}
```
Be prepared to spend time reading the manual.man fscanfis your friend, but takes some time to warm up to.
|
I was trying out some array related stuff in C.
I did following:
```
char a2[4] = {'g','e','e','k','s'};
printf("a2:%s,%u\n",a2,sizeof(a2));
printf("a2[4]:%d,%c\n",a2[4],a2[4]);
```
In thiscode, it prints:
```
a2:geek,4
a2[4]:0,
```
In thiscode, it prints:
```
a2:geek�,4
a2[4]:-1,�
```
Both code run on same online compiler. Then why different output. Is it because the standard defines this case as undefined behavior. If yes, can you point me to exact section of the standard?
|
Yes, this is undefined behavior. I don't have a reference to the standard, but%sformat is for printing null-terminated strings, and you don't have a null terminator ona2. And when you accessa2[4]you're accessing outside the array bounds, another cause of undefined behavior.
Finally, the array initializer also causes undefined behavior, seeIs it ok to have excess elements in array initializer?
|
I am attempting to use a variable to store a conditional statement's result:
```
int age = 40;
int validAge = age > 40;
if (validAge) { /* ... */ }
```
Is the above code example allowed in C? If so, what type should I set these conditional variables?
|
This is valid.
The expressionage > 40evaluates to either 0 or 1, so you can use any integer type (char,short,int,long, either signed or unsigned) to store it.
|
If I have this .txt file containing Integers :
```
- //firstRow 14 5
- //secondRow 5
- //fourthRow 3
- //fourthRow 3
```
How can I readsecondIntegerfrom thefirst row?
Thank you
|
fscanf(fptr, "[^\n]", file);
The scanf functions are hard to understand when first encountered. Yourformat string(2nd parameter) is wrong. You want something more like
```
int a, b, n;
while( (n = fscanf(fptr, "%d%d", &a, &b)) != EOF ) {
if( n == 2 ) { ... your code here ... }
}
```
Be prepared to spend time reading the manual.man fscanfis your friend, but takes some time to warm up to.
|
I was trying out some array related stuff in C.
I did following:
```
char a2[4] = {'g','e','e','k','s'};
printf("a2:%s,%u\n",a2,sizeof(a2));
printf("a2[4]:%d,%c\n",a2[4],a2[4]);
```
In thiscode, it prints:
```
a2:geek,4
a2[4]:0,
```
In thiscode, it prints:
```
a2:geek�,4
a2[4]:-1,�
```
Both code run on same online compiler. Then why different output. Is it because the standard defines this case as undefined behavior. If yes, can you point me to exact section of the standard?
|
Yes, this is undefined behavior. I don't have a reference to the standard, but%sformat is for printing null-terminated strings, and you don't have a null terminator ona2. And when you accessa2[4]you're accessing outside the array bounds, another cause of undefined behavior.
Finally, the array initializer also causes undefined behavior, seeIs it ok to have excess elements in array initializer?
|
So I know that you should declare char arrays to be one element bigger than the word you want to put there because of the\0that has to be at the end, but what about char arrays that I don't want to use as words?
I'm currently writing a program in which i store an array of keyboard letters that have some function assigned to them. Should I still end this array with\0?
|
That is probably not necessary.
A null terminator is not a requirement for arrays ofchar; it is a requirement for "C-strings", things that you intend to use as unitary blobs of data, particularly if you intend to pass them to C API functions. It's the conventional way that the "length" of the string is determined.
But if you just want a collection ofchars to use independently then knock yourself out.
We cannot see your code, but it sounds to me like you don't want or need it in this case.
|
I'm trying to iteratively copy an unsigned char array to a uint_32t variable (in 4 byte blocks), perform some operation on the uint_32t variable, and copy it back to the unsigned char array.
Here's my code:
```
unsigned char byteArray[len]
for (int i=0; i<len; i+=4) {
uint32_t tmpInt = 0;
memcpy(&tmpInt, byteArray+(i*4), sizeof(uint32_t));
// do some operation on tmpInt here
memcpy((void*)(byteArray+(i*4)), &tmpInt, sizeof(uint32_t));
}
```
It doesn't work though. What's wrong, and how can I achieve what I want to do?
|
The problem is that you are adding 4 toiwith each iterationandmultiplying by 4. You should be usingbyteArray + i.
Also, as @WeatherVane pointed out below, your loop would be more consistent with a sizeof():
for (int i = 0; i < len; i += sizeof(uint32_t)).
|
I need to divide a number by 12 using bit shift operations. With multiplication, you can add powers of 2 until you arrive at the desired number, however that approach does not seem to be applicable here.
|
Well know solution fromHackers Delightby using shift operation
```
unsigned divu12(unsigned n) {
unsigned q, r;
q = (n >> 1) + (n >> 3);
q = q + (q >> 4);
q = q + (q >> 8);
q = q + (q >> 16);
q = q >> 3;
r = n - q*12;
return q + ((r + 4) >> 4);
// return q + (r > 11);
}
```
Hope this helps you
|
```
extern int aabbcc;
void fun1()
{
aabbcc = 1;
}
```
compile it with mingw
```
i686-w64-mingw32-gcc -shared -o a.dll a.c
```
reports error: undefined reference to 'aabbcc'
compile it with linux gcc, it is ok
```
gcc -fPIC -shared -o liba.so a.c
```
WHY ? what is the different between linux-gcc and mingw ?
|
In Linux, .so files are allowed to have undefined references. When the .so is loaded into a process, it tries to find the reference in any other .so or the main program. The .so doesn't even have to know where the referenced object is located.
In Windows, .dll files are not allowed to have undefined references. The .dll has to either define the referenced object itself, or tell the loader which other .dll to find the object in.
|
I’ve written a small database engine in C that works by reading commands you input in the console and it outputs the result.
Is there any way of me writting some PHP code that could send arguments to the console and recieve the output back to PHP without restarting the compiled program.
Is there a better way of doing this?
|
You say you want the PHP to send and receive messages to your programwithout restartingthe compiled program.
So I don't think using shell_exec or proc_open will work how you want, since these commands both load a fresh instance of the compiled program.
Instead, I suggest you look intosockets, and how you would rewrite your database engine to use those instead of STDIN/STDOUT. Then you can use PHP'ssocket functionsto communicate between your applications. And you'll have just one instance of your compiled program running in the background, even with multiple hits to your PHP script.
|
I am trying to print starts like Image attached in nested for loop, but after writing code, I am getting the result like below
Following is code
```
int main() {
int height = 5, y, z;
for(int x=1; x<=height; x++)
{
for(y=1;y<=x;y++)
printf("*");
for(z=height-(2*x);z>0;z=z-2)
printf(" ");
for(y=1;y<=x;y++)
printf("*");
printf("\n");
}
}
```
The result is following, but I need exact print like showing in the image.
```
* *
** **
******
********
**********
```
|
I guess you just got the middle section wrong. Try this to print the spaces:
```
for(z=0 ;z < height - x; ++z)
printf(" "); // <- Notice there are 2 spaces being printed here.
```
|
I don't know what use case it might be. I was just wondering if a function would ever appear on the left side of the assignment in C/C++. Just as an example, of course it is wrong,swap(x,y) = 100;
|
It seems that you can do that using references. In C++, that is, there are no references in C.
```
#include <iostream>
int a = 0;
int& swap(int x, int y) {
return a;
}
int main()
{
int x = 0, y = 0;
swap(x, y) = 100;
std::cout << "a is " << a << std::endl;
return 0;
}
```
|
I'm trying to iteratively copy an unsigned char array to a uint_32t variable (in 4 byte blocks), perform some operation on the uint_32t variable, and copy it back to the unsigned char array.
Here's my code:
```
unsigned char byteArray[len]
for (int i=0; i<len; i+=4) {
uint32_t tmpInt = 0;
memcpy(&tmpInt, byteArray+(i*4), sizeof(uint32_t));
// do some operation on tmpInt here
memcpy((void*)(byteArray+(i*4)), &tmpInt, sizeof(uint32_t));
}
```
It doesn't work though. What's wrong, and how can I achieve what I want to do?
|
The problem is that you are adding 4 toiwith each iterationandmultiplying by 4. You should be usingbyteArray + i.
Also, as @WeatherVane pointed out below, your loop would be more consistent with a sizeof():
for (int i = 0; i < len; i += sizeof(uint32_t)).
|
I need to divide a number by 12 using bit shift operations. With multiplication, you can add powers of 2 until you arrive at the desired number, however that approach does not seem to be applicable here.
|
Well know solution fromHackers Delightby using shift operation
```
unsigned divu12(unsigned n) {
unsigned q, r;
q = (n >> 1) + (n >> 3);
q = q + (q >> 4);
q = q + (q >> 8);
q = q + (q >> 16);
q = q >> 3;
r = n - q*12;
return q + ((r + 4) >> 4);
// return q + (r > 11);
}
```
Hope this helps you
|
```
extern int aabbcc;
void fun1()
{
aabbcc = 1;
}
```
compile it with mingw
```
i686-w64-mingw32-gcc -shared -o a.dll a.c
```
reports error: undefined reference to 'aabbcc'
compile it with linux gcc, it is ok
```
gcc -fPIC -shared -o liba.so a.c
```
WHY ? what is the different between linux-gcc and mingw ?
|
In Linux, .so files are allowed to have undefined references. When the .so is loaded into a process, it tries to find the reference in any other .so or the main program. The .so doesn't even have to know where the referenced object is located.
In Windows, .dll files are not allowed to have undefined references. The .dll has to either define the referenced object itself, or tell the loader which other .dll to find the object in.
|
We're running Win10 LTS-B.
Using SMB shares and no domain.
The user is able to access the remote share using file explorer.
But the signed executable which runs as the same user
fails with code 5 'access denied' when calling the function "netShareEnum".
The code is a direct copy from the msdn example.https://learn.microsoft.com/en-us/windows/desktop/api/lmshare/nf-lmshare-netshareenum
When starting the executable,
The remote systen with the SMB share shows in the Eventlog "security" a successful login, and approx 10 seconds later a logoff entry.(seems triggered by my call)
So something else is wrong.
I dont know where to look next..
I also enabled dcom/ole access- and failure-logging on the remote system in the hope of finding something, but nothing.
|
I found it ! :) It was because someone pressed [cancel] on the next popup
|
I want to use ffmpeg's transcoding features multiple times in my program. This can be achieved by doing
```
ffmpeg -i input output
```
in a terminal. I believe I can use some shell or C code to execute these commands programmatically.
I could also directly use ffmpeg's c libraries to do this. My question is, will there be a noticeable performance difference between the 2 approaches? Obviously the first will be simpler to implement, but will I pay a big performance cost?
|
It's quite typical these days to use the executable (system()) version even on mobile phones. If time-to-start is not critical for you, don't bother. If it is, consider making ffmpeg executable available for immediate start, e.g. withprelink.
|
I came across this question and expected it to show up as a compile time error but to my surprise each statement separated by comma is executed and the final value is assigned to the variable.
```
int a,b=5;
a=(b++,++b,b*4,b-3);
printf("%d",a);
Output is 4
```
This output is exactly what should be the printed when each of those comma separated statements are executed separately. What I am not understanding is how and why does C allow this and how does compiler process this.
|
SeeWhat does the comma operator , do?
After understanding how the comma operator works, we can tell that this code is equivalent to:
```
int a,b=5;
b++;
++b;
b*4; // nonsense, the result isn't stored anywhere
a=b-3;
printf("%d",a);
```
5 + 1 + 1 - 3 = 4. Theb*4part does nothing and is just obfuscation.
|
I was going through the Linux Kernel code and found below line. What do the square brackets mean?
```
#define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
```
From:https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/kernel/bpf/disasm.c#n18
It's used like this:
```
static const char * const func_id_str[] = {
__BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
};
```
|
In c99, a syntax was introduced for designated initializers. The square bracket syntax is for array initialization. So the line:
```
int a[] = { [10] = 4 };
```
will create an arrayathat can hold 11ints, and initializesa[10]to 4, and the rest of its members initialized to 0.
|
I'm developing an Android Studio project with JNI code, and I added a .c and .h source file manually to the project. However, Android Studio informs me that the file is not part of the project. I Googled a bit and the solution seems to be to include it in Android.mk, but I did a search for that file and there are multiple such files on my Windows system, so I'm not sure which to change.
Help please?
|
I figured it out. I had to add the .c file (full path) to my CMakeLists.txt as a separate line under add_library, and then it worked.
|
How can I show theprintfstatements inrpl-of0.cin the mote output window like the way we can see theprintfstatements inrpl-icmp6.c? I have triedDEBUG_PRINTandDEBUG_FULLbut to no avail.
|
replace#define DEBUG DEBUG_NONEwith#define DEBUG DEBUG_PRINT
|
How can I use unifdef on a directory recursively.
The following command removes code around DEFINE_NAME on a given file.
I would like to remove code from all files under a directory.
```
unifdef -UDEFINE_NAME filename
```
|
If you've got GNU findutils, you can usefindto execute commands with found files whose name ends with.cor.h:
```
% find -name '*.[ch]' -exec unifdef -m -UDEFINE_NAME '{}' ';'
```
execgets a command that will have a filename substituted,{}is the place where a found filename is substituted, and;ends the command.
On the other hand if you usezshas your shell, you can use a recursive glob:
```
% unifdef -m -UDEFINE_NAME **/*.[ch]
```
Notice that you need-mto actually modify the file in place.
|
I expected results are same. Two functions do same thing butwhy they are different?I think its related to pointers.
```
void changer(int n){
n = 20;
}
void arrayChanger(int n[]){
n[0] = 20;
}
int main()
{
int a = 5;
int ar[1] = {5};
changer(a);
arrayChanger(ar);
printf("%d\n",a);
printf("%d\n",ar[0]);
return 0;
}
```
|
Arguments are passedby valueunless the argument is specifically declared to be passedby reference, and arrays will decay to a pointer to their first element when passed to functions.
The functionchangerdoes not update the actual variableasince it only receives its value, not the variable itself.
If you want to update a value in a function call, you need to pass it by reference:
```
void make20(int *a)
{
*a = 20;
}
```
The call would then look like:
```
int n = 5;
make20(&n);
// now n = 20
```
|
this program prints out -8 -4 but i wanna know why and why isn't the compiler showing an error about which function to use? why are the results different.
i don't know much about defining a function like this can someone explain this too
```
#include <stdio.h>
#include <stdlib.h>
int foo(int x, int y);
#define foo(x, y) x/y + x
int main() {
int i = -6, j = 3;
printf("%d ", foo(i + j, 3));
#undef foo
printf("%d\n", foo(i + j, 3));
}
int foo(int x, int y) {
return x/y + x;
}
```
|
If you preprocess the call to the macrofoo, you get:
```
i + j / 3 + i + j
```
With your values, that's
```
(-6) + 3 / 3 + (-6) + 3
```
Which evaluates to-8.
When you undefine the macrofoo, you get the functionfooinstead, where the linereturn x + y / xis executed.
Withi = -6andj = 3, you get:
```
(-3) / 3 + -3
```
Which is-4.
Further reading:
Operator Precedence in C#defines are EVIL
|
I have a small file containing numbers, separated by new lines/spaces.
I am looking for a way to scan the file , but in reverse.
```
Input: 1 2 3 4 5 1025
Output: 1025 5 4 3 2 1
```
Attention! in the following code, I need to modify the scanf. I need to leave printf unchanged! I don't need to transform 1024 into 4201, the integers remain unchanged. Only their order changes.
Code:
```
while (fscanf(input,"%d", &b) && !feof(input)) {printf("%d",b);}
```
|
Do you have a big enough stack?
```
void printreverse(FILE *f) {
int n;
if (fscanf(f, "%d", &n) != 1) return;
printreverse(f); // recursive call
printf("%d", n);
}
```
https://ideone.com/1jejpM
|
I am reading K&R and one of the code counts words. I decided to try and make my own version of the code, but with my current code the EOF (Ctrl+Das I am on Linux) isn't working.
```
#include <stdio.h>
int main(void) {
int c, wc = 0;
while((c = getchar()) != EOF) {
while(c != ' ' && c != '\t' && c != '\n') {
wc++;
}
}
printf("%d", wc);
return 0;
}
```
|
The following example is a bit closer to countingwords:
```
#include <stdio.h>
int main(void) {
int c, wc = 0;
int sep = 1;
while((c = getchar()) != EOF) {
if (c != ' ' && c != '\t' && c != '\n') {
if ( sep ){
wc++;
sep = 0;
}
}
else
sep = 1;
}
printf("%d", wc);
return 0;
}
```
|
I'm working on a basic SIC assembler and one of the features that I'm trying to implement is that during a dump function, if the program generates more than a page of text on the console, it would prompt the user to press a key before continuing.
My dump function reads out the hex values of a range of addresses in memory.
|
First you need to define what a "page" is. Then you will know how many lines are available. Then when printing you stop to get input every X lines (where X is the number of lines per page) before continuing printing the next X lines.
Because reading input will block until the user presses theEnterkey (normally) then it will seem like your program pauses.
|
I'm working on a basic SIC assembler and one of the features that I'm trying to implement is that during a dump function, if the program generates more than a page of text on the console, it would prompt the user to press a key before continuing.
My dump function reads out the hex values of a range of addresses in memory.
|
First you need to define what a "page" is. Then you will know how many lines are available. Then when printing you stop to get input every X lines (where X is the number of lines per page) before continuing printing the next X lines.
Because reading input will block until the user presses theEnterkey (normally) then it will seem like your program pauses.
|
```
#define IRQ_HANDLER(name) void name(); \
asm(#name ": pusha \n call _" #name " \n movb $0x20, %al \n outb %al, $0x20 \n outb %al, $0xA0 \n popa \n iret"); \
void _##name()
```
What does_##name()mean? I know that#namemeans"name", but what is##name?
|
#is the stringize preprocessor operator
##is the token pasting or token concatenation preprocessor operator. When the macro is expanded both sides of##are combined and make one identifier. Such that in your example the_will be concatenated to the name given in argument to the macro.
|
I am trying to make a new programming language, and I am trying to add the&(pointer-to) operator from C. What exactly does it do? That is, how does it 'create' a pointer? Why can't it create a pointer to a constant1? My current implementation of the operator is as follows, but it also works on constants, so I assume it is not how the C operator works:
```
operator & (any one argument):
temp = allocate (typeof argument)
store argument in temp
return temp
```
1: example program:
```
int main(){
int* x;
x = &1;
}
```
gccoutput:
```
ptr.c: In function ‘main’:
ptr.c:3:6: error: lvalue required as unary ‘&’ operand
x = &1;
```
|
C's unary&gives you the address of the thing it's applied to.
So for example,&xgives the address ofx.
It doesn't create a new variable, copy x into that variable and then return the address of the new variable. It returns the address ofx, plain and simple.
|
I'm trying to create a folder using mkdir in C but it wont't work
the code won't create the folders
```
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
int main (){
char chemin[256];
char name[20];
//char fichier[100];
// FILE *fp;
strcpy(chemin,"/home/Deva/Documents/prog/C/la/sds");
mkdir(chemin,0755);
if (mkdir(chemin,0755)==-1){
printf("\nERROR\n");
} else { printf("fichier creer"); }
}
```
|
You have to create the intermediate directories first: e.g. you must create /home/Deva before creating /home/Deva/Documents, etc.
|
I have this script written:
```
#include <stdio.h>
#include <string.h>
int main(void)
{
int k = 65;
char key[1];
printf("%s\n", key);
key[0] = k;
printf("%s\n", key);
}
```
The first printf() gives nothing as expected. But the second one prints 'AA' instead of just A. What is the reason for this? I want it only to print A. Thanks for your help.
|
changeprintf("%s\n", key);to:
```
printf("%c\n", *key);
```
to print only the char
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed4 years ago.Improve this question
I have a MakeFile file in the following way:
```
conf:
cd teste
nano teste
```
However, when i executemake conf, he does not enter in the directory that i specified. How can i access different directories with makefile?
|
Each command in a makefile recipe acts in its own sub-shell. The first command begins in the working directory, entersteste/and dies; the second command begins in the working directory, and fails.
Here is one solution:
```
conf:
cd teste; nano teste
```
|
I want to turn mychar **argvinto anotherchar **but exclude the first element (which in my case is always going to be the program name)
I thought&argv[1]would work, but I get seg faults now.
So like in python, all but the first element of a list can be done like this
```
>>> argv = [1, 2, 3]
>>> argv[1:]
[2, 3]
```
I want to getargv[1:]but in C.
|
You can manipulatechar** argvusing standard pointer arithmetics:
```
char** arguments_from_second_onwards = argv + 1;
char* second_argument = *(argv + 1);
assert(argv[1] == arguments_from_second_onwards[0]);
```
|
I have made a header file with the following code :
```
#if C //this code will execute if header file is included in .c file
struct something{
};
#endif
#if CPP //this code will be executed if header file is included in .cpp file
class something {
}
#endif
```
This header file can be included by both .c and .cpp file. What should I do to execute the respective code snippet?
|
This is what the__cplusplusmacro is for.
```
#ifdef __cplusplus
// C++ code
#else
// C code
#endif
```
|
Here's an example:
```
char x[20] = "aa";
int y = 2;
if(y==2) {
x[20] = "bb";
}
printf("%s",x);
```
If we run this code aa gets printed instead of bb, is there a way to change the value of x from the if statement?
|
You have to copy the stringbbinto the stringx, by usingstrcpy():
```
strcpy(x, "bb");
```
xwould be a character if it was something like thischar x = 'a';. Notice the single quotes (used for a character), instead of double quotes (used for a string). In the character case, the assignment operator, would indeed work.
|
We know that for character arrays we have the '\0' to identify its end, what about other types of arrays?
I presume it's not a special character such as the '\0' since to declare an integer array of n elements for example you just allocate n * sizeof(int), yet for a character array we account for the '\0'.
|
C arrays don't have an end marker.
It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size.
If you do access an element outside the allocated size, the result isundefined behaviour.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed4 years ago.Improve this question
I have a MakeFile file in the following way:
```
conf:
cd teste
nano teste
```
However, when i executemake conf, he does not enter in the directory that i specified. How can i access different directories with makefile?
|
Each command in a makefile recipe acts in its own sub-shell. The first command begins in the working directory, entersteste/and dies; the second command begins in the working directory, and fails.
Here is one solution:
```
conf:
cd teste; nano teste
```
|
I want to turn mychar **argvinto anotherchar **but exclude the first element (which in my case is always going to be the program name)
I thought&argv[1]would work, but I get seg faults now.
So like in python, all but the first element of a list can be done like this
```
>>> argv = [1, 2, 3]
>>> argv[1:]
[2, 3]
```
I want to getargv[1:]but in C.
|
You can manipulatechar** argvusing standard pointer arithmetics:
```
char** arguments_from_second_onwards = argv + 1;
char* second_argument = *(argv + 1);
assert(argv[1] == arguments_from_second_onwards[0]);
```
|
I have made a header file with the following code :
```
#if C //this code will execute if header file is included in .c file
struct something{
};
#endif
#if CPP //this code will be executed if header file is included in .cpp file
class something {
}
#endif
```
This header file can be included by both .c and .cpp file. What should I do to execute the respective code snippet?
|
This is what the__cplusplusmacro is for.
```
#ifdef __cplusplus
// C++ code
#else
// C code
#endif
```
|
Here's an example:
```
char x[20] = "aa";
int y = 2;
if(y==2) {
x[20] = "bb";
}
printf("%s",x);
```
If we run this code aa gets printed instead of bb, is there a way to change the value of x from the if statement?
|
You have to copy the stringbbinto the stringx, by usingstrcpy():
```
strcpy(x, "bb");
```
xwould be a character if it was something like thischar x = 'a';. Notice the single quotes (used for a character), instead of double quotes (used for a string). In the character case, the assignment operator, would indeed work.
|
We know that for character arrays we have the '\0' to identify its end, what about other types of arrays?
I presume it's not a special character such as the '\0' since to declare an integer array of n elements for example you just allocate n * sizeof(int), yet for a character array we account for the '\0'.
|
C arrays don't have an end marker.
It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size.
If you do access an element outside the allocated size, the result isundefined behaviour.
|
so if i run this code it will give the expected answer of9
```
int main()
{
int a[]={9,8,7,6,5,4,3,2,1};
int n=sizeof(a)/sizeof(a[0]); printf("%d", n);
}
```
but if i changesizeof(a[0])tosizeof(&a[0])..then the output is4Why does this happen? Exactly what does the computer 'think' when it is givensizeof(&a[0])?
|
&a[0]on an arrayain C yields the address of its first element. On a 16-bit system,sizeofof that address is most likely 2, on a 32-bit system,sizeofthat address it is 4, and, on a 64-bit system, it is 8.
|
Why does-fsanitize=undefinedthrow
runtime error: left shift of 1 by 31 places cannot be represented in type 'int'
on this code
```
uint32_t z;
z = 1 << 31;
```
?
|
Make the 1 unsigned:
```
uint32_t z;
z = UINT32_C(1) << 31;
```
|
I'm not sure if this is something GCC is correcting during compilation, but I can't find a definite answer as to which call is correct forpthread_create. I've seen both formats used in tutorials, however it seems that one should fail (unless the compiler is doing something behind the scenes to put it in the right format):
```
pthread_create (&thread, NULL, thread_func, (void *) var);
```
OR
```
pthread_create (&thread, NULL, &thread_func, (void *) var);
```
Notice the first call passes in the function pointer, whereas the second passes in the address to the function pointer. It seems like one should break, but both compile and execute correctly.
thread_func def:
```
void *thread_func (void *var);
```
|
The function will decay to a function pointer hence both works the same.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed4 years ago.Improve this question
How can I call a function that has printf in it - in printf BUT without it printing the value entered twice?
in the code written below is how it is now, it prints the inserted value.
can I just use the function without printing the value again?
can I use printf(roll(num))
```
#include<stdio.h>
int roll(int);
int main()
{
int num;
printf("%d",roll(num));
return 0;
}
int roll(int a)
{
printf("Enter a number between 1-6:\n");
scanf("%d",&a);
while(a<1 || a>6)
{
printf("Wrong input! please enter a number between 1-6:\n");
scanf("%d",&a);
}
return a;
}
```
|
Just call the function without printf.
```
roll(num);
```
|
from now I have ach[5]stored{'a','b','c','d','e'}
I have another array char loadtext[i];
which will store many strings.;
likeloadtext[0] = "abced"
how can append the five char together;
I have tried;
```
for(i = 0; i < 5; i++){
strcat(loadtext[0],ch[i];
}
```
but ir return erorrs
```
[Warning] passing argument 1 of 'strcat' makes pointer from integer without a cast
```
How can I solve it?
|
Thestrcatfunction is used to copy strings. You're not copying strings but individual characters, so just assign the values directly:
```
for(i = 0; i < 5; i++){
loadtext[0][i] = ch[i];
}
loadtext[0][5] = '\0';
```
Note also that we add a null byte to the end ofloadtext[0]to make the array of characters a string.
|
I have a text file of 257 points like this
```
3.78135
2.84681
2.81403
2.54225
3.10854
...
```
and I would like to read this data and copy them into an array. With the help of similar answered question I wrote this:
```
#include<stdio.h>
#include<stdlib.h>
int max_read = 258;
double phi[max_read];
FILE *stream;
stream = fopen("namefile.txt", "r");
if (stream == NULL) {
print ("! Cannot open file %sn", "namefile.txt\n");
exit(1);
} else{
int m = 0;
while(m<max_read) {
phi[m] = // But I still don't know how write the correct value into the array.
m++;
}
}
```
I also would like to do this reading-coping procedure until the end of file.
|
This should do the trick i think.
```
if (stream == NULL) {
fprint("! Cannot open file %sn", "namefile.txt\n");
exit(1);
} else{
int m = 0;
while (fscanf(stream, "%lf\n", &phi[m])){
m++;
}
}
```
|
how do i understand something like this
typedef void string(char * str,int num);
string * stringptr;
isstringptra function pointer that point to a funtion likestring
|
The typedef defines a function type. It is not terribly useful in itself, but it allows us to declare a function pointer to that type, just as we declare a normal object pointer. And that's whatstring * stringptr;does - declaring a function pointer to a function of the formvoid string(char * str,int num);
|
I have a main.c code (cannot be changed) :
```
int main() {
uint8_t *param ;
param = func(key) ;
}
```
Key is an array of 16 elements and func is declared in a stud.c that is linked to main by stud.h. the func() is declared as follows
```
void *func(void *key){//some code}
```
Now how can i print param ? i have tried multiple options with printf . Is there any suggestion plZ ? I need the param as an array of 16 elements in hex format also. I cannot change anything in main.c (i cannot change any type!!!)
```
for(int j = 0; j < 16; j++) {
printf("%02X ", param[j]);
}
printf("\n");
```
|
```
for(int i = 0; i < 16; ++i) {
printf("%02" PRIu8 "\n", param[i]);
}
```
since your array is of typeuint8_t.
Do not forget to#include <inttypes.h>.
Read more inGood introduction to <inttypes.h>, where other naming conventions are explained, e.g.PRIx8if you want to print the hexadecimal value.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this question
Which of the following is not equivalent to the other two? Please tell me when it isn't output different from the other two.
```
while (i<10) {...}
for (;i<10:) {...}
do {...} while (i<10);
```
I'll appreciate it for your answer.
|
The last one is different from the first two! Ifi==15, then the first two are not executed at all, while thedo {}block gets executed once.
|
from now I have ach[5]stored{'a','b','c','d','e'}
I have another array char loadtext[i];
which will store many strings.;
likeloadtext[0] = "abced"
how can append the five char together;
I have tried;
```
for(i = 0; i < 5; i++){
strcat(loadtext[0],ch[i];
}
```
but ir return erorrs
```
[Warning] passing argument 1 of 'strcat' makes pointer from integer without a cast
```
How can I solve it?
|
Thestrcatfunction is used to copy strings. You're not copying strings but individual characters, so just assign the values directly:
```
for(i = 0; i < 5; i++){
loadtext[0][i] = ch[i];
}
loadtext[0][5] = '\0';
```
Note also that we add a null byte to the end ofloadtext[0]to make the array of characters a string.
|
I have a text file of 257 points like this
```
3.78135
2.84681
2.81403
2.54225
3.10854
...
```
and I would like to read this data and copy them into an array. With the help of similar answered question I wrote this:
```
#include<stdio.h>
#include<stdlib.h>
int max_read = 258;
double phi[max_read];
FILE *stream;
stream = fopen("namefile.txt", "r");
if (stream == NULL) {
print ("! Cannot open file %sn", "namefile.txt\n");
exit(1);
} else{
int m = 0;
while(m<max_read) {
phi[m] = // But I still don't know how write the correct value into the array.
m++;
}
}
```
I also would like to do this reading-coping procedure until the end of file.
|
This should do the trick i think.
```
if (stream == NULL) {
fprint("! Cannot open file %sn", "namefile.txt\n");
exit(1);
} else{
int m = 0;
while (fscanf(stream, "%lf\n", &phi[m])){
m++;
}
}
```
|
So, I'm trying to compile my C code using the command "gcc -o file file.c", but I get "error: libnet.h: No such file or directory" I included libnet.h (#include ) and I also installed libnet. I'm running CentOS 7.
|
yum install libnetonly installs the precompiled library.
You need to install the headers usingyum install libnet-develbefore you can use it in your own software.
|
This question already has answers here:Difference between putchar(), putch(), fputchar()?(3 answers)Closed4 years ago.
I have searched a lot on internet but I coudln't find any difference apart from the fact that both come from different libraries. So what exactly are the differences betweenputch()andputchar()in c?
|
putchar(): This function is used to print one character on the screen, and this may be any character from C characterset(i.e it may be printable or non printable characters).
putch(): The putch() function is used to display all alphanumeric characters throught the standard output device like monitor. this function display single character at a time.
|
It's a long time since I did any coding of any sort.
I'm trying to remember the name (in C) of an item you put at the beginning of your code that allows compilation to a constant for efficiency but can have its value adjusted before compilation if necessary.
What is it called? (specifically the name in C and optionally the name in general)
Thanks.
|
#definestatements allow you to define a constant at the beginning of your code.
|
So, I'm trying to compile my C code using the command "gcc -o file file.c", but I get "error: libnet.h: No such file or directory" I included libnet.h (#include ) and I also installed libnet. I'm running CentOS 7.
|
yum install libnetonly installs the precompiled library.
You need to install the headers usingyum install libnet-develbefore you can use it in your own software.
|
This question already has answers here:Difference between putchar(), putch(), fputchar()?(3 answers)Closed4 years ago.
I have searched a lot on internet but I coudln't find any difference apart from the fact that both come from different libraries. So what exactly are the differences betweenputch()andputchar()in c?
|
putchar(): This function is used to print one character on the screen, and this may be any character from C characterset(i.e it may be printable or non printable characters).
putch(): The putch() function is used to display all alphanumeric characters throught the standard output device like monitor. this function display single character at a time.
|
It's a long time since I did any coding of any sort.
I'm trying to remember the name (in C) of an item you put at the beginning of your code that allows compilation to a constant for efficiency but can have its value adjusted before compilation if necessary.
What is it called? (specifically the name in C and optionally the name in general)
Thanks.
|
#definestatements allow you to define a constant at the beginning of your code.
|
From the StandardN15706.7.8:
Atypedefdeclaration does not introduce a new type, only a synonym
for the type so specified.
So I expected that it is not possible to write something like this:
```
typedef t;
t *t_ptr;
```
and it should fail to compile since no type to introduce a synonym to provided. But it is fine:Demo. So what does this ever mean and why does it compile?
|
This relies on the fact that, missing type specification defaults toint.
So, your statement
```
typedef t;
```
is the same as
```
typedef int t;
```
With the proper level of warning, compiler emits warning:
```
warning: type defaults to ‘int’ in declaration of ‘t’ [-Wimplicit-int]
typedef t;
^
```
That said,do notrely on this behaviour, "implicit int" rule has been obsolete sinceC99.
|
I have a pattern
"^\+?\d{3,20}$"
Test on "123455", "+123445", expected match.Test on "123+213", "abc", expect no match.
This pattern worked onpcre_exec()but not onregexec().
|
Theregexec()function implementsPOSIX Basic Regular Expressions (BRE) and Extended Regular Expressions (ERE).
Thepcre_exec()function implementsPerl-Compatible Regular Expressions, which are a major superset of the ERE (seeperlrefor Perl's specification of Perl's REs).
The\dnotation is not special to POSIX ERE (let alone BRE); it does not mean 'a digit'. It does mean 'a digit' in PCRE. If you want the regular expression to work in both dialects, you'll need to use[0-9]in place of\d, and ensureregcomp()is told to compile an ERE.
```
"^+?[0-9]{3,20}$"
```
|
I created some utilities which
help me to handle the management of a DinamicList. In the section that I
use to handle the removing of a element in a list, if there is
a element added that is stored in the stack, when I callfree()an undefined behaviour is reached.
Surfing on the net I found out
that there aren't ways to determine whether a pointer points to stack
memory or heap memory.
So I think that to solve this problem I have to handle
the error generated fromfree(). Is there a way to handle that exception when I callfree()?
|
No.
You need to not callfree()for non heap pointers. Easiest way is let whoever allocated the memory take care of freeing it. I.e. your utilities look after whatever memory they allocate but someone else looks after the memory passed to your utilities.
|
From the StandardN15706.7.8:
Atypedefdeclaration does not introduce a new type, only a synonym
for the type so specified.
So I expected that it is not possible to write something like this:
```
typedef t;
t *t_ptr;
```
and it should fail to compile since no type to introduce a synonym to provided. But it is fine:Demo. So what does this ever mean and why does it compile?
|
This relies on the fact that, missing type specification defaults toint.
So, your statement
```
typedef t;
```
is the same as
```
typedef int t;
```
With the proper level of warning, compiler emits warning:
```
warning: type defaults to ‘int’ in declaration of ‘t’ [-Wimplicit-int]
typedef t;
^
```
That said,do notrely on this behaviour, "implicit int" rule has been obsolete sinceC99.
|
I have a pattern
"^\+?\d{3,20}$"
Test on "123455", "+123445", expected match.Test on "123+213", "abc", expect no match.
This pattern worked onpcre_exec()but not onregexec().
|
Theregexec()function implementsPOSIX Basic Regular Expressions (BRE) and Extended Regular Expressions (ERE).
Thepcre_exec()function implementsPerl-Compatible Regular Expressions, which are a major superset of the ERE (seeperlrefor Perl's specification of Perl's REs).
The\dnotation is not special to POSIX ERE (let alone BRE); it does not mean 'a digit'. It does mean 'a digit' in PCRE. If you want the regular expression to work in both dialects, you'll need to use[0-9]in place of\d, and ensureregcomp()is told to compile an ERE.
```
"^+?[0-9]{3,20}$"
```
|
I created some utilities which
help me to handle the management of a DinamicList. In the section that I
use to handle the removing of a element in a list, if there is
a element added that is stored in the stack, when I callfree()an undefined behaviour is reached.
Surfing on the net I found out
that there aren't ways to determine whether a pointer points to stack
memory or heap memory.
So I think that to solve this problem I have to handle
the error generated fromfree(). Is there a way to handle that exception when I callfree()?
|
No.
You need to not callfree()for non heap pointers. Easiest way is let whoever allocated the memory take care of freeing it. I.e. your utilities look after whatever memory they allocate but someone else looks after the memory passed to your utilities.
|
```
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
main() {
int n,counter=0,choice;
srand(time(NULL));
n = rand() % 10 + 1;
printf("Geuss My Number\n");
while(1){
counter++;
scanf("%d" ,&n);
if(n==choice){
printf("Correct You Guessed It in %d Tries\n" ,counter);
break;
}
else if (n>choice) printf("Too High\n");
else printf("Too Low\n");
}
```
}
So, for example, everytime I run the program, the random number is always the same it does not change.
|
I think you meant this;
```
scanf("%d" ,&n); --> scanf("%d" ,&choice);
```
|
6.3.1.1p2says
The following may be used in an expression wherever anintorunsigned intmay be used:An object or expression with an integer type (other thanintorunsigned int) whose integer conversion rank is less than or equal to the rank ofintandunsigned int.A bit-field of type_Bool,int,signed int, orunsigned int.
What's the intention behind the second bullet point?
Why leave out integer fields of other types whose rank is less than that ofint?
Does it mean that I can do e.g.:
```
printf("%d\n", (struct{ _Bool x:1; }){0}.x);
```
but not:
```
printf("%d\n", (struct{ unsigned short x:1; }){0}.x);
```
|
Presumably this is because of6.7.2.1p5:
A bit-field shall have a type that is a qualified or unqualified version of_Bool,signed int,unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted.
I.e. you can't portably create bit-fields of other types anyway.
|
I want to generate on Windows a file (script) for UNIX. So I need to output justLFcharacters, without outputtingCRcharacters.
When I dofprintf(fpout, "some text\n");, character\nis automatically replaced by\r\nin the file.
Is there a way to output specifically just\n(LF) character?
The language is C++, but the I/O functions come from C.
|
You can open the file in binary mode, e.g.
```
FILE *fpout = fopen("unixfile.txt", "wb");
fprintf(fpout, "some text\n"); // no \r inserted before \n
```
As a consequence, every byte you pass tofprintfis interpreted as a byte and nothing else, which should omit the conversion from\nto\r\n.
From cppreference onstd::fopen:
File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of '\n' and '\x1A'.
|
So im trying to make a program that inputs grade using arrays, this is the main loop. The problem is that it successfully asks the input but after the 5th student, 1st subject, it crashes, where did I go wrong???
crash starts when studloop=4; gradloop=2
```
float data[4][7];
for(studLoop = 0; studLoop < 5; studLoop++){
ave=0;
printf("\nStudent %d ID#", studLoop+1);
data[studLoop][0] = inputNum();
for(gradLoop = 1; gradLoop < 7; gradLoop++){
printf("Subject %d: ", gradLoop);
data[studLoop][gradLoop] = inputNum();
gradLoop = checkGrade(data[studLoop][gradLoop], gradLoop, ave);
}
data[studLoop][7] = ave / 6;
printf("press any key to continue...");
getch();
system("cls");
}
```
|
Well since you're trying to store 5 students and 7 grades for each, then this:
```
float data[4][7];
```
should be
```
float data[5][7];
```
|
Is there a possibility to split large.afiles into multiple smaller ones?
I'm currently having an issue with a.afile being multiple GiB large and GCC raises an error even with the flag-mcmodel=medium.
|
Use binutils tool "ar":
```
ar -x libbig.a
```
for extracting the objects from the archive and
```
ar -r libsmall.a obj1.o obj2.o obj3.o
```
for creating a new archive.
|
6.3.1.1p2says
The following may be used in an expression wherever anintorunsigned intmay be used:An object or expression with an integer type (other thanintorunsigned int) whose integer conversion rank is less than or equal to the rank ofintandunsigned int.A bit-field of type_Bool,int,signed int, orunsigned int.
What's the intention behind the second bullet point?
Why leave out integer fields of other types whose rank is less than that ofint?
Does it mean that I can do e.g.:
```
printf("%d\n", (struct{ _Bool x:1; }){0}.x);
```
but not:
```
printf("%d\n", (struct{ unsigned short x:1; }){0}.x);
```
|
Presumably this is because of6.7.2.1p5:
A bit-field shall have a type that is a qualified or unqualified version of_Bool,signed int,unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted.
I.e. you can't portably create bit-fields of other types anyway.
|
I want to generate on Windows a file (script) for UNIX. So I need to output justLFcharacters, without outputtingCRcharacters.
When I dofprintf(fpout, "some text\n");, character\nis automatically replaced by\r\nin the file.
Is there a way to output specifically just\n(LF) character?
The language is C++, but the I/O functions come from C.
|
You can open the file in binary mode, e.g.
```
FILE *fpout = fopen("unixfile.txt", "wb");
fprintf(fpout, "some text\n"); // no \r inserted before \n
```
As a consequence, every byte you pass tofprintfis interpreted as a byte and nothing else, which should omit the conversion from\nto\r\n.
From cppreference onstd::fopen:
File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of '\n' and '\x1A'.
|
So im trying to make a program that inputs grade using arrays, this is the main loop. The problem is that it successfully asks the input but after the 5th student, 1st subject, it crashes, where did I go wrong???
crash starts when studloop=4; gradloop=2
```
float data[4][7];
for(studLoop = 0; studLoop < 5; studLoop++){
ave=0;
printf("\nStudent %d ID#", studLoop+1);
data[studLoop][0] = inputNum();
for(gradLoop = 1; gradLoop < 7; gradLoop++){
printf("Subject %d: ", gradLoop);
data[studLoop][gradLoop] = inputNum();
gradLoop = checkGrade(data[studLoop][gradLoop], gradLoop, ave);
}
data[studLoop][7] = ave / 6;
printf("press any key to continue...");
getch();
system("cls");
}
```
|
Well since you're trying to store 5 students and 7 grades for each, then this:
```
float data[4][7];
```
should be
```
float data[5][7];
```
|
Is there a possibility to split large.afiles into multiple smaller ones?
I'm currently having an issue with a.afile being multiple GiB large and GCC raises an error even with the flag-mcmodel=medium.
|
Use binutils tool "ar":
```
ar -x libbig.a
```
for extracting the objects from the archive and
```
ar -r libsmall.a obj1.o obj2.o obj3.o
```
for creating a new archive.
|
Why does it give me this when i try to run in gdb ?
```
(gdb) run
Starting program: /home//Cfile/./ginr
Invocation: /home/Cfile/./ginr <test case file> <results file> [-repeat]
[Inferior 1 (process 3615) exited with code 01]
Missing separate debuginfos, use: debuginfo-install glibc-2.17-222.el7.x86_64
```
|
That looks like a message from the program itself. If you try to run/home/Cfile/./ginrin a terminal without arguments you probably get the same results.
You need to provide arguments when running the program, which is done almost the same insidegdb:
```
(gdb) run test_case_file result_File
```
|
I am trying to allocate memory for 2D Array. But when I am trying to free up the memory it throws the segmentation fault. Kindly help me to know what I am doing wrong?
```
int **arr1 = (int **) malloc (rows * columns * sizeof (int));
//Array Access:
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++)
*(arr1 + i * columns + j) = ++count;
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++)
printf ("%d", *(arr1 + i * columns + j));
for (i = 0; i < rows*columns; i++)
free (arr1[i]);
```
|
It looks like you are trying to allocate an array of pointers to arrays. Your code segfaults because youfreenon-allocated memory. The proper way to allocate a "2D array" is more like this:
```
int **arr1 = malloc (rows * sizeof (int*));
for (int r = 0; r < rows; r++)
arr1[r] = malloc(columns * sizeof(int));
...
for (int r = 0; r < rows; r++)
free(arr1[r]);
free(arr1);
```
|
For example:
```
char* p[10];
char* x = "string"
char* y = "char"
int main{
fun1(){
for (i = 0; i<10;i++ ){
p[i]=x;
}
}
fun2(){
for (i = 0; i<10;i++ ){
p[i]= y;
}
}
}
```
Will the value that is pointed by the pointer overwritten? Or will be saved in the different adress.
|
Aside from the several syntax and other errors, yes, the pointers in an arraypdeclared withchar *p[10]may be modified. This simply changes them to point to different places.
|
I was wondering if there was a way to read bytes (like this:\x00\x01\x02) from the command line in C.
For example:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%s", argv[1]);
return 0;
}
```
```
user@UbuntuServer: ~/Code# gcc Program.c -o Program
user@UbuntuServer: ~/Code# ./Program "\x48\x69"
Hiuser@UbuntuServer: ~/Code# ./Program "\x48\x69\x0a"
Hi
user@UbuntuServer: ~/Code#
```
Thanks!
|
Unless you use a library to parse regex strings like that, you'll need to parse the hex manually. Check out this answer (which has slightly different syntax but a similar function):
Hexadecimal string to byte array in C
|
For example if we declare a file pointerfpand open a file like this:FILE* fp = fopen("filename","w");
If the file doesn't openfopenreturnsNULLto file pointerfp. What is stored in the file pointerfpif the file opens?
|
The C Committee draft N1570 states this aboutFILE*:
7.21.3 Files...The address of theFILEobject used to control a stream may be significant; a copy of aFILEobject need not serve in place of the original.
The pointer returned byfopen()points to aFILEstructure and the contents of that structure are implementation-specific (which means they are different in different platforms).
Even if you know the contents of that structure in a specific implementation,you should NOT try to access any of its members or write code that depends on your knowledge of those members(even if it were possible to do such a thing).
|
I've created a small multiboot complaint kernel that I, until now, used to boot with grub. Now I want to create my own bootloader for it. But I don't know at what address the gnu linker places entry point program. In Microsoft's PE files, there was a specific field called AddressofEntryPoint in _IMAGE_OPTIONAL_HEADER. Is there any such way to find AddressofEntryPoint of a kernel linked by gnu linker (ld)?
|
It depends on the binary format you use. For ELF, thee_entrymember of the main header is what you want.
|
time_t t;
printf("%f\n",time(&t));
it throws "Can not print float number"
|
You may try
#include <stdlib.h>
printf("%jd\n", (intmax_t) time(NULL));.
|
I was wondering if there was a way to read bytes (like this:\x00\x01\x02) from the command line in C.
For example:
```
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("%s", argv[1]);
return 0;
}
```
```
user@UbuntuServer: ~/Code# gcc Program.c -o Program
user@UbuntuServer: ~/Code# ./Program "\x48\x69"
Hiuser@UbuntuServer: ~/Code# ./Program "\x48\x69\x0a"
Hi
user@UbuntuServer: ~/Code#
```
Thanks!
|
Unless you use a library to parse regex strings like that, you'll need to parse the hex manually. Check out this answer (which has slightly different syntax but a similar function):
Hexadecimal string to byte array in C
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.