Affichage des articles dont le libellé est Active questions tagged c - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged c - Stack Overflow. Afficher tous les articles

mercredi 5 août 2015

how does it happened that a variable used before it's declared?


I am confused about a function dictCreate() in file dict.c of redis implementation. I am going to paste the code here:

/* Create a new hash table 
 * T = O(1)
 */
dict *dictCreate(dictType *type, void *privDataPtr) {
    dict *d = zmalloc(sizeof(*d));
    _dictInit(d, type, privDataPtr);
    return d;
}

variable d is used in zmalloc(sizeof(*d)), but theoretically it will exist when this line was executed. So my question is how it is possible to use variable d before it is declared?



via Chebli Mohamed

Is uninitialized local variable the fastest random number generator?


I know the uninitialized local variable is undefined behaviour(UB), and also the value may have trap representations which may affect further operation, but sometimes I want to use the random number only for visual representation and will not further use them in other part of program, for example, set something with random color in a visual effect, for example:

void updateEffect(){
    for(int i=0;i<1000;i++){
        int r;
        int g;
        int b;
        star[i].setColor(r%255,g%255,b%255);
        bool isVisible;
        star[i].setVisible(isVisible);
    }
}

is it that faster than

void updateEffect(){
    for(int i=0;i<1000;i++){
        star[i].setColor(rand()%255,rand()%255,rand()%255);
        star[i].setVisible(rand()%2==0?true:false);
    }
}

and also faster than other random number generator?



via Chebli Mohamed

How to represent time in structure using C? [on hold]


I am beginning to code in C and the first assignment I got has this question of structure that I am unable to understand.Even a simple logic would be of great help.How should I proceed?

"Define a structure to represent time in hours (0-23), minutes (0-59), and seconds (0-59), and then write a function that accepts an argument of type time represented by this structure and updates it by one second & 30 seconds."



via Chebli Mohamed

GLCM in Digital image processing


I am not understanding GLCM, How to get GLCM matrix , Can anyone post the C/C++ code for getting GLCM matrix. am working with opencv.



via Chebli Mohamed

Parsing JSON array in C


I have the following JSON returned from the server, and I'm trying to access to the Values (timestamp/data):

{
   "queries": [
     {
       "sample_size": 1,
       "results": [
         {
           "name": "data",
           "group_by": [
             {
               "name": "type",
               "type": "number"
             }
           ],
           "tags": {
             "hostname": [
               "host"
             ]
           },
           "values": [
             [
               1438775895302,
               143
             ]
           ]
         }
       ]
     }
   ]
 }

I am using json-c, and am using slightly modified version of the complete json parser. However I keep getting a segmentation fault (core dumped) when attempting to access the values section using json_parse_array.

How would I go about accessing the values section?



via Chebli Mohamed

Bubble sort concept


I just want the explanation about the condition in nested for loop. How its processing, i am bit confused. I want the logic behind the conditions of two for loops.

 #include<stdio.h>
void bubblesort(int a[25],int n);

int main()
{
    int a[25],size,i;
    printf("Enter the size of an array");
    scanf("%d",&size);
    for(i=0;i<size;i++)
    {
        scanf("%d",&a[i]);
    }
    bubblesort(a,size);
    for(i=0;i<size;i++)
    {
        printf("%d\t",a[i]);
    }

    return 0;
}

void bubblesort(int a[], int n)
{

    int temp,i,j;
    for(i=0;i<n;i++)
    {
        for(j=0;j<(n-i)-1;j++)
        {
            if(a[j]>a[j+1])
            {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]= temp;
            }
        }
    }
}



via Chebli Mohamed

How to convert double value to uint8_t string[] to print on terminal window in atmel studio


I am trying to convert some double values to uint8_t String[] (in C) when programming in Atmel Studio 6.2 in order to use it further in function: usart_write_buffer_job.

And this is the whole command I am going to use further, but instead of characters, I would like to print the given double values on the screen:

   uint8_t string[] = "Hello World!\n";
   usart_write_buffer_job(&usart_instance, string, sizeof(string));

I have tried casting, but it does not work properly in Atmel, as it does not recognize the (uint8_t*)(&MyDoubleValue)



via Chebli Mohamed

String splitting examples that don't use malloc or realloc?


I was wondering if any of you out there have ever come across any examples that split large "strings" by delimiter (like a newline for example) into an array without using malloc or realloc?



via Chebli Mohamed

GMP: Are self-assignments forbidden?


I'm using the GMP library for arbitrary precision in C. All usage examples that I've seen seem to avoid self assignments such as:

Syntax : void mpz_add (mpz_t rop, const mpz_t op1, const mpz_t op2)

mpz_add(a, a, b); // Assign a+b to a

Is this usage allowed or should I only resort to assigning to a third variable?



via Chebli Mohamed

Packets incapsulation for own simple VPN


I want to do my own very simple implementation of VPN in C on Linux. For that purpose I'm going to capture IP packets, modify them and send forward. The modification consists of encryption, authentication and other stuff like in IPSec. My question is should I process somehow the size of packets or this will be handled automatically? I know it's maximum size is 65535 - 20 (for header) but accoring to MTU it is lesser. I think its because encrypted payload "incapsulated into UDP" for NAT-T is much bigger then just "normal payload" of the IP packet.



via Chebli Mohamed

cmake and 2 libraries


I have a library in my project that I would like to compile once in 32 bits and than on 64 bits (at the same time, e.g. at the end of my compilation I would like to have the 2 versions). Is that possible or I have to call 2 times cmake + make but with different parameters?



via Chebli Mohamed

How is a text area created in a programming language [on hold]


How is a textarea designed or made at a very basic level.

Let's for example say JTextArea or JEditorPane (I know only Java and Javascript). How are they made from the very basic level. Looking at the source code of the mentioned components is very hallucinating. I wish to know the basic thought process or major steps involved in creating a textArea using a programming language.

Just guessing if it involves usage of 2d graphics to show the rectangle, the border, the scrollbar and showing the text over the rectangle, etc. The reason I am thinking that way is because, some text editors have indentation guidelines, collapsible areas, etc.

Can anyone please throw some light on this question as to how can I build my own text area. I can't think of any simpler way of putting this.

Kindly refrain from mentioning different plugins. I know there are many. But I want to know the approach to create one from scratch.



via Chebli Mohamed

Color measurement and certification


I wanna obtain the LAB values using icc profile But i just know the CMYK values.

I just own two things 1) CMYK values 2) an icc profile(colorspace:CMYK, PCS:LAB) file.

Is it possible to obtain the LAB values using an icc profile? CMYK -> icc profile -> LAB (Is it a correct concept about color transfer?)



via Chebli Mohamed

Program terminated with signal 6, Aborted. Why?


I am writing a C program which crashes every time I try to stop the daemon, works well otherwise. This tells me it probably has to do something with free(). I spent sometime on debugging but still no luck. Here's the core dump

Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `/usr/lib/quagga/bgpd --daemon -A 127.0.0.1'.
Program terminated with signal 6, Aborted.
#0  0x00007f5e896b2165 in raise () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) bt
#0  0x00007f5e896b2165 in raise () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007f5e896b53e0 in abort () from /lib/x86_64-linux-gnu/libc.so.6
#2  0x00007f5e8a721cea in core_handler (signo=<optimized out>, siginfo=<optimized out>, context=<optimized out>) at sigevent.c:216
#3  <signal handler called>
#4  0x00007f5e896fa939 in free () from /lib/x86_64-linux-gnu/libc.so.6
#5  0x00007f5e8a70f00b in zfree (type=<optimized out>, ptr=<optimized out>) at memory.c:132
#6  0x00007f5e8abf89f6 in bgp_bfd_peer_free (peer=0x7f5e8b32ab30) at bgp_bfd.c:69
#7  0x00007f5e8abaa803 in peer_group_delete (group=group@entry=0x7f5e8b1d0dc0) at bgpd.c:2176
#8  0x00007f5e8abaa96b in bgp_delete (bgp=0x7f5e8b31af20) at bgpd.c:2730
#9  0x00007f5e8aba47bb in bgp_exit (status=<optimized out>) at bgp_main.c:238
#10 sigint () at bgp_main.c:206
#11 0x00007f5e8a721d27 in quagga_sigevent_process () at sigevent.c:111
#12 0x00007f5e8a70d7fe in thread_fetch (m=0x7f5e8b1c8900, fetch=fetch@entry=0x7fff76f2f3d8) at thread.c:1279
#13 0x00007f5e8aba4592 in main (argc=4, argv=0x7fff76f2f598) at bgp_main.c:452

Anyone have idea what is signal 6 and why is it being generated?



via Chebli Mohamed

Loading .dll with ctypes


I have a .dll with dependencies to some other (Sundials ODE solver) .dlls. I use windows 8.1 with mingw to compile and link the c-code I use for my .dll. When trying to load them with Python and ctypes I get a pop-up with a System error: cannot find libsundials_cvode.dll since it does not exist on the computer and when you close the popup Python spits out WindowsError: [Error 126] Cannot find the module Cannot understand why this is, because gcc compiles and links the files fine without errors (and yes, they do exist)... I have even tried to copy the dependent dlls into the directory where my python script is, without success.

I run the following compile and linker commands without any warnings or errors

gcc -c -I c:\sundials\include cfile.c
gcc -shared -o clib.dll cfile.o -L. C:\sundials\instdir\lib\libsundials_cvode.dll -L. C:\sundials\instdir\lib\libsundials_nserial.dll

My python test script giving the abovementioned error is

import ctypes
lib = ctypes.cdll.LoadLibrary('clib.dll')

I'm a beginner with gcc and c, but quite experienced with Python. Any suggestions what might be the reason?



via Chebli Mohamed

How to create a dynamic array of strings with the space just necessary for each string in C


I want to have an array of pointers to strings,and just get the space necessary for each string. I know malloc and getc are required but not familiar with the use of them.

Here is part of my code. It gives the error message "Segmentation fault" ....

char **allstrs;
char *one_str;
int totstrs=0,current_size= INITIALSIZE;

allstrs = (char **)malloc(current_size*sizeof(char*)); //dynamic array of strings
while(getstr(one_str)!=EOF){
    if(totstrs == current_size){
        current_size *=2;
        allstrs = realloc(allstrs, current_size*sizeof(char*));
    }
    strcpy(allstrs[totstrs],one_str);
    printf("String[%d] is : %s\n",totstrs,allstrs[totstrs]);
    totstrs ++;

}
free(allstrs);   //deallocate the segment of memory

return 0;

and the function getstr called

char c; 
int totchars=0, current_size=INITIALCHARS;

str = (char*)malloc(sizeof(char));
while(c!='\n'){
    c = getc(stdin);     
    if(c==EOF){
        return EOF;
    }

    if(totchars == current_size){
        current_size *=2;
            str = (char*)realloc(str,current_size*sizeof(char));
    }
        str[totchars] = c;  //store the newly-read character    
    totchars++;
}
str[totchars]='\0';   //at the end append null character to mark end of string

return 0;

}



via Chebli Mohamed

How to send CTRL+C WITH JSCH?


I'm using jsch ChannelShell to send commands to a remote system, but I can't send special commands like ctrl+c. I tried many things, but have no success.

Any help would be appreciated.



via Chebli Mohamed

What alterations must I do to this code.. I am receiving a Wrong answer message


All submissions for this problem are available.

Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction. Input

Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw. Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance. Output

Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.

  • Example - Successful Transaction

Input: 30 120.00

Output: 89.50

  • Example - Incorrect Withdrawal Amount (not multiple of 5)

Input: 42 120.00

Output: 120.00

  • Example - Insufficient Funds

Input: 300 120.00

Output: 120.00

**

  • In reference to the above problem... I am receiving a wrong output message on submission! Can somebody help me out? I believe i have covered all cases! But guys, do take a look

**

#include<stdio.h>
#define bank_charge 0.5
int main()
{
    float X, Y,new_balance;
    X=0, Y = 0;

    printf("With amt and balance ");
    scanf("%f%f", &X, &Y);
    if (X > 0 && X <= 2000 && Y >= 0 && Y <= 2000)
    {
        if (X > Y || ((Y-0.5-X)<0))
        {   printf("Insufficient Funds\n");
            printf("%0.2f", Y);
            return 0;

        }
        if ((int)X % 5 == 0)
        {
            new_balance = (Y - X) - bank_charge;
            printf("%0.2f", new_balance);
            return 0;

        }
        printf("%0.2f", Y);
            }
    return 0;
}



via Chebli Mohamed

calculate difference between cells in an array [on hold]


I want to calculate the difference between every cell in one primary row to other rows and then sum the diff.

Primary row: - [11,19,59,69,9]

other row:   - [10,20,30,20,50]
diff         - [|11-10|,|19-20|,|59-30|,|69-20|,|9-50|] = [1,1,29,49,41] 
sum(diff)    = 1 + 1 + 29 + 49 + 41 = 121

How can i do it ?



via Chebli Mohamed

how can source files see other files without path in a cmake project?


In a CMAKE project I have created 2 folders, a and b, each of which has include and src directories:

-- MyProject

CMakeLists.txt

---- a

------ include

-------- a.h

---- b

------ include

-------- b.h

...

a.h includes b.h. But only if the path is specified, ie, #include "../../b/include/b.h".

How can I configure cmake so that all project files can see each other without specifying the path? eg: #include "b.h"



via Chebli Mohamed