2-D character array - c

#include<stdio.h>
int main()
{
char str[3][10]={
"vipul",
"ss",
"shreya"
};
Why this won't work:
printf("%s",str[1][0]);
If i want to access str whereas
printf("%s",&str[1][0]);
or this would do it perfectly
printf("%s",str[1]);
Can anyone explain ?
Why is the first code giving an error
prog.c: In function ‘main’:
prog.c:9:5: error: format ‘%s’ expects argument of type ‘char *’, but
argument 2 has type ‘int’ [- Werror=format]
cc1: all warnings being treated as errors
Why does the argument has type int?

printf("%s",str[1][0]);
The problem is in this line. When For %s format specifier, printf() expects a pointer to a null terminated string. Whereas str[1][0] is simply a char (specifically the first s in "ss"), which is promoted to int (default argument promotions). That's exactly what the error message says.

Well
str[1] is a char* and str[1][0] is a char.
But when you use %s, printf() expect a pointer so you try to cast the char into a pointer.
So your char is promoted to an int.

It is said in the error:
format ‘%s’ expects argument of type ‘char *’
and your argument str[1][0] is a char, not the expected char *. In C, a char is treated as an int.

In first case printf("%s",str1[1][0]); you are passing single character to printf function and format specifier that you use it %s. For %s printf function expects string of character and not character.So it gives error.
As in 1st printf function you are specifying %s and you are passing character, argument promotion will takes place and char will promoted to int.
•The default argument promotions are char and short to int/unsigned int and float to double
•The optional arguments to variadic functions (like printf) are subject to the default argument promotions
More on Default argument promotion and here.

on your line error:
printf("%s",str[1][0]);
you try to print a string where you have a character ("%c" in printf)
so to only print one of ur 2D array you would have to do something like that:
int main()
{
int i;
char str[3][10]=
{
"vipul",
"ss",
"shreya"
};
i = 0;
while(str[0][i] != '\0')
{
printf("%c",str[0][i]);
i++;
}
}
which is pretty ugly ^^
instead you could print all ur 2D array with 3 single iteration with that:
int main()
{
int i;
char str[3][10]=
{
"vipul",
"ss",
"shreya"
};
i = 0;
while(i < 3)
{
printf("%s\n",str[i]);
i++;
}
}

Related

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] [duplicate]

#include <stdio.h>
int main(void)
{
int i,j,k;
char st;
printf("enter string\n");
scanf("%s", st);
printf("the entered string is %s\n", st);
}
Compiling above program gives me a warning:
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]
palindrom.c:8:1: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]
What am I doing wrong here?
This is what happens when I run it:
$ ./a.out
enter string
kiaaa
the entered string is (null)
Edit:
Here is another version of the code (made char st; into char *st):
#include <stdio.h>
int main(void)
{
int i,j,k;
char *st;
printf("enter string\n");
scanf("%s", st);
printf("the entered string is %s\n", st);
}
However, it behaves the same on runtime.
char st is a single character. Judging by the rest of your code, you probably intended to declare an array of characters:
char st[80];
scanf needs a pointer to char* to indicate you are scanning a string.
You are supplying a character that's allocated on the stack.
You either want to use a getchar() or make st a char array.
You have a type mis-match.
scanfis not type safe, You need to provide proper type. scanf enables you to get data from the input and you need to tell it what is the type of the data you want it to read. You ask it to read a string by specifying %s by provide it with a character variable.
You need an array:
#define MAX_LENGTH 256
char st[MAX_LENGTH];
As #Jerry rightly points out, You can just simple avoid all the hassle by using:
getline() instead of using scanf
st is type of char
&st is type of char *
Take care of the difference.
BTW, only one char cannot be used to store a string. Use char[] array.
As others have mentioned you want to create an array:
Change char st; to char st[10]; or whatever size array you want.
With the above change st is an array that has 10 individual elements that can hold a single char value.
char st is a character i.e it will store only one character try it like this
main()
char st [100];
scanf("%s",st);
just change these three lines and it will work it will except only single word strings
here you have declared the function as an int that is int main() keep it as main() and it will work
Use char *st; or an array like char st[50];.
When you complete the usage of a char pointer, you should deallocate the memory used by the pointer. This can be done using free(st); function.
EDIT : As you are printing string and if you are using pointer, you can do:
printf("the entered string is %s\n",st);
printf("the entered string is %s\n",*st); // This will work in both cases, if you use char *st or char st[50]

while giving string value to integer what is happening?

In my C program i assign a string in one integer variable and i print with percentage %s it will print that string with warning integer to pointer without cast and print with %d it print 134513904 then i change my string value and print with %d "134513904" is printing what is this value and how integer variable storing a string value in int variable?
enter code here
#include<stdio.h>
main()
{
int a="naveen";
printf("%d\n",a);
printf("\n%s\n",a);
if("naveen")
{
printf("hi");
}
int_point.c: In function ‘main’:
int_point.c:22:8: warning: initialization makes integer from pointer without a cast [enabled by default]
int a="naveen";
^
int_point.c:24:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
printf("\n%s\n",a);
^
134513920
naveen
hi
The following assigns a pointer (not a string) to s:
const char *s = "navven";
That means the following assigns a pointer (not a string) to a:
int a = "naveen";
Computers don't really see a difference between a pointer and number. They're both things that fit in their registers. And some people take advantage of that fact. So while the compiler warns you that you are doing something wrong, it still lets you treat the pointer as a number.
So a is ends up with the value of the pointer if it were an int. That's not safe to do. Not quite. While you can't use an int safely, you can use an intptr_t safely.
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
const char *p1 = "naveen";
printf("%p %s\n", p1, p1);
intptr_t i = (intptr_t)p1;
printf("0x%" PRIxPTR "\n", i);
const char *p2 = (const char*)i;
printf("%p %s\n", p2, p2);
return 0;
}
Output:
0x51ee878764 naveen
0x51ee878764
0x51ee878764 naveen

passing argument makes pointer from integer without a cast

I've read through several similar questions on Stack Overflow, but I've not been able to find one that helps me understand this warning in this case. I'm in my first week of trying to learn C though, so apologies if I've missed an obvious answer elsewhere on Stack Overflow through lack of understanding.
I get the following warning and note:
warning: passing argument 2 of ‘CheckIfIn’ makes pointer from integer without a cast [enabled by default]
if(CheckIfIn(letter, *Vowels) ){
^
note: expected ‘char *’ but argument is of type ‘char’
int CheckIfIn(char ch, char *checkstring) {
When trying to compile this code:
#include <stdio.h>
#include <string.h>
#define CharSize 1 // in case running on other systems
int CheckIfIn(char ch, char *checkstring) {
int string_len = sizeof(*checkstring) / CharSize;
int a = 0;
for(a = 0; a < string_len && checkstring[a] != '\0'; a++ ){
if (ch == checkstring[a]) {
return 1;
}
}
return 0;
}
// test function
int main(int argc, char *argv[]){
char letter = 'a';
char *Vowels = "aeiou";
if(CheckIfIn(letter, *Vowels) ){
printf("this is a vowel.\n");
}
return 0;
}
Vowels is a char*, *Vowels is just a char, 'a'. chars get automatically promoted to integers, which your compiler is allowing to be implicitly converted to a pointer. However the pointer value will not be Vowels, it will be the address equal to the integer encoding of the character 'a', 0x61 almost universally.
Just pass Vowels to your function.
In your case, the type conversion is from char to integer pointer. In some cases, the function takes void pointer as the second argument to accommodate for all the data-types.
In such cases, you would need to typecast the second argument as (void *)
This would be the function declaration in most well written modular functions:
int CheckIfIn(char ch, void *checkstring);
You would need to pass the argument as a void pointer, provided the Vowels is not a char pointer
if(CheckIfIn(letter, (void *)Vowels) ){
printf("this is a vowel.\n");
}

expected ‘const char *’ but argument is of type ‘char **’ in C

I am trying to write a function which searches the array looking for the specified key.The argument n specifies the effective size of the array,which must be sorted according to the lexicographic order imposed by strcmp.If the key if found,the function returns the index in the array at which that key appears.So ,it can return the index of the substring.However,it come two errors which I can't fix with.Please help.
jiebin#jiebin-ThinkPad-Edge-E530:~/Program_C/programming_abstractions_in_c/FindStringInSortedArray$ gcc FindStringInSortedArray.c -o FindStringInSortedArray
FindStringInSortedArray.c: In function ‘FindStringInSortedArray’:
FindStringInSortedArray.c:7:3: warning: passing argument 1 of ‘strlen’ from incompatible pointer type [enabled by default]
/usr/include/string.h:399:15: note: expected ‘const char *’ but argument is of type ‘char **’
jiebin#jiebin-ThinkPad-Edge-E530:~/Program_C/programming_abstractions_in_c/FindStringInSortedArray$
This is my code:
#include<stdio.h>
#include<string.h>
int FindStringInSortedArray(char *key,char *array[],int n)
{
int mid,cmp;
int low=strlen(array)-n;
int high=n;
if(low > high) return(-1);
mid = (low+high)/2;
cmp = strcmp(key,array[mid]);
if(cmp==0) return(mid);
if(cmp<0){
return(FindStringInSortedArray(key,array,n/2));
}else{
return(FindStringInSortedArray(key,array+n/2,n));
}
}
int main()
{
char key[2]="ab";
char *array[10]={"ab","bc","cd","de","ef","fg","gh","hi","ij","jk"};
int test=FindStringInSortedArray(key,array,10);
printf("Result:%d\n",test);
return 0;
}
int low=strlen(array)-n; is wrong. Pass the array size as different parameter like:
int FindStringInSortedArray(char *key,char *array[],int n, int arraysize)
Since arrays decay into pointers in functions. Declaration of strlen is of the form
strlen (const char*)
And you are passing *array[] whose type decays to char * *.
In C99 there are three fundamental cases where array name doesn't decay into pointers to first elements:
when it's the argument of the & (address-of) operator.
when it's the argument of the sizeof operator.
When it's a string literal of type char [N + 1] or a wide string literal of type wchar_t [N + 1] (N is the length of the string) which is used to initialize an array, as in char str[] = "foo"; or wchar_t wstr[] = L"foo";.
In C11, the newly introduced alignof operator doesn't let its array argument decay into a pointer either.
When you call strlen, it is expecting a char* (i.e. a string) as an argument, but you provide it with array which is a char** (i.e. an array of strings).
What you want is the size of the array, i guess. There is no way to know it, in C. The only way is to pass the size of the array as an argument :
int FindStringInSortedArray(char *key,char *array[],int n, int len)

atoi from string to Integer using char pointer

Here is the code I have written which splits a string in c and then I want to return the first integer value pointed by the char pointer.
#include<stdio.h>
void main(){
int month[12]={0};
char buf[]="1853 was the year";
char *ptr;
ptr = strtok(buf," ");
printf("%s\n",ptr);
int value = atoi(*ptr);
printf("%s",value);
}
EDIT:It gives me segmentation fault.
The problem is it is printing 1853 as the year, But I want to convert this into integer format.How can i retrieve that value as an integer using the pointer?
you are here trying to use an integer as a string:
printf("%s",value);
you should do
printf("%d",value);
Edit: yes, and also do int value = atoi(ptr); as added in another answer.
main should also be int, not void.
Also, what compiler are you using? With gcc 4.6 I got these errors and warnings when trying to compile your code (after adding some includes):
ptrbla.C:5:11: error: ‘::main’ must return ‘int’
ptrbla.C: In function ‘int main()’:
ptrbla.C:11:30: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive]
/usr/include/stdlib.h:148:12: error: initializing argument 1 of ‘int atoi(const char*)’ [-fpermissive]
ptrbla.C:12:26: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat]
I'd think you could get at least some of these from most compilers.
int value = atoi(ptr);
No need to dereference, atoi() expects a const char*, not a char.
printf("%d",value);
And you print an integer using %d or %i. %s is for string only.
BTW, maybe you would like to use strtol instead
char buf[]="1853 was the year";
char* next;
long year = strtol(buf, &next, 10);
printf("'%ld' ~ '%s'\n", year, next);
// 'year' is 1853
// 'next' is " was the year"
Use:
int value = atoi(ptr);
atoi should get a character pointer, which is what ptr is. *ptr is the first character - 1 in this case, and anyway isn't a pointer, so it's unusable for atoi.

Resources