i am a beginner to coding and learning c language as my first step.
when i use string function the program returns with a value without showing output. using minGW as compiler
i tried to add string.h header folder
string
from below follows code
''''
#include <stdio.h>
#include <conio.h>
int main()
{
/*
int strlen(string);
*/
char name = { 's','i','l','a','m','\0' };
int length;
length = strlen(name);
printf("the length of %s is %d\n", name, length);
getch();
return 0;
}
'''
code ends here
expected to to print length of the char name but it crashes
as in build log
"Process terminated with status -1073741819 "
in build messages
warning: passing argument 1 of 'strlen' makes pointer from integer without a cast [-Wint-conversion]|
note: expected 'const char *' but argument is of type 'char'|
thanking you for looking into
You declare name as a char yet you treat it like an array. To declare name as a char array, use:
char name[] = { 's','i','l','a','m','\0' };
Also since you reference the function strlen(), you must add the header file:
#include <string.h>
Enjoy:
#include <stdio.h>
#include <string.h>
int main()
{
// single char can't store that string
// so we have to declare an array of chars
char name[] = {'s', 'i', 'l', 'a', 'm', '\0'};
// also we can use string literal syntax:
// char name[] = "silam";
int length = strlen(name);
printf("the length of %s is %d\n", name, length);
getc(stdin);
// i don't have <conio.h> so i call 'getc' instead of 'getch'
return 0;
}
Related
Hello I am new to C and I am trying to create a list of strings. But when I try to define the list uninitialized it gives me an error. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
int size;
char *sentence = "";
char *allWords[]; //incomplete type is not allowed
scanf("%d *[^\n]", &size);
fgets(sentence, size + 1, stdin);
return 0;
}
Instead of doing that you can just define a variable, BUFFER in this case for the lenght of the strings and ask for the size of the array list, then you can just make a for loop to store each value in a postion of the array list if you want with strcpy function (You cant use == to compare strings in C, that only work with chars because you're comparing ASCII value, for example 'a' == 97 is true).
#include <stdio.h>
#include <stdlib.h>
#define BUFFER 50
int main(){
int size;
char sentence[BUFFER];
printf("Introduce the size of the array list:");
scanf("%d", &size);
char allWords[size][BUFFER];
fgets(sentence, size + 1, stdin);
// Then you can insert the "sentence" in the array list with strcpy function included in <string.h>
strcpy(allWords[Position], sentence); //Position not declared in this case, is just an example, you can use this in a loop with a variable iterating each position of the array list
return 0;
}
Having an issue with reading in from the command line into an array of integers.
Intent is to parse the entered line by spaces/tabs and then atoi() each individual number into the appropriate array slot.
Relevant code:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main()
{
int nums[100];
int count = 0;
readInput(&nums, &count);
return 0;
}
functions.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
void readInput(int *nums[], int *count);
#endif // FUNCTIONS_H_INCLUDED
functions.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
#define delims " \t\r\n"
#define MAX_LEN 128
void readInput(int *nums[], int *count)
{
char *input = malloc(MAX_LEN);
char *buffer;
gets(input);
buffer = strtok(input, delims);
nums[(*count)++] = atoi(buffer);
while ((buffer = strtok(NULL, delims)) != NULL)
nums[(*count)++] = atoi(buffer);
buffer = strtok(NULL, delims);
}
The lines in functions.c with nums[(*count)++] = atoi(buffer); are flagging with the warning "warning: assignment makes pointer from integer without a cast".
And from main.c, the line readInput(&nums, &count); is flagging with "warning: passing argument 1 of 'readInput' from incompatible pointer type".
The odd thing is this program works when run and any attempts to add in casting or dereferencing has resulted in the warnings being subdued, but the program crashing when run.
When you declare your function:
void readInput(int *nums[], int *count);
the argument declaration int *nums[] is an array of pointers, not a pointer to an array which is what you call it like with &nums.
However, you don't need to pass a pointer to the array here. Arrays naturally decays to pointers to their first element. And when you declare an array as an argument to a function (like the declaration of nums in the function prototype above) it's really a pointer.
When you declare function arguments, a declaration like int nums[] is the same as int *nums.
So the declaration of readInput should really be
void readInput(int *nums, int *count);
If you do that change (including the function definition of course), and call it like
readInput(nums, &count);
then everything should work out fine.
this is the code, it is supposed to invert a string.
#include <stdio.h>
void StrRev(char str[]) {
int len=strlen(str);
char out[len];
int i;
for(i=0;i<len;i++){
out[i]=str[len-i-1];
}
printf("%s",out);
}
int main(void) {
StrRev("TestString");
return 0;
}
expected output:
gnirtStseT
actual output:
gnirtStseT#
the same thing happens with other inputs, while not on some others.
compiled with MingW on Code::Blocks
Two issues:
You fail to #include <string.h>, so there's no declaration for strlen. So the function is implicitly declared as int strlen(). So add that to the top of the file.
You also aren't adding the null terminating character to your reversed string.
After the for loop, set one additional character in the array to 0. Also, you'll need to make the array one larger to fit it.
#include <stdio.h>
// import declaration of strlen
#include <string.h>
void StrRev(char str[]) {
int len=strlen(str);
char out[len+1]; // increase length to make room for null terminator
int i;
for(i=0;i<len;i++){
out[i]=str[len-i-1];
}
out[i]=0; // add null terminator
printf("%s",out);
}
int main(void) {
StrRev("TestString");
return 0;
}
strlen() returns the length of the string without the null terminator at the end. So when you're copying over the characters, you're skipping the NULL at the end. If you simply use
int len=strlen(str) + 1;
instead of
int len=strlen(str);
Then everything should work.
I am starting to learn about pointers in C.
How can I fix the error that I have in function x()?
This is the error:
Error: a value of type "char" cannot be assigned to an entity of type "char *".
This is the full source:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void x(char **d, char s[]) {
d = s[0]; // here i have the problem
}
void main() {
char *p = NULL;
x(&p, "abc");
}
In function x() you pass d which is a char ** (a pointer to a string pointer), and char s[] (an array of char, passed as similarly to a pointer to char).
So in the line:
d = s[0];
s[0] is a char, whereas char **d is a pointer to a pointer to char. These are different, and the compiler is saying you cannot assign from one to the other.
However, did your compiler really warn you as follows?
Error: a value of type "char" cannot be assigned to an entity of type "char *"
Given the code sample, it should have said char ** at the end.
I think what you are trying to make x do is copy the address of the string passed as the second argument into the first pointer. That would be:
void x(char **d, char *s)
{
*d = s;
}
That makes p in the caller point to the constant xyz string but does not copy the contents.
If the idea was to copy the string's contents:
void x(char **d, char *s)
{
*d = strdup(s);
}
and ensure you remember to free() the return value in main(), as well as adding #include <string.h> at the top.
A more proper way would be to use strcpy:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void x(char **d) {
*d = malloc(4 * sizeof(char));
strcpy(*d, "abc");
}
int main() {
char *p;
x(&p);
printf("%s", p);
free(p);
return 0;
}
Outputs: abc
I have this array called arr_[6], having an idea of including six strings...but when I declare this array compiler throws error.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char arr_1[]= {"My_name","your Name", "His Name"};
char *arr_p;
arr_p = malloc(sizeof(char)*6);
arr_p = arr_1;
printf("%s\n",*arr_p);
system("PAUSE");
return 0;
}
Shown errors are as follows:
> main.c: In function `main': main.c:9: error: excess elements in char
> array initializer main.c:9: error: (near initialization for `arr_1')
> main.c:9: error: excess elements in char array initializer main.c:9:
> error: (near initialization for `arr_1')
>
> make.exe: *** [main.o] Error 1
Please help me!
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
const char *arr_1[]= {"My_name","your Name", "His Name"}; // has to be an array of <char *>
//arr_p is not necessary
printf("%s\n",*arr_1); // will print the first string, "My_name"
printf("%s\n",arr_1[1]); // will print the second string, "your Name"
printf("%s\n",arr_1[2]); // will print the third string, "His Name"
system("PAUSE");
return 0;
}
I believe what you're looking for is this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char* arr_1[]= {"My_name","your Name", "His Name", NULL};
char** arr_p;
arr_p = arr_1;
i = 0;
while (arr_p[i] != NULL)
{
printf("%s\n",(arr_p[i]));
++i;
}
system("PAUSE");
return 0;
}
These are the list of changes I've made:
Use char* arr_1[] to declare an array of strings, since each string is an array of characters.
If you need a pointer to a char*, you need to declare the pointer to be of datatype char**
Used NULL as the last element in the array, so that you know when you've reached the end of the array of strings.
Use a while loop to iterate over all the strings.