get first char from *char[] variable in C
10,292
Solution 1
There are two main ways to do this. The first is to simply dereference the pointer.
C = *argv[4];
You can also do it via array subscript, which implicitly adds an offset to the pointer before dereferencing it.
Be sure to check whether it's null first, and so on. In general, you need to be careful when dealing with pointers.
Solution 2
argv[4]
is a char
array. You need to dereference that array to obtain a single element from it
C = *(argv[4]);
Author by
40detectives
Updated on June 04, 2022Comments
-
40detectives almost 2 years
i want to get the first character of a string (char[]) in C.
unsigned int N; unsigned int F; unsigned int M; char C; int main (int argc, char *argv[]){ if (argc!=5){ printf("Invalid number of arguments! (5 expected)\n"); exit(-1); } N = atoi(argv [1]); F = atoi(argv [2]); M = atoi(argv [3]); C = (char) argv[4]; //this way gives a wrong char value to variable C
The code above gives me the warning: cast to pointer from integer of different size.
EDIT: as pointed in comments, argv is char *[], not char[].
-
Daniel Fischer about 11 yearsI guess the
argc != 5
test counts as checking the validity in this case.