Possible Duplicate:
Problem with processing individual strings stored in an array of pointers to multiple strings in C
Ok so I’m trying to change a char of a string to another char in C. The thing is, each string is an element of a 1D array so essentially all together its a 2D array because a string itself is an array of chars. Anyways I have a problem creating code to do this. Is it even possible to do this? Any help is appreciated.
Here’s the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
int i, size;
char **a;
a=(char**)malloc(sizeof(char*));
printf("Enter the size of the array:");
scanf("%d", &size);
for(i=0;i<size;i++){
a[i]=(char*)malloc(sizeof(char)*8);
}
a[3]="Read";
while(*(a[3])!='\0'){
if(*(a[3]) == 'e'){
*(a[3]) = 'r';
}
}
printf("%s\n", a[3]);
system("pause");
return 0;
}
You didn’t allocate enough space for
a. Instead ofyou need
and obviously this must move to be after
sizehas been read.Once you sort that rather mundane problem out the fundamental problem is here:
This makes the pointer
a[3]point at a literal which cannot be modified. Instead you need to copy the contents of that literal intoa[3]. Like this:You must understand that
a[3]=...assigns just the pointera[3]and does not modify the string to whicha[3]points.Now, your code will obviously be in error if
sizeis less than4since thena[3]would be out of bounds, but I guessa[3]is just transient while you debug this.Your while loop is all wrong. Judging from your comments you want something like this:
No need to cast the return value of
mallocin C, so remove the casts.sizeof(char)is always equal to1so you can remove that too.