LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   what the... C code problem (https://www.linuxquestions.org/questions/programming-9/what-the-c-code-problem-282426/)

zaichik 01-26-2005 07:24 AM

what the... C code problem
 
Hi all,

I clearly am suffering from a fundemental lack of understanding. What is wrong with the following code snippet?

Code:

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <unistd.h>

int main( int argc, char **argv) {

        char *a;
        int b = 100;

        a = ( char * ) malloc( 4 );
        strcpy( a, ( char * ) b );
        printf( "%s\n", a );
        return ( 0 );
}

I get a segmentation fault. Do I not have to malloc memory for the point to char? Is four bytes not enough? Do I not have to cast b as a pointer to char in order to strcpy it into a? Or am I approaching storing/concatenating an int into a string in the wrong way?

TIA.

leonscape 01-26-2005 07:35 AM

strcpy( a, ( char * ) b );

This isn't doing what you think it's doing. Its attempting to access memory location 100 and copy that to a. Which is why you have the segmentation fault.

sscanf( a, "%d", b );

zaichik 01-26-2005 07:59 AM

Hi,

Thanks. You were right--that wasn't doing at all what I thought it was.
When I try sscanf, I get a warning:

junk.c:15: warning: format argument is not a pointer (arg 3)

And then the printf prints just the newline.

Ideas?

Thanks again.

Matir 01-26-2005 09:19 AM

I think you need this:

Code:

a=(char *)malloc(4);
sprintf(a,"%d",b);

...

leonscape 01-26-2005 09:41 AM

Yep Matir is right mixing up my scan and my print.

zaichik 01-26-2005 02:00 PM

Thank you both, all fixed now and ready to roll for a while!

Thanks again!

Matir 01-26-2005 02:08 PM

No problem. Feel free to click the thanks button by my post... not that I know what it does, lol. :)


All times are GMT -5. The time now is 05:40 AM.