Question:
Doubt in char* in C programing?
?
2011-11-03 12:55:34 UTC
Hi ,
I am defining a char* in C like this

char* name[10];
char* p="hello";
name[0]=p;
------------
Why does this throw an error ?
Whereas,

char* name[10][20];
char* p="hello";
name[0]=p;

Works perfectly fine !!
in a 2-D Char* array what does name, name[0], name[0][0] mean ??
Three answers:
?
2011-11-03 13:11:14 UTC
Your examples are switched. The first example has no errors, see https://ideone.com/CrZwW



The second example has an error: you can't assign to an array: https://ideone.com/7dbih



To answer the rest of the questions, given a 2D char* array

     char* name[10][20];



the expression "name" is a 10x20 2D array of pointers to char. In rvalue contexts it is implicitly converted to a pointer to a 1D array of 20 pointers to char



the expression "name[0]" is a 1D array of 20 pointers to char. In rvalue contexts it is implicitly converted to a pointer to pointer to char.



the expression "name[0][0]" is a pointer to char.



I suspect that the first example meant to use array of char, not an array of pointers to char:

     char name[10];

     strncpy(name, "hello", 10);
?
2011-11-03 20:25:05 UTC
char* name[10] - declaring an array of 10 pointers to characters

then name[0] = p would try to assign a pointer value to a character.

the correct way would be char* name[10][20];

name[0]=pointer to the 20-length "string"

name[0][0] = the value of the first character in the first string of the array.



Different compilers use different implementations, so what works in one may not work in another.
TheMadProfessor
2011-11-03 20:07:31 UTC
In the first case, 'name' is a pointer to an array of 10 characters, so name[0] is a character, not a character pointer and you can't assign p (a character pointer to the character array "hello") to it.



In the second case, name is an array of pointers to character arrays, so now it's just fine to set the first such instance to p.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...