LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Strings in gtk+ (c) (https://www.linuxquestions.org/questions/programming-9/strings-in-gtk-c-4175608540/)

Linusovic 06-24-2017 10:00 AM

Strings in gtk+ (c)
 
Hello!

I'm currently having a trouble with strings and allocation of memory ( i think ).

float effect = calc_power_r(); //calc_power is my own function.
char StartText[] = "Effekt: ";
char* effectString = (char *)malloc(sizeof(float));
char* effectLabel = (char *)malloc(sizeof(effectString)+sizeof(StartText));
snprintf(effectLabel, strlen(effectString), "%f", effect);
g_stpcpy(effectLabel, StartText);
strcat(effectLabel, effectString);
gtk_label_set_text(GTK_LABEL(test->EffectResultLabel),effectLabel);
free(effectLabel);
free(effectString);

I've noticed if i change the allocation of effectString to a static string like
char effectString[50];
and
snprintf(effectLabel, 50, "%f", effect);

it works like a charm. So i suppose I'm doing something wrong with the allocation of the string or this line.
snprintf(effectLabel, strlen(effectString), "%f", effect);

//Best Regards, Linusovic

af7567 06-24-2017 11:06 AM

I think it is because of the effectString allocation too. effectString is a string made of chars so instead of sizeof(float) which would just return the size of the float datatype you need to allocate enough memory for the number of characters that will be used when the float is converted to a string.

Something like this would allocate enough memory for a 50 char string, similar to what you did with "char effectString[50];"
Code:

char* effectString = (char *)malloc(50 * sizeof(char));
I don't know how long your "effect" number is going to be, but I guess less than 50 characters long (including the . ). Not sure how to work out the length in characters of the number though so you might just have to allocate enough for whatever the maximum length of a float can be.

Laserbeak 06-24-2017 07:51 PM

I think af7567 hit it. That's the first thing I noticed too.

If you want to store a string representation of a float, you don't do something like:

Code:


char *myFloatString = (char *)malloc(sizeof(float)); // WRONG!

If you want a string representation of a float, you'd do something like this:

Code:

#include <stdio.h>
#include <math.h>

int main (int argc, char *argv[]) {
    char myFloatString[10];
    sprintf (myFloatString, "%f", M_PI);
    printf ("%s\n", myFloatString);
    return 0;
}

Output:

Code:

$ ./floattest
3.141593

If you want more digits, you need to use a double or double double and allocate more characters.


All times are GMT -5. The time now is 06:21 AM.