0

#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;

int main(){
char s[100];
cout<<"enter the string :"<<endl;
gets(s);
//memcpy
char a[100];
memcpy(a,s,strlen(s)+1);//here if we decrease bytes to be copied to a value less than length of s i.e.(strlen(s)), then s is getting destroyed ...some garbage value is coming
cout<<" a : "<<a<<" s : "<<s<<endl;
}

4
Contributors
7
Replies
8
Views
9 Years
Discussion Span
Last Post by dougy83
0

);//here if we decrease bytes to be copied to a value less than length of s i.e.(strlen(s)), then s is getting destroyed ...some garbage value is coming

Try null-terminating a after you copy. You'll probably be seeing random characters after the copied string.

0

thnx for ur reply ....but it is not still clear to me that while we are copying the value of char array s to char array a......should it happen that s gets some random characters?????y calling some function is effecting s.....we are just copying s to a.

0

I don't think s is being affected. Only a is changed by memcpy. Try the following to see that you need to null terminate your string in a.

int main(){
   char s[100];
   cout<<"enter the string :"<<endl;
   gets(s);
   //memcpy
   char a[100];
   ZeroMemory(a, sizeof(a));  // fill array with a know quantity
   memcpy(a,s,strlen(s)+1);//here if we decrease bytes to be copied to a value less than length of s i.e.(strlen(s)), then s is getting destroyed ...some garbage value is coming
   cout<<" a : "<<a<<" s : "<<s<<endl;
   }

Note the ZeroMemory command.

0

memcpy(a,s,strlen(s)+1) instead if this run the same prgm using memcpy(a,s,strlen(s)-1)...you will get to know that s is changing.

0

Note the ZeroMemory command.

What is the point of replying to you if you don't bother to listen.

memcpy(a,s,strlen(s)+1) instead if this run the same prgm using memcpy(a,s,strlen(s)-1)...you will get to know that s is changing.

If I run that, a gets displayed as whatever I typed in less the last char; how is this surprising in any way??

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.