Unknown pointer error..

Dec 15, 2011 at 7:52pm
i can't pinpoint the error.any help is appreciated 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
#include <iostream>
using namespace std;

int main(){
	char c;
	char *shm, *s;
	s = shm;
	
	for (c = 'a'; c <='z'; c++) 
		*s++ = c;
		*s = '\0';
		cout << "This is s" << *s;
	
	
	return 0;
}

/*
 *  vre.h
 *  unix test
 *
 *  Created by shani09 on 15/12/2011.
 *  Copyright 2011 EMU. All rights reserved.
 *
 */
Last edited on Dec 15, 2011 at 7:54pm
Dec 15, 2011 at 8:05pm
Maybe you could try:
1
2
*s=c;
*s++='\0';
Dec 15, 2011 at 8:05pm
1
2
char *shm, *s;
s = shm;


both pointers aren't pointing to anything yet.

so when you try to do these 2 lines

1
2
*s++ = c;
*s = '\0';


you're trying to access something that isn't there. So the program will most likely crash.
Last edited on Dec 15, 2011 at 8:06pm
Dec 15, 2011 at 8:08pm
When you declare a char*, (or any other variable) it contains garbage data. This data doesn't ponit to anything that your program can or should write to.
You use some memory through a pointer, you need to allocate it. Either
1
2
3
char memory[80];
char *s = memory;
//though this makes s a bit redundant. 

Or
1
2
3
char *s = new char[80];
//and then at the end of your function
delete[] s;//for cleanliness 

Notice that either way, your code isn't good. After the for loop, s points to '\0' thus printing *s (which, by the way, can only print a single char) or s (which is probably what you wanted) will print nothing.
Now, if you have two pointers point to the same memory (which looks like what shm is meant for), this is not going to happen.
triple-reply!It's odd that I haven't seen a quadruple one yet..
Last edited on Dec 15, 2011 at 8:09pm
Topic archived. No new replies allowed.