How to use memset in c++?The Definitive C++ Book Guide and Listdifference between sizeof and strlen in cWhat are the differences between a pointer variable and a reference variable in C++?How do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?The Definitive C++ Book Guide and ListHow do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptWhat is the “-->” operator in C++?How to check whether a string contains a substring in JavaScript?How do I convert a String to an int in Java?Easiest way to convert int to string in C++
Alternate way of computing the probability of being dealt a 13 card hand with 3 kings given that you have been dealt 2 kings
Second (easy access) account in case my bank screws up
Need feedback - Can the composition/colors of this design be fixed if something is lacking or is not a better fit?
Is it expected that a reader will skip parts of what you write?
Wooden cooking layout
Implement Own Vector Class in C++
Mathematically, why does mass matrix / load vector lumping work?
Fixing obscure 8080 emulator bug?
Can Rydberg constant be in joules?
Is it legal for a bar bouncer to confiscate a fake ID
SQL counting distinct over partition
How do I prevent employees from either switching to competitors or opening their own business?
Someone whose aspirations exceed abilities or means
Overlapping String-Blocks
Union with anonymous struct with flexible array member
Pre-1972 sci-fi short story or novel: alien(?) tunnel where people try new moves and get destroyed if they're not the correct ones
Is using haveibeenpwned to validate password strength rational?
What can I, as a user, do about offensive reviews in App Store?
How can this tool find out registered domains from an IP?
Cascading Switches. Will it affect performance?
How to manually rewind film?
Giant Steps - Coltrane and Slonimsky
Importance of Building Credit Score?
Certain search in list
How to use memset in c++?
The Definitive C++ Book Guide and Listdifference between sizeof and strlen in cWhat are the differences between a pointer variable and a reference variable in C++?How do I iterate over the words of a string?How do I read / convert an InputStream into a String in Java?The Definitive C++ Book Guide and ListHow do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptWhat is the “-->” operator in C++?How to check whether a string contains a substring in JavaScript?How do I convert a String to an int in Java?Easiest way to convert int to string in C++
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am from Python background and recently learning C++. I was learning a C/C++ function called memset
and following the online example from website https://www.geeksforgeeks.org/memset-in-cpp/ where I got some compilation errors:
/**
* @author : Bhishan Poudel
* @file : a02_memset_geeks.cpp
* @created : Wednesday Jun 05, 2019 11:07:03 EDT
*
* Ref:
*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
char str[] = "geeksforgeeks";
//memset(str, "t", sizeof(str));
memset(str, 't', sizeof(str));
cout << str << endl;
return 0;
Error when using single quotes 't'
This prints extra characters.
tttttttttttttt!R@`
Error when using "t" with double quotes
$ g++ -std=c++11 a02_memset_geeks.cpp
a02_memset_geeks.cpp:17:5: error: no matching function for call to 'memset'
memset(str, "t", sizeof(str));
^~~~~~
/usr/include/string.h:74:7: note: candidate function not viable: no known
conversion from 'const char [2]' to 'int' for 2nd argument
void *memset(void *, int, size_t);
^
1 error generated.
How to use the memset in C++ ?
Further Study
Excellent tutorial with shortcomings of memset
is given here:
https://web.archive.org/web/20170702122030/https:/augias.org/paercebal/tech_doc/doc.en/cp.memset_is_evil.html
c++ string initialization string-literals memset
|
show 9 more comments
I am from Python background and recently learning C++. I was learning a C/C++ function called memset
and following the online example from website https://www.geeksforgeeks.org/memset-in-cpp/ where I got some compilation errors:
/**
* @author : Bhishan Poudel
* @file : a02_memset_geeks.cpp
* @created : Wednesday Jun 05, 2019 11:07:03 EDT
*
* Ref:
*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
char str[] = "geeksforgeeks";
//memset(str, "t", sizeof(str));
memset(str, 't', sizeof(str));
cout << str << endl;
return 0;
Error when using single quotes 't'
This prints extra characters.
tttttttttttttt!R@`
Error when using "t" with double quotes
$ g++ -std=c++11 a02_memset_geeks.cpp
a02_memset_geeks.cpp:17:5: error: no matching function for call to 'memset'
memset(str, "t", sizeof(str));
^~~~~~
/usr/include/string.h:74:7: note: candidate function not viable: no known
conversion from 'const char [2]' to 'int' for 2nd argument
void *memset(void *, int, size_t);
^
1 error generated.
How to use the memset in C++ ?
Further Study
Excellent tutorial with shortcomings of memset
is given here:
https://web.archive.org/web/20170702122030/https:/augias.org/paercebal/tech_doc/doc.en/cp.memset_is_evil.html
c++ string initialization string-literals memset
3
"t"
and't'
are not the same.
– SergeyA
9 hours ago
5
most online learning resources for c++ are crap and afaik that site is no exception, give this a try instead: stackoverflow.com/questions/388242/…
– formerlyknownas_463035818
9 hours ago
1
Why even usememset
in C++? The reason old C functions exists is for backwards compability.
– Broman
9 hours ago
3
It is a loaded gun, you aimed it at your left foot and pulled the trigger. You have to aim right.
– Hans Passant
9 hours ago
2
You should not change question underneath people who are answering it. If you take a comment or answer in and it is still not working, you can ask another question, but this sort of editing, which replaces once question with another, is destructive
– SergeyA
9 hours ago
|
show 9 more comments
I am from Python background and recently learning C++. I was learning a C/C++ function called memset
and following the online example from website https://www.geeksforgeeks.org/memset-in-cpp/ where I got some compilation errors:
/**
* @author : Bhishan Poudel
* @file : a02_memset_geeks.cpp
* @created : Wednesday Jun 05, 2019 11:07:03 EDT
*
* Ref:
*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
char str[] = "geeksforgeeks";
//memset(str, "t", sizeof(str));
memset(str, 't', sizeof(str));
cout << str << endl;
return 0;
Error when using single quotes 't'
This prints extra characters.
tttttttttttttt!R@`
Error when using "t" with double quotes
$ g++ -std=c++11 a02_memset_geeks.cpp
a02_memset_geeks.cpp:17:5: error: no matching function for call to 'memset'
memset(str, "t", sizeof(str));
^~~~~~
/usr/include/string.h:74:7: note: candidate function not viable: no known
conversion from 'const char [2]' to 'int' for 2nd argument
void *memset(void *, int, size_t);
^
1 error generated.
How to use the memset in C++ ?
Further Study
Excellent tutorial with shortcomings of memset
is given here:
https://web.archive.org/web/20170702122030/https:/augias.org/paercebal/tech_doc/doc.en/cp.memset_is_evil.html
c++ string initialization string-literals memset
I am from Python background and recently learning C++. I was learning a C/C++ function called memset
and following the online example from website https://www.geeksforgeeks.org/memset-in-cpp/ where I got some compilation errors:
/**
* @author : Bhishan Poudel
* @file : a02_memset_geeks.cpp
* @created : Wednesday Jun 05, 2019 11:07:03 EDT
*
* Ref:
*/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
char str[] = "geeksforgeeks";
//memset(str, "t", sizeof(str));
memset(str, 't', sizeof(str));
cout << str << endl;
return 0;
Error when using single quotes 't'
This prints extra characters.
tttttttttttttt!R@`
Error when using "t" with double quotes
$ g++ -std=c++11 a02_memset_geeks.cpp
a02_memset_geeks.cpp:17:5: error: no matching function for call to 'memset'
memset(str, "t", sizeof(str));
^~~~~~
/usr/include/string.h:74:7: note: candidate function not viable: no known
conversion from 'const char [2]' to 'int' for 2nd argument
void *memset(void *, int, size_t);
^
1 error generated.
How to use the memset in C++ ?
Further Study
Excellent tutorial with shortcomings of memset
is given here:
https://web.archive.org/web/20170702122030/https:/augias.org/paercebal/tech_doc/doc.en/cp.memset_is_evil.html
c++ string initialization string-literals memset
c++ string initialization string-literals memset
edited 7 hours ago
astro123
asked 9 hours ago
astro123astro123
720112
720112
3
"t"
and't'
are not the same.
– SergeyA
9 hours ago
5
most online learning resources for c++ are crap and afaik that site is no exception, give this a try instead: stackoverflow.com/questions/388242/…
– formerlyknownas_463035818
9 hours ago
1
Why even usememset
in C++? The reason old C functions exists is for backwards compability.
– Broman
9 hours ago
3
It is a loaded gun, you aimed it at your left foot and pulled the trigger. You have to aim right.
– Hans Passant
9 hours ago
2
You should not change question underneath people who are answering it. If you take a comment or answer in and it is still not working, you can ask another question, but this sort of editing, which replaces once question with another, is destructive
– SergeyA
9 hours ago
|
show 9 more comments
3
"t"
and't'
are not the same.
– SergeyA
9 hours ago
5
most online learning resources for c++ are crap and afaik that site is no exception, give this a try instead: stackoverflow.com/questions/388242/…
– formerlyknownas_463035818
9 hours ago
1
Why even usememset
in C++? The reason old C functions exists is for backwards compability.
– Broman
9 hours ago
3
It is a loaded gun, you aimed it at your left foot and pulled the trigger. You have to aim right.
– Hans Passant
9 hours ago
2
You should not change question underneath people who are answering it. If you take a comment or answer in and it is still not working, you can ask another question, but this sort of editing, which replaces once question with another, is destructive
– SergeyA
9 hours ago
3
3
"t"
and 't'
are not the same.– SergeyA
9 hours ago
"t"
and 't'
are not the same.– SergeyA
9 hours ago
5
5
most online learning resources for c++ are crap and afaik that site is no exception, give this a try instead: stackoverflow.com/questions/388242/…
– formerlyknownas_463035818
9 hours ago
most online learning resources for c++ are crap and afaik that site is no exception, give this a try instead: stackoverflow.com/questions/388242/…
– formerlyknownas_463035818
9 hours ago
1
1
Why even use
memset
in C++? The reason old C functions exists is for backwards compability.– Broman
9 hours ago
Why even use
memset
in C++? The reason old C functions exists is for backwards compability.– Broman
9 hours ago
3
3
It is a loaded gun, you aimed it at your left foot and pulled the trigger. You have to aim right.
– Hans Passant
9 hours ago
It is a loaded gun, you aimed it at your left foot and pulled the trigger. You have to aim right.
– Hans Passant
9 hours ago
2
2
You should not change question underneath people who are answering it. If you take a comment or answer in and it is still not working, you can ask another question, but this sort of editing, which replaces once question with another, is destructive
– SergeyA
9 hours ago
You should not change question underneath people who are answering it. If you take a comment or answer in and it is still not working, you can ask another question, but this sort of editing, which replaces once question with another, is destructive
– SergeyA
9 hours ago
|
show 9 more comments
3 Answers
3
active
oldest
votes
This declaration
char str[] = "geeksforgeeks";
declares a character array that contains a string that is a sequence of characters including the terminating zero symbol ''
.
You can imagine the declaration the following equivalent way
char str[] =
'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ''
;
This call of the function memset
memset(str, 't', sizeof(str));
overrides all characters of the array including the terminating zero.
So the next statement
cout << str << endl;
results in undefined behaviour because it outpuuts characters until the terminating zero is encountered.
You could write instead
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) - 1 );
std::cout << str << 'n';
Or the following way
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', std::strlen( str ) );
std::cout << str << 'n';
That is keeping the terminating zero unchanged in the array.
If you want to override all characters of the array including the terminating zero, then you should substitute this statement
std::cout << str << 'n';
for this statement
std::cout.write( str, sizeof( str ) ) << 'n';
as it is shown in the program below because the array now does not contain a string.
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) );
std::cout.write( str, sizeof( str ) ) << 'n';
As for this call
memset(str, "t", sizeof(str));
then the type of the second argument (that is the type const char *
) does not correspond to the type of the second function parameter that has the type int
. See the declaration of the function
void * memset ( void * ptr, int value, size_t num );
Thus the compiler issues an error message.
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you usestd::string
, which should be used here instead instead of using this complicatedC
stuff. (It might be relevant to know, though not at the beginning of a course)
– JVApen
6 hours ago
add a comment |
Error when using single quotes 't' This prints extra characters.
That's because you overwrote the null terminator.
The terminator is part of the array's size (an array is not magic), though it's not part of the logical string size.
So, I think you meant:
memset(str, 't', strlen(str));
// ^^^^^^
Error when using "t" with double quotes
Completely different thing. You told the computer to set every character in the string, to a string. Doesn't make sense; won't compile.
How to use memset in C++?
Don't.
Either use the type-safe std::fill
, in combination with std::begin
and std::end
:
std::fill(std::begin(str), std::end(str)-1, 't');
Or just a std::string
to begin with. 😊
I was learning the fuction memset in C++ from https://www.geeksforgeeks.org/memset-in-cpp/ where the example is given as below
Don't attempt to learn C++ from random websites. Get yourself a good book instead.
1
unfortunately it really issizeof
in the orginial example. A pity that such code is used to "teach" c++ :(
– formerlyknownas_463035818
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
1
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
2
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
|
show 2 more comments
This is the correct syntax for memset...
void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behaviour is undefined. If count is greater than the size of the object pointed to by dest, the behaviour is undefined.
For the first syntax memset(str, 't', sizeof(str));
. The compiler complained because of extra size. It prints 18 times tttttttttttttt!R@
. I suggest try with sizeof(str) -1
for char array.
For Second syntax memset(str, "t", sizeof(str));
you are providing the second parameter is a string. This is the reason compiler complains error: invalid conversion from ‘const char*’ to ‘int’
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, becausememset
only takes one pointer arg; the other args are by value. That phrasing makes sense formemcpy
which forbids overlap, unlikememmove
.
– Peter Cordes
14 mins ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56463341%2fhow-to-use-memset-in-c%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
This declaration
char str[] = "geeksforgeeks";
declares a character array that contains a string that is a sequence of characters including the terminating zero symbol ''
.
You can imagine the declaration the following equivalent way
char str[] =
'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ''
;
This call of the function memset
memset(str, 't', sizeof(str));
overrides all characters of the array including the terminating zero.
So the next statement
cout << str << endl;
results in undefined behaviour because it outpuuts characters until the terminating zero is encountered.
You could write instead
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) - 1 );
std::cout << str << 'n';
Or the following way
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', std::strlen( str ) );
std::cout << str << 'n';
That is keeping the terminating zero unchanged in the array.
If you want to override all characters of the array including the terminating zero, then you should substitute this statement
std::cout << str << 'n';
for this statement
std::cout.write( str, sizeof( str ) ) << 'n';
as it is shown in the program below because the array now does not contain a string.
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) );
std::cout.write( str, sizeof( str ) ) << 'n';
As for this call
memset(str, "t", sizeof(str));
then the type of the second argument (that is the type const char *
) does not correspond to the type of the second function parameter that has the type int
. See the declaration of the function
void * memset ( void * ptr, int value, size_t num );
Thus the compiler issues an error message.
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you usestd::string
, which should be used here instead instead of using this complicatedC
stuff. (It might be relevant to know, though not at the beginning of a course)
– JVApen
6 hours ago
add a comment |
This declaration
char str[] = "geeksforgeeks";
declares a character array that contains a string that is a sequence of characters including the terminating zero symbol ''
.
You can imagine the declaration the following equivalent way
char str[] =
'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ''
;
This call of the function memset
memset(str, 't', sizeof(str));
overrides all characters of the array including the terminating zero.
So the next statement
cout << str << endl;
results in undefined behaviour because it outpuuts characters until the terminating zero is encountered.
You could write instead
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) - 1 );
std::cout << str << 'n';
Or the following way
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', std::strlen( str ) );
std::cout << str << 'n';
That is keeping the terminating zero unchanged in the array.
If you want to override all characters of the array including the terminating zero, then you should substitute this statement
std::cout << str << 'n';
for this statement
std::cout.write( str, sizeof( str ) ) << 'n';
as it is shown in the program below because the array now does not contain a string.
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) );
std::cout.write( str, sizeof( str ) ) << 'n';
As for this call
memset(str, "t", sizeof(str));
then the type of the second argument (that is the type const char *
) does not correspond to the type of the second function parameter that has the type int
. See the declaration of the function
void * memset ( void * ptr, int value, size_t num );
Thus the compiler issues an error message.
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you usestd::string
, which should be used here instead instead of using this complicatedC
stuff. (It might be relevant to know, though not at the beginning of a course)
– JVApen
6 hours ago
add a comment |
This declaration
char str[] = "geeksforgeeks";
declares a character array that contains a string that is a sequence of characters including the terminating zero symbol ''
.
You can imagine the declaration the following equivalent way
char str[] =
'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ''
;
This call of the function memset
memset(str, 't', sizeof(str));
overrides all characters of the array including the terminating zero.
So the next statement
cout << str << endl;
results in undefined behaviour because it outpuuts characters until the terminating zero is encountered.
You could write instead
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) - 1 );
std::cout << str << 'n';
Or the following way
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', std::strlen( str ) );
std::cout << str << 'n';
That is keeping the terminating zero unchanged in the array.
If you want to override all characters of the array including the terminating zero, then you should substitute this statement
std::cout << str << 'n';
for this statement
std::cout.write( str, sizeof( str ) ) << 'n';
as it is shown in the program below because the array now does not contain a string.
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) );
std::cout.write( str, sizeof( str ) ) << 'n';
As for this call
memset(str, "t", sizeof(str));
then the type of the second argument (that is the type const char *
) does not correspond to the type of the second function parameter that has the type int
. See the declaration of the function
void * memset ( void * ptr, int value, size_t num );
Thus the compiler issues an error message.
This declaration
char str[] = "geeksforgeeks";
declares a character array that contains a string that is a sequence of characters including the terminating zero symbol ''
.
You can imagine the declaration the following equivalent way
char str[] =
'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ''
;
This call of the function memset
memset(str, 't', sizeof(str));
overrides all characters of the array including the terminating zero.
So the next statement
cout << str << endl;
results in undefined behaviour because it outpuuts characters until the terminating zero is encountered.
You could write instead
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) - 1 );
std::cout << str << 'n';
Or the following way
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', std::strlen( str ) );
std::cout << str << 'n';
That is keeping the terminating zero unchanged in the array.
If you want to override all characters of the array including the terminating zero, then you should substitute this statement
std::cout << str << 'n';
for this statement
std::cout.write( str, sizeof( str ) ) << 'n';
as it is shown in the program below because the array now does not contain a string.
#include <iostream>
#include <cstring>
int main()
char str[] = "geeksforgeeks";
std::memset( str, 't', sizeof( str ) );
std::cout.write( str, sizeof( str ) ) << 'n';
As for this call
memset(str, "t", sizeof(str));
then the type of the second argument (that is the type const char *
) does not correspond to the type of the second function parameter that has the type int
. See the declaration of the function
void * memset ( void * ptr, int value, size_t num );
Thus the compiler issues an error message.
edited 8 hours ago
answered 9 hours ago
Vlad from MoscowVlad from Moscow
142k1276181
142k1276181
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you usestd::string
, which should be used here instead instead of using this complicatedC
stuff. (It might be relevant to know, though not at the beginning of a course)
– JVApen
6 hours ago
add a comment |
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you usestd::string
, which should be used here instead instead of using this complicatedC
stuff. (It might be relevant to know, though not at the beginning of a course)
– JVApen
6 hours ago
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you use
std::string
, which should be used here instead instead of using this complicated C
stuff. (It might be relevant to know, though not at the beginning of a course)– JVApen
6 hours ago
The original post clearly indicates that the user is trying to learn C++. Please mention at least that none of this is relevant if you use
std::string
, which should be used here instead instead of using this complicated C
stuff. (It might be relevant to know, though not at the beginning of a course)– JVApen
6 hours ago
add a comment |
Error when using single quotes 't' This prints extra characters.
That's because you overwrote the null terminator.
The terminator is part of the array's size (an array is not magic), though it's not part of the logical string size.
So, I think you meant:
memset(str, 't', strlen(str));
// ^^^^^^
Error when using "t" with double quotes
Completely different thing. You told the computer to set every character in the string, to a string. Doesn't make sense; won't compile.
How to use memset in C++?
Don't.
Either use the type-safe std::fill
, in combination with std::begin
and std::end
:
std::fill(std::begin(str), std::end(str)-1, 't');
Or just a std::string
to begin with. 😊
I was learning the fuction memset in C++ from https://www.geeksforgeeks.org/memset-in-cpp/ where the example is given as below
Don't attempt to learn C++ from random websites. Get yourself a good book instead.
1
unfortunately it really issizeof
in the orginial example. A pity that such code is used to "teach" c++ :(
– formerlyknownas_463035818
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
1
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
2
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
|
show 2 more comments
Error when using single quotes 't' This prints extra characters.
That's because you overwrote the null terminator.
The terminator is part of the array's size (an array is not magic), though it's not part of the logical string size.
So, I think you meant:
memset(str, 't', strlen(str));
// ^^^^^^
Error when using "t" with double quotes
Completely different thing. You told the computer to set every character in the string, to a string. Doesn't make sense; won't compile.
How to use memset in C++?
Don't.
Either use the type-safe std::fill
, in combination with std::begin
and std::end
:
std::fill(std::begin(str), std::end(str)-1, 't');
Or just a std::string
to begin with. 😊
I was learning the fuction memset in C++ from https://www.geeksforgeeks.org/memset-in-cpp/ where the example is given as below
Don't attempt to learn C++ from random websites. Get yourself a good book instead.
1
unfortunately it really issizeof
in the orginial example. A pity that such code is used to "teach" c++ :(
– formerlyknownas_463035818
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
1
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
2
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
|
show 2 more comments
Error when using single quotes 't' This prints extra characters.
That's because you overwrote the null terminator.
The terminator is part of the array's size (an array is not magic), though it's not part of the logical string size.
So, I think you meant:
memset(str, 't', strlen(str));
// ^^^^^^
Error when using "t" with double quotes
Completely different thing. You told the computer to set every character in the string, to a string. Doesn't make sense; won't compile.
How to use memset in C++?
Don't.
Either use the type-safe std::fill
, in combination with std::begin
and std::end
:
std::fill(std::begin(str), std::end(str)-1, 't');
Or just a std::string
to begin with. 😊
I was learning the fuction memset in C++ from https://www.geeksforgeeks.org/memset-in-cpp/ where the example is given as below
Don't attempt to learn C++ from random websites. Get yourself a good book instead.
Error when using single quotes 't' This prints extra characters.
That's because you overwrote the null terminator.
The terminator is part of the array's size (an array is not magic), though it's not part of the logical string size.
So, I think you meant:
memset(str, 't', strlen(str));
// ^^^^^^
Error when using "t" with double quotes
Completely different thing. You told the computer to set every character in the string, to a string. Doesn't make sense; won't compile.
How to use memset in C++?
Don't.
Either use the type-safe std::fill
, in combination with std::begin
and std::end
:
std::fill(std::begin(str), std::end(str)-1, 't');
Or just a std::string
to begin with. 😊
I was learning the fuction memset in C++ from https://www.geeksforgeeks.org/memset-in-cpp/ where the example is given as below
Don't attempt to learn C++ from random websites. Get yourself a good book instead.
edited 9 hours ago
answered 9 hours ago
Lightness Races in OrbitLightness Races in Orbit
302k56489843
302k56489843
1
unfortunately it really issizeof
in the orginial example. A pity that such code is used to "teach" c++ :(
– formerlyknownas_463035818
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
1
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
2
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
|
show 2 more comments
1
unfortunately it really issizeof
in the orginial example. A pity that such code is used to "teach" c++ :(
– formerlyknownas_463035818
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
1
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
2
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
1
1
unfortunately it really is
sizeof
in the orginial example. A pity that such code is used to "teach" c++ :(– formerlyknownas_463035818
9 hours ago
unfortunately it really is
sizeof
in the orginial example. A pity that such code is used to "teach" c++ :(– formerlyknownas_463035818
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
I am learning C++, and learning online from geeksforgeeks.org/memset-in-cpp, The example is taken from there, nothing warnings were given there. Thanks for the usage info.
– astro123
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
Updated to address both comments.
– Lightness Races in Orbit
9 hours ago
1
1
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
@astro123 Another reason to work from a good book instead. There are different kinds of literals in C++, which is completely different from Python.
– Lightness Races in Orbit
9 hours ago
2
2
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
This site (geeksforgeeks) should be forever banned.
– SergeyA
9 hours ago
|
show 2 more comments
This is the correct syntax for memset...
void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behaviour is undefined. If count is greater than the size of the object pointed to by dest, the behaviour is undefined.
For the first syntax memset(str, 't', sizeof(str));
. The compiler complained because of extra size. It prints 18 times tttttttttttttt!R@
. I suggest try with sizeof(str) -1
for char array.
For Second syntax memset(str, "t", sizeof(str));
you are providing the second parameter is a string. This is the reason compiler complains error: invalid conversion from ‘const char*’ to ‘int’
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, becausememset
only takes one pointer arg; the other args are by value. That phrasing makes sense formemcpy
which forbids overlap, unlikememmove
.
– Peter Cordes
14 mins ago
add a comment |
This is the correct syntax for memset...
void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behaviour is undefined. If count is greater than the size of the object pointed to by dest, the behaviour is undefined.
For the first syntax memset(str, 't', sizeof(str));
. The compiler complained because of extra size. It prints 18 times tttttttttttttt!R@
. I suggest try with sizeof(str) -1
for char array.
For Second syntax memset(str, "t", sizeof(str));
you are providing the second parameter is a string. This is the reason compiler complains error: invalid conversion from ‘const char*’ to ‘int’
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, becausememset
only takes one pointer arg; the other args are by value. That phrasing makes sense formemcpy
which forbids overlap, unlikememmove
.
– Peter Cordes
14 mins ago
add a comment |
This is the correct syntax for memset...
void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behaviour is undefined. If count is greater than the size of the object pointed to by dest, the behaviour is undefined.
For the first syntax memset(str, 't', sizeof(str));
. The compiler complained because of extra size. It prints 18 times tttttttttttttt!R@
. I suggest try with sizeof(str) -1
for char array.
For Second syntax memset(str, "t", sizeof(str));
you are providing the second parameter is a string. This is the reason compiler complains error: invalid conversion from ‘const char*’ to ‘int’
This is the correct syntax for memset...
void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest. If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behaviour is undefined. If count is greater than the size of the object pointed to by dest, the behaviour is undefined.
For the first syntax memset(str, 't', sizeof(str));
. The compiler complained because of extra size. It prints 18 times tttttttttttttt!R@
. I suggest try with sizeof(str) -1
for char array.
For Second syntax memset(str, "t", sizeof(str));
you are providing the second parameter is a string. This is the reason compiler complains error: invalid conversion from ‘const char*’ to ‘int’
answered 8 hours ago
Erik NielsenErik Nielsen
6628
6628
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, becausememset
only takes one pointer arg; the other args are by value. That phrasing makes sense formemcpy
which forbids overlap, unlikememmove
.
– Peter Cordes
14 mins ago
add a comment |
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, becausememset
only takes one pointer arg; the other args are by value. That phrasing makes sense formemcpy
which forbids overlap, unlikememmove
.
– Peter Cordes
14 mins ago
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,
uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, because memset
only takes one pointer arg; the other args are by value. That phrasing makes sense for memcpy
which forbids overlap, unlike memmove
.– Peter Cordes
14 mins ago
potentially-overlapping subobject of what? It's not automatically UB to modify the object-representation of other objects in C++. For example,
uint32_t
has a fully defined object representation (except for the endian byte-order). So it's not clear what kind of overlap you're talking about, because memset
only takes one pointer arg; the other args are by value. That phrasing makes sense for memcpy
which forbids overlap, unlike memmove
.– Peter Cordes
14 mins ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56463341%2fhow-to-use-memset-in-c%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
"t"
and't'
are not the same.– SergeyA
9 hours ago
5
most online learning resources for c++ are crap and afaik that site is no exception, give this a try instead: stackoverflow.com/questions/388242/…
– formerlyknownas_463035818
9 hours ago
1
Why even use
memset
in C++? The reason old C functions exists is for backwards compability.– Broman
9 hours ago
3
It is a loaded gun, you aimed it at your left foot and pulled the trigger. You have to aim right.
– Hans Passant
9 hours ago
2
You should not change question underneath people who are answering it. If you take a comment or answer in and it is still not working, you can ask another question, but this sort of editing, which replaces once question with another, is destructive
– SergeyA
9 hours ago