dynamic array problem

Can someone please tell me why I can't use strncpy on a dynamic array or how I might go about getting the same task accomplished. I'm getting protected memory errors when running the following code. Thanks.

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
#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;
using namespace System;

int main(array<System::String ^> ^args)
{
    char** stars;
	stars = new char*[30];
	int i;
	for(i = 0; i < 30; i++){
		stars[i] = new char[100];
                stars[i] = "Robert Redford";
	}
	
	for(i = 0; i < 30; i++){

		char* pos = strstr(stars[i], "Redford");

			if(pos){
				strncpy(pos, "Redrumm", 7);
			}

		for(i = 0; i < 30; i++){

		cout << stars[i] << endl;
	}
	}
    return 0;
}
You can, but on line 15, you overwrote each pointer to a dynamic array with a pointer to the same string literal, which is illegal to write to.
Last edited on
When you declared stars[i] = new char[100];, you made stars[i] point to a plot of memory. When you then declared stars[i] = "Robert Redford";, you told stars[i] to look somewhere else. More specifically, to a read-only part of memory. If you want to mess with the values of stars[i], use strcpy_s(stars[i],100,"Robert Redford").

As well, strncpy doesn't automatically add a '\0' to the end of your c-string.
http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
If it's illegal to write to, how do you store a string there? thanks
thanks wasabi, that's the information I needed. Thanks helios for letting me know I was trying to do an illegal operation.
Topic archived. No new replies allowed.