View Full Version : some C programing
monkeyhead
05-06-02, 07:38 PM
b. Consider the following C program fragment.
char * a; /* declare a as a string */
char * b = “This is a silly problem\n”; /* declare and initialize b */
/* note length = 25 bytes, counting trailing NULL */
a = (char *) malloc (30); /* give a 30 bytes of storage */
a = b;
Explain why the assignment statement will not have the (apparent) intended effect. What should be used instead?
monkeyhead
05-07-02, 09:30 AM
bump
YARDofSTUF
05-07-02, 09:33 AM
i kinda understand it, but i havent done any C programming so i dunno :p
downhill
05-07-02, 09:51 AM
Originally posted by michaelanthony
b. Consider the following C program fragment.
char * a; /* declare a as a string */
char * b = “This is a silly problem\n”; /* declare and initialize b */
/* note length = 25 bytes, counting trailing NULL */
a = (char *) malloc (30); /* give a 30 bytes of storage */
a = b;
Explain why the assignment statement will not have the (apparent) intended effect. What should be used instead?
I'd use the programing fourm with a redirect, instead. :)
Originally posted by michaelanthony
b. Consider the following C program fragment.
char * a; /* declare a as a string */
char * b = “This is a silly problem\n”; /* declare and initialize b */
/* note length = 25 bytes, counting trailing NULL */
a = (char *) malloc (30); /* give a 30 bytes of storage */
a = b;
Explain why the assignment statement will not have the (apparent) intended effect. What should be used instead?
Not sure what "the (apparent) intended effect" is. If the effect is to copy the value of b into a and waste 5 bytes, then you are on target. If you want to copy the value of b into a, then strcpy() (you could do memcpy(), but using string functions for strings is a little more consistant) in string.h is the way to go--you still have to malloc a but you can use strlen() to get the length of b and add one for the trailing NULL. Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char * a; /* declare a as a string */
char * b = "This is a silly problem\n"; /* declare and initialize b */
/* note length = 25 bytes, counting trailing NULL */
a = (char *) malloc (strlen(b) + 1); /* give the correct amount of storage */
strcpy(a,b);
printf("a is |%s|\nsize %d\n", a, strlen(a));
printf("b is |%s|\nsize %d\n", b, strlen(b));
} /* End main() */
I'm not sure what other "intended effects" you could want. Without seeing that you intend to do with the variable a after declaring and setting its value, there is little to go on...
vBulletin® v3.7.3, Copyright ©2000-2008, Jelsoft Enterprises Ltd.