Sorry if this seems like a dumb question, but I am trying to convert a Char * to Char Array and I cannot figure it out. Every time I think I get close I end up getting a segmentation fault. I want to convert to a character array because I want to be able to reference the different characters in individual positions from the array. Below is what I am doing:
1 2 3 4 5 6 7 8
char * ptr;
char array[10];
// Populate ptr
ptr = "10234";
// Copy from ptr to array.
strcpy(array, ptr);
sebrandon1,
I didn't see a problem in your code snippet. I suppose it was different from what you were trying/using.
You may pay attention to the size of the array, which should be big enough to contain the string.
Ah I realized what I was doing wrong. It was how I was de-referencing the pointer in the calling function. Pointers will be my ultimate downfall. :)
You were correct about how the example is different than what I'm actual using. The example is based how I thought things were happening in my code and not the reality.
I want to convert to a character array because I want to be able to reference the different characters in individual positions from the array.
If that's why you want the conversion, you actually don't need the conversion. You're creating duplicate data and it's a waste of memory and time.
char [] is the same as char * in natural (array name is a pointer to the first element of the array), although when you do char * str = "Hello"; and stuff like that, your compiler might warn you that something is deprecated or similar.
So in your case, since you already have the char * variable, make sure you know which character it is pointing to at the moment, then do pointer arithmetics by yourself and you'll be able to access the character you want.
You get segmentation fault possibly because you're access something out of boundary. It shouldn't be the problem of char * variable.