assignment from incompatiable pointer type C
Say I want to read in a list of pages name of max 19 character, e.g. 4 (Number of page) Name1 Name2 Name3 Name4
I am trying to use a global 2D array to store the 开发者_运维知识库page number and page name, I got an error saying assignment from incompatiable pointer type...
Thanks
static int nPages;
static char** pageName;
int main(void){
scanf(" %d", &nPages);
pageName = (char *)malloc(nPages*sizeof(char));
for(int i=0; i < nPages ;i++){
pageName[i] = (char *)malloc(20*sizeof(char));
scanf(" %s", pageName[i]);
}
//Free Memory Here of coz.
return 0;
}
Never cast the return value of malloc()
in C. It hides compiler warnings that actually help you, and it's never necessary so it just adds clutter. You should use:
pageName = malloc(nPages * sizeof *pageName);
Note how this is free from repetitions of the type name of pageName
. Here, sizeof *pageName
means "the size of the object pointed at by pageName
", i.e. "the size of a character pointer". You should expect a sizeof
expression as malloc()
's argument very often.
Also, sizeof (char)
is always 1 in C, so that particular expression, it can be argued, adds more clutter than it helps make the code safe.
The problem lies right there:
pageName = (char *)malloc(nPages*sizeof(char));
pageName is a char **
, not a char *
. So it should read:
pageName = malloc(nPages*sizeof(char*)); // sizeof(char *), and no need to cast
EDIT: removed the cast
Your defined pageName
as char **
but when calling malloc to initialize the pointer, you use a cast to (char *)
. Maybe that is the problem.
You are assigning char*
to char**
at your first malloc
line. Just drop the (char*)
cast - C handles void*
to char**
conversion automatically.
char*
and char**
are two different types, and you can't freely assign the first to the latter.
Having said that, you have to do a two-step initialization. First, you have to malloc()
space for nPages
string:
pageName = (char**) malloc(nPages * sizeof(char*));
then, you have to malloc()
space for each pageName
:
for (i = 0; i < nPages; ++i) {
pageName[i] = (char*) malloc(20);
}
精彩评论