473,698 Members | 2,574 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tricky problem

Hi , below given question was asked to me during an interview and i
figured it out little tricky . It would be a great help if anyone
could solve it.

Code : -
main()
{
char *s1="abcd",*s2= NULL;

/* From here you call a function copy which has return type void .
Simple task is to copy s1 into s2 . */

copy(&s1,&s2);

}

copy(char **s,char **t)
{

----- NORMAL COPY STATEMENTS --------
/* But here we have to malloc " t " compulsory . Now what changes
should i do so that chage will reflect in main .I have to print in main
only. */

}

Nov 15 '05 #1
8 1880


pr*********@gma il.com wrote:
Hi , below given question was asked to me during an interview and i
figured it out little tricky . It would be a great help if anyone
could solve it.

Code : -
main()
{
char *s1="abcd",*s2= NULL;

/* From here you call a function copy which has return type void .
Simple task is to copy s1 into s2 . */

copy(&s1,&s2);

}


Seems like trick question, how about a shallow copy?

void
copy(char **s,char **t)
{
*t = *s;
}

Don't forgot a function prototype for 'copy' and the correct
declaration of 'main'.

-Charlie

Nov 15 '05 #2


pr*********@gma il.com wrote:
Hi , below given question was asked to me during an interview and i
figured it out little tricky . It would be a great help if anyone
could solve it.

Code : -
main()
{
char *s1="abcd",*s2= NULL;

/* From here you call a function copy which has return type void .
Simple task is to copy s1 into s2 . */

copy(&s1,&s2);

}

copy(char **s,char **t)
{

----- NORMAL COPY STATEMENTS --------
/* But here we have to malloc " t " compulsory . Now what changes
should i do so that chage will reflect in main .I have to print in main
only. */

}


you may write the copy function as follows:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int
copy( char **s, char **t)
{
size_t len ;
len = strlen(*s);

*t = malloc(len + 1);
strcpy(*t,*s);
return(0);
}

Also, you don't need to pass the address of s1. Passing s1 is
sufficient.
If you pass s1 to copy, then you can use following function.

int
copy ( char *s, char **t)
{
size_t len ;
len = strlen(s);
*t = malloc(len + 1);
strcpy(*t,s);
return(0);
}

Also, string literals may be placed in read only memory and so won't
be modified. In that case you don't even need to allocate the
space for s2.

int
copy(char *s,char **t)
{
*t = s;
return(0);
}

Nov 15 '05 #3
main()
{

char *s1="abcd",*s2= NULL;

copy(&s1,&s2);

printf("%s\n",s 2);
}

void copy(char **s, char **t)
{

*t=(char *)malloc(4);
strcpy(*t,*s);
}


<pr*********@gm ail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Hi , below given question was asked to me during an interview and i
figured it out little tricky . It would be a great help if anyone
could solve it.

Code : -
main()
{
char *s1="abcd",*s2= NULL;

/* From here you call a function copy which has return type void .
Simple task is to copy s1 into s2 . */

copy(&s1,&s2);

}

copy(char **s,char **t)
{

----- NORMAL COPY STATEMENTS --------
/* But here we have to malloc " t " compulsory . Now what changes
should i do so that chage will reflect in main .I have to print in main
only. */

}

Nov 15 '05 #4

"Hash" <a@b.com> wrote in message
news:A2******** *********@news. cpqcorp.net...
main()
{

char *s1="abcd",*s2= NULL;

copy(&s1,&s2);

printf("%s\n",s 2);
}

void copy(char **s, char **t)
{

*t=(char *)malloc(4);
strcpy(*t,*s);
and now you have just caused a memory access problem, "abcd" is 5 chars
long - remember the \0 at the end ;-)
Allan
}

Nov 15 '05 #5
Hash top-posted (BAD Hash, no biscuit):
main()
{

char *s1="abcd",*s2= NULL;

copy(&s1,&s2);

printf("%s\n",s 2);
}

void copy(char **s, char **t)
{

*t=(char *)malloc(4);
strcpy(*t,*s);
}


BOOM.

(a) dangerous cast of `malloc`.

(b) no `#include <stdlib.h>`.

(c) no check for malloc returning null.

(d) Copying 5 characters (`a`, `b`, `c`, `d`, 0) into
a mallocation with room only for 4.

--
Chris "electric hedgehog" Dollin
It's called *extreme* programming, not *stupid* programming.
Nov 15 '05 #6
Hash wrote:

Rude top posting fixed. Your reply belongs *under* the text you are
replying to.
<pr*********@gm ail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Hi , below given question was asked to me during an interview and i
figured it out little tricky . It would be a great help if anyone
could solve it.
If you are ready for a C programming job then, IMHO, this is not tricky.
Code : -
main()
{
char *s1="abcd",*s2= NULL;

/* From here you call a function copy which has return type void .
Simple task is to copy s1 into s2 . */

copy(&s1,&s2);

}

copy(char **s,char **t)
{

----- NORMAL COPY STATEMENTS --------
/* But here we have to malloc " t " compulsory . Now what changes
should i do so that chage will reflect in main .I have to print in main
only. */

}

Include the appropriate headers for the library functions you are using,
otherwise bad things can (and sometimes do) happen.

#include <string.h>
#include <stdlib.h>

Since your copy function is defined after it is used, provide a
prototype declaration to ensure everything ties together nicely.

void copy(char **s, char **t);
main()
main returns an int, tell the compiler this. Especially as in C99
implicit int is no longer allowed.

int main(void)
{

char *s1="abcd",*s2= NULL;

copy(&s1,&s2);

printf("%s\n",s 2);
}

void copy(char **s, char **t)
{

*t=(char *)malloc(4);
The return value of malloc is a void* so the cast is not required. If
the compiler complains without the cast then either you have not
included stdlib.h or you are compiling as C++.
strcpy(*t,*s);
Bang. You need to allow space for the '\0' termination of the string as
well. Also you are not checking for malloc failing.

size_t len = strlen(*s) + 1; /* +1 for the null termination */
*t = malloc( len );
if (*t != NULL)
memcpy(*t, *s, len); /* might as well use memcpy as we know

the length already. */

/* Note that on malloc failure the destination is set NULL so
the caller needs to check this before using the value. */
}

--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #7
#include <stdio.h>
#include <stdlib.h>

copy(char **, char **);

main() {
char *s1="abcd", *s2=NULL;

copy(&s1, &s2);

/*
* test it ;)
*/
printf("%s\n", s2);
}

copy(char **s, char **t) {
*t=malloc(strle n(*s)+1);
if(*t!=NULL)
strcpy(*t, *s);
}

Nov 15 '05 #8
ma******@gmail. com wrote:
#include <stdio.h>
#include <stdlib.h>

copy(char **, char **);

main() {
char *s1="abcd", *s2=NULL;

copy(&s1, &s2);

/*
* test it ;)
*/
printf("%s\n", s2);
}

copy(char **s, char **t) {
*t=malloc(strle n(*s)+1);
if(*t!=NULL)
strcpy(*t, *s);
}


Did you try to compile this program with e.g. gcc -Wall -Wextra ??
Nov 15 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2159
by: Lars Plessmann | last post by:
Problem: I try to store data in a objects field and read it out again. Sounds easy, yeah. But its a bit tricky here.... ;-) This is the class Customer.php with some setter and getter functions to store customers data within an object. It works. Furthermore, it includes a synchronize method, which calls the individual setXXX function and takes the data from the $_POST or $_GET var.
0
595
by: dracolytch | last post by:
Good day all, Ok, I have a pretty tricky problem that I need some help with. I pass around search query information a fair amount (specifically WHERE statements). Normally, I just rawurlencode() the buggers, and pass them via the URL. I like having the where clauses in the URL, because then someone can just bookmark the URL, or send it to a friend, and I don't have to worry about a thing. If someone does a search that requires a LIKE...
4
1911
by: Bung | last post by:
Hi, I have a tricky sql statment I have to write (tricky for me) and I am stuck. I'm having trouble with the following problem. Table1 (Column a, Column b, Column c) Table2 (Column a, Column b, Column c) Table3 (Column a, Column b, Column c) Table1 contains a row of value (1, 2, 3)
25
3402
by: PyPK | last post by:
What possible tricky areas/questions could be asked in Python based Technical Interviews?
5
1630
by: Danny | last post by:
Hi there I need help with a tricky problem. I have a 2 dimensional array with qualities such as ball size, ball color, ball weight. Now I have to print out all the possible combinations of this. assume I have it stored as such i have two dimensional array ball:
13
2745
by: Steve Jorgensen | last post by:
== On Error Resume next, and Err.Number == If you want to call one of your procedures from another procedure, and check for errors afterward, you mayimagine that you should write code something like this... On Error Resuse Next MyFoo 123 lngErrNum = Err.Number On Error Goto 0
2
1821
by: pruebauno | last post by:
I am currently working on a tricky problem at work. I googled around a bit, but "time intervals" did not come up with anything useful. Although I have some rough idea of how I could solve it, I still would value some input. I have information of (It has only couple dozen entries.) ServiceNum, DollarCost and a input database table in the form (several GBytes): ClientNumber (CN), BeginDate(BD), EndDate(ED),
1
1496
by: MorrganMail | last post by:
Or at least I find it tricky. :-) Assume we have three tables A, B and C. Table A contains a path and the distance for traveling that path: A (PathId, NodeId, Dist (from previous node)) 1, 1, 0 1, 2, 10 1, 3, 5
7
2271
by: Osiris | last post by:
Just something I would like to share: I just learned the hard way (2 days detective work on a bug) that foreach loops are not at all like for loops, not intuitive at all. BEWARE: arrays and matrices are sparse by design/definition in PHP. I'm doing some matrix manipulation in a Finite Element program. Translating Fortran to PHP, because hosters won't allow anything else than PHP. I wish PHP would do array and matrix stuff like Fortran...
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8610
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8902
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4623
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2339
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.