58127-1 C-ohjelmointi - Syksy 2000 : Kertausta: Osoittimet
Seuraava ohjelma ei tulosta merkkijonoa "this is a test", missä vika ?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void foo(char *x)
{
x = (char *) malloc(100);
if ( !x) exit(1);
strcpy(x,"this is a test");
}
int main(void)
{
char *y;
foo(y);
printf("string = %s\n",y);
free(y);
return 0;
}
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
*******************************************
Virheettömässä versiossa käytetään osoitinta osoittimeen:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void foo(char **x)
{
*x = (char *) malloc(100);
if ( !(*x)) exit(1);
strcpy(*x,"this is a test");
}
int main(void)
{
char *y;
foo(&y);
printf("string = %s\n",y);
free(y);
return 0;
}
Jan Lindström (Jan.Lindstrom@cs.Helsinki.FI)

