why is it breaking ?

Nov 29, 2015 at 8:20pm
why is it breaking ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 // ConsoleApplication22.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

char st(char *str[5]) {
	int x = 0, n;

	

	cout << "puts a number:" << endl;
	cin >> n;


	while (x < 5) {


		cout << str[x] + n << endl;

		x++;

	}







	return 0;



}


int main()
{

	char *ch[5] = { "whatsup?", "how u doing", "r u ok?", "whats gives?" };

	st(&ch[0]);
	cin >> ch[0];

	return 0;
}
Nov 29, 2015 at 10:15pm
Sting literals may not be modified. Doing so results in undefined behavior.

In your code you are attempting to overwrite memory that is occupied by string literals (which may be stored in read-only memory.) Don't do that.

The type on line 42 should be: const char* ch[5]

You are also accessing memory you don't own on line 20 (which is also undefined behavior.)
Last edited on Nov 29, 2015 at 10:17pm
Nov 30, 2015 at 8:35am
closed account (E0p9LyTq)
ohad wrote:
I want to start the strings from n letters after the start of the string.. how do i do that ?


Forget using C-style character array strings, learn to use C++ strings.
http://www.cplusplus.com/reference/string/basic_string/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main()
{
   std::string text = "this is a very long string...";

   // create a sub-string starting at the 6th character (index 5)
   std::string text2 = text.substr(5);
   
   std::cout << text2 << "\n";

   return 0;
}


Topic archived. No new replies allowed.