i tried to take input from user
input type is not determined(can be char or int)
i wanna take input and store in pointer array
while i doing that job forr each pointer i wanna take place from leap area
that is using malloc
but belo开发者_JS百科w code doesnot work why???
int main(void)
{
char *tutar[100][20],temp;
int i;
int n;
i=0;
while(temp!='x')
{
scanf("%c",&temp);
tutar[i]=malloc(sizeof(int));
tutar[i]=temp;
++i;
}
n =i;
for(i=0;i<=n;++i)
{
printf(" %c ",*tutar[i]);
}
printf("\n\n");
/*for(i=0;i<=n;++i)
{
printf("%d",atoi(*tutar[i]));
}
*/
}
note that; this cite has problem when rewrite(edit) the previous mail it is general problem or not
There are several problems in your code, including:
- you declare
tutar
as a two-dimensional array of pointers to character, then use it as a one-dimensional array tutar[i]=temp
assigns the value of temp (a char) to tutar[i] (a pointer to char), effectively overwriting the pointer to the newly reserved memory block- you don't initialize
temp
, so it will have garbage value - occasionally it may have the valuex
, in which your loop will not execute
Here is an improved version (it is not tested, and I don't claim it to be perfect):
int main(void)
{
char *tutar[100], temp = 0;
int i = 0;
int n;
while(temp!='x')
{
scanf("%c",&temp);
tutar[i]=malloc(sizeof(char));
*tutar[i]=temp;
++i;
}
n =i;
for(i=0;i<=n;++i)
{
printf(" %c ",*tutar[i]);
}
printf("\n\n");
}
Note that unless you really need to allocate memory dynamically, you would be better off using a simple array of chars:
char tutar[100], ...
...
while(temp!='x')
{
scanf("%c",&temp);
tutar[i++]=temp;
}
...
For the sake of brevity, I incremented i
within the assignment statement.
精彩评论