I can't seem to change individual characters in a pointer without the program crashing. R1 must be a pointer.
char * R1[6];
int main (){
*R1 = "33333";
printf("%s\n", *R1);
R1[3] = '4';
printf("%s", *R1);
return 0;
}
I can't seem to change individual characters in a pointer without the program crashing. R1 must be a pointer.
char * R1[6];
int main (){
*R1 = "33333";
printf("%s\n", *R1);
R1[3] = '4';
printf("%s", *R1);
return 0;
}
This should work for you:
#include <stdio.h>
char R1[6] = "33333";
int main () {
printf("%s\n", R1);
R1[3] = '4';
printf("%s", R1);
return 0;
}
Output:
33333
33343
EDIT:
With a pointer this should work for you:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char * R1 = malloc(6*sizeof(char));
strcpy(R1, "33333");
printf("%s\n", R1);
R1[3] = '4';
printf("%s", R1);
free(R1);
return 0;
}
Your code must be like this to get it work
char R1[6]="33333";
int main (){
printf("%s\n", R1);
R1[3] = '4';
printf("%s", R1);
return 0;
}
let's analyze your wrong code to figure out the problems
first ERROR
char * R1[6];
here you are declaring an array of 6 pointer pointing each one to a char but you want an array of 6 char that's why it should be char R1[6];
to get what you want
second ERROR
*R1 = "33333";
in C language you cannot assign a string by using the operator =
. You have two choices either you initialize when declaring it like that char R1[6] = "33333";
or you can use the
function strcpy()
located in the string.h
library and it wil be strcpy(R1,"33333");
third ERROR:
printf("%s\n", *R1);
when dereferencing a string in printf()
you need to provide only the address of the first element of the string which is the name of the array R1
that's why it should be like that
the instruction
printf("%s\n", R1);
the same thing for the last printf()
The variable you are declaring is not a pointer; it is in fact an array of six char pointers (this is why printf
fails). If you want to use a char array, simply write:
char R1[6];
If you want a char pointer, write:
char *R1;
And initialize it somehow (probably with malloc
):
/*in main*/
R1 = malloc(6); /*six bytes for five chars +null terminator*/
Make sure to zero-terminate your string:
R1[5] = '\0';
Once you have a valid, mutable* char sequence, you can assign to individual chars much like you are already:
R1[3] = '4';
However, when it comes to assigning the whole string, you'll want to use the strcpy function instead of the =
operator:
/*R1 now contains the text "33333"*/
strcpy(R1, "33333");
*When you write R1 = "33333"
, you are assigning to the pointer instead of to the text it points to. Since "33333"
is immutable, you won't be able to assign to the values in your string when your string is a direct reference to it.
So the complete program might look like this:
char *R1;
int main (){
R1 = malloc(6);
R1[5] = '\0';
strcpy(R1, "33333");
printf("%s\n", R1);
R1[3] = '4';
printf("%s", R1);
free(R1);
return 0;
}