whats wrong with this pointer?

D

Dan

Hi, I am getting a SEG V at line 12 and just can't figure out why?
Can you help please? This is a simple program to replace spaces with '_' in string
1 #include <stdio.h>
2
3 int main()
4 {
5 char *ptr;
6 ptr="Beginning Linux Programming.pdf";
7
8 printf("ptr=%s\n", ptr);
9 while(*ptr!='\0')
10 {
11 if((*ptr)==' ' || (*ptr)==' ')
12 *ptr='_';
13 ptr++;
14 }
15 printf("%s\n",ptr);
16 printf("\n");
17 }
Thanks!

../a.out
ptr=Beginning Linux Programming.pdf
Segmentation fault
 
A

Artie Gold

Dan said:
Hi, I am getting a SEG V at line 12 and just can't figure out why?
Can you help please? This is a simple program to replace spaces with '_' in string
1 #include <stdio.h>
2
3 int main()
4 {
5 char *ptr;
6 ptr="Beginning Linux Programming.pdf";
7
8 printf("ptr=%s\n", ptr);
9 while(*ptr!='\0')
10 {
11 if((*ptr)==' ' || (*ptr)==' ')
12 *ptr='_';
13 ptr++;
14 }
15 printf("%s\n",ptr);
16 printf("\n");
17 }
Thanks!

./a.out
ptr=Beginning Linux Programming.pdf
Segmentation fault

Obviously you've neither read the FAQ nor lurked before posting. Being a
responsible citizen of usenet requires you do both.

HTH,
--ag
 
C

CBFalconer

Dan said:
Hi, I am getting a SEG V at line 12 and just can't figure out why?
Can you help please? This is a simple program to replace spaces
with '_' in string
1 #include <stdio.h>
2
3 int main()
4 {
5 char *ptr;
6 ptr="Beginning Linux Programming.pdf";
7
8 printf("ptr=%s\n", ptr);
9 while(*ptr!='\0')
10 {
11 if((*ptr)==' ' || (*ptr)==' ')
12 *ptr='_';
13 ptr++;
14 }
15 printf("%s\n",ptr);
16 printf("\n");
17 }
Thanks!

./a.out
ptr=Beginning Linux Programming.pdf
Segmentation fault

Of course it fails. ptr has been set to point to a non-modifiable
string, which you then attempt to modify. You might try declaring
it as:

ptr[] = "Beginning Linux Programming.pdf";

which changes it from an initialized pointer to an initialized
array.
 
M

MJ

Hi
if you do like this it will work fine
#include <stdio.h>

int main()
{
char *ptr;
char ptr1[]="Beginning Linux Programming.pdf";
ptr = ptr1;

printf("ptr=%s\n", ptr);
while(*ptr!='\0')
{
if((*ptr)==' ' || (*ptr)==' ')
*ptr='_';
ptr++;
}
printf("%s\n",ptr1);
printf("\n");
}


Regards
MJ
 
?

=?iso-8859-1?q?Dag-Erling_Sm=F8rgrav?=

pete said:
I'm pretty sure that if (*ptr) equals ' ',
then (*ptr) will also be equal to ' '.

one of those should be '\t'.

DES
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top