I am trying to pass a string to a function and tokenize the string, but it gives me an access violation error when it tries to execute strtok.
int main(void) {
char String1[100];
// note: I read data into the string from a text file, but I'm not showing the code for it here
tokenize(String1);
return 0;
}
void tokenize(char data[]) {
strtok(data, ','); // gives me an access violation error
}
When I used strtok in main, it works, but not when I pass it to the function.
If your compiler is not giving you plenty of warnings about this code, please enable more warnings.
You need to #include <string.h> to get the prototype for strtok().
You either need a prototype for tokenize(), or more simply, just move its definition above main().
(Where your actual bug is) The second parameter of strtok() should be a char *, not a char. So change ',' to ",".
You should consult man strtok for more detail. And it's advisable to use strtok_r instead of strtok.
#include <stdio.h>
#include <string.h>
void tokenize(char data[]) {
char *token = data;
while (1) {
token = strtok(token, ",");
if (!token) {
break;
}
printf("token : %s\n", token);
token = NULL;
}
}
int main(void) {
char String1[] = "a,b,c,d,e,f,g";
// note: I read data into the string from a text file, but I'm not showing the
// code for it here
tokenize(String1);
return 0;
}
Related
I am unable to figure out how to assign a string to a struct variable using only <stdio.h> header file.
The following code gives me an error and I am unable to fix it.
#include <stdio.h>
struct Student
{
char name[50];
};
int main()
{
struct Student s1;
printf("Enter studen's name:\n");
scanf("%s",s1.name);
printf("Name : \n",s1.name);
s1.name={"Hussain"};
printf("Name : \n",s1.name);
}
It gives the following error while compilation:
test.c: In function 'main':
test.c:12:12: error: expected expression before '{' token
s1.name={"Hussain"};
^
I have tried initializing it in the following way:
s1.name="Hussain";
But this doesn't work too.
I could avoid this by the use of pointers as follows:
#include <stdio.h>
struct Student
{
char *name;
};
int main()
{
struct Student s1;
printf("Enter studen's name:\n");
scanf("%s",s1.name);
printf("Name : %s\n",s1.name);
s1.name="Hussain";
printf("Name : %s\n",s1.name);
}
This code works perfectly fine with no errors.
But I want to know where exactly I am doing wrong with the array, which is making my code not work.
A char array (and arrays in general) can't be assigned a value directly, only initialized. To write a string into a char array, use strcpy.
strcpy(s1.name, "Hussain");
The latter code where the name member is a pointer works for the assignment because the pointer is assigned the start address of the start of the string constant. Also note that you can't (at least not yet) use strcpy in that case because s1.name doesn't point anywhere. You would first need to allocate memory using malloc, or perform both steps at once using strdup. Also for this reason, you can't yet use scanf until you allocate memory.
If you're not allowed to use functions from string.h, then you would need to write the characters into the array one at a time, and then write a terminating null byte at the end.
Arrays do not have the assignment operator. So these assignment statements
s1.name = { "Hussain" };
s1.name = "Hussain";
are invalid.
You could use the standard C string function strcpy to copy elements of the string literal to the array s1.name like
#include <string.h>
//...
strcpy( s1.name, "Hussain" );
If you may not use standard string functions then you need to write a loop as for example
const char *p = "Hussain";
for ( char *t = s1.name; ( *t++ = *p++ ) != '\0'; );
Or
for ( char *t = s1.name, *p = "Hussain"; ( *t++ = *p++ ) != '\0'; );
Pay attention to that the second your program has undefined behavior. The pointer s1.name is not initialized and does not point to a valid object of an array type. So the call of scanf in this code snippet invokes undefined behavior.
struct Student s1;
printf("Enter studen's name:\n");
scanf("%s",s1.name);
If you can't use <string.h>, then you have to implement your own version of strcpy():
void copystring(char *dest, const char *src)
{
const char *p = src;
while (*p) {
*dest = *p;
p++;
dest++;
}
*dest = '\0'; // Null-terminate string (as pointed by #Ted)
}
Make sure that dest has enough space to hold src.
Also, avoid using scanf() in your code. Use fgets() as an alternative.
EDIT: As pointed by Jabberwocky, fgets() leaves \n read in the string. But since using <string.h> is not allowed, you have to implement your own function to replace it with a null-terminator:
int findchar(const char *str, char c)
{
int pos;
for (pos = 0; str[pos]; ++pos)
if (str[pos] == c)
return pos;
return -1;
}
You can use it like:
char str[100];
if (!fgets(str, sizeof str, stdin)) {
// fgets() failed. Do something.
} else {
int nwln = findchar(str, '\n');
if (nwln == -1) {
// You probably entered more than 100 characters
// because \n couldn't be found.
} else {
str[nwln] = '\0';
}
}
I'm new in c programming and I want to pass array from library.
I have function in library c file that creates char array. How to use this array in main function. This is short code of something I tried:
libfile.c
char *myArray;
void PopulateArray()
{
// Getting data from serial port in char buffer[100]
myArray = buffer;
}
libfile.h
exter char *myArray;
void PopulateArray();
program.c
int main()
{
// in fore loop
printf("%s\n" , myArray[i]);
}
This is just one of combinations that I have tried but nothing works.
How to do this?
To pass an array from a library function to the surrounding code, you can use the return value of a function or use a pointer-to-pointer argument.
See the following example code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* createSourceCopy() {
const char *source = "Example Text";
// We got some text in variable source;
const size_t sourceSize = strlen(source);
char *result = (char*)malloc(sizeof(char)*(sourceSize+1));
strncpy(result, source, sourceSize);
return result;
}
A user of your library could use the function like this:
main() {
char *result = createSourceCopy();
// Do something with result.
// After the use, destroy the array
delete[] result;
return 0;
}
Another way how to pass an array is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool copySourceText( char **outText ) {
const char *source = "Example Text";
// We get some text in variable source;
const size_t sourceSize = strlen(source);
*outText = new char[sourceSize];
strncpy(*outText, source, sourceSize);
return true; // success
}
This second variant has the benefit that the return value can be used as status. The function could return true on success, or false if there was an error.
This second version can be used like this.
int main() {
char *result;
if (copySourceText(&result)) {
// Do something with result.
// After the use, destroy the array
free(result);
result = NULL;
} else {
// Error handling
}
return 0;
}
It's not clear exactly what's going wrong in the code you posted (it would help to see more code), but assuming your problem isn't a compilation error, one of these lines might be wrong:
char *myArray;
printf("%s\n" , myArray[i]);
char *myArray declares a pointer to char (which would be appropriate for a single string).
The printf line dereferences myArray (producing a char, i.e. one character). You're passing down a char, but the %s format expects a pointer-to-char.
If you want to print the string character-by-character, you could use %c:
for (i = 0; i < length; i++) {
printf("%c\n", myArray[i]); /* or %x or %d if you want */
}
Otherwise, if myArray is one string and is null-terminated (see Why is a null terminator necessary?), then you could do:
printf("%s\n" , myArray); /* [i] removed, no for loop necessary */
The dreaded warning: passing argument 1 of ... makes integer from pointer without a cast
I just don't understand this. All I am trying to do is to pass a simple string (yes, I know a character array) to a function. The function parses the string and returns the first part. Can somebody please show me what I am doing wrong? Thank you!
char* get_request_type(char* buffer) {
char* p;
p = strtok(buffer, "|");
return p;
}
int main()
{
char buffer[30] = "test|something";
fprintf(stdout, "buffer: %s\n", buffer); //<-- looks great but needs parsing
char* request_type = get_request_type(buffer); //<-- error is here
fprintf(stdout, "%s\n", request_type); //<--expecting to see 'test'
}
There may yet come a day when I get comfortable working with strings in C, but that day is not this day...
You didn't include string.h, so the compiler will assume that strtok is defined as:
int strtok();
returns int and takes unknown number of arguments, it's call implicit function declaration. The solution is just to include string.h where strtok is declared.
This piece of the code works well. Post if there is still any problem.
#include<stdio.h>
#include<string.h>
char* get_request_type(char *buffer) {
char *p;
printf("----%s\n",buffer);
p = strtok(buffer, "|");
//fprintf("%s--->",p);
return p;
}
int main()
{
char buffer[30] = "test|something";
fprintf(stdout, "buffer: %s\n", buffer); //<-- looks great but needs parsing
char* request_type = get_request_type(buffer); //<-- No error here
fprintf(stdout, "request_type: %s\n", request_type);
return 0;
}
I have to write a function which takes in 2 double pointers (both to char type). The first double pointer has a string of query values and the 2nd one has stopwords. The idea is to eliminate the stopwords from the query string and return all the words without those stopwords.
For example
Input - query: “the”, “new”, “store”, “in”, “SF”
stopwords: “the”, “in”
OUTPUT
new
store
SF
I have written the following code while trying to use strtok which takes in only single pointers to char types. How do I access the contents of a double pointer?
Thanks
#include <stdio.h>
void remove_stopwords(char **query, int query_length, char **stopwords, int stopwords_length) {
char *final_str;
final_str = strtok(query[0], stopwords[0]);
while(final_str != NULL)
{
printf("%s\n", final_str);
final_str = strtok(NULL, stopwords);
}
}
For simplicity's sake, you can assume a double pointer to be equivalent to a 2d array (it is not!). However, this means that you can use array-convention to access contents of a double pointer.
#include <stdio.h>
#include <string.h>
char *query[5] = {"the","new","store","in","SF"};
char *stopwords[2] = {"the","in"};
char main_array[256];
void remove_stopwords(char **query,int query_length, char **stopwords, int stopwords_length);
int main()
{
remove_stopwords(query,5,stopwords,2);
puts(main_array);
return 0;
}
void remove_stopwords(char **query,int query_length, char **stopwords, int stopwords_length)
{
int i,j,found;
for(i=0;i<query_length;i++)
{
found=0;
for(j=0;j<stopwords_length;j++)
{
if(strcmp(query[i],stopwords[j])==0)
{
found=1;
break;
}
}
if(found==0)
{
printf("%s ",query[i]);
strncat(main_array,query[i],strlen(query[i]));
}
}
}
Output: new store SF newstoreSF
#Binayaka Chakraborty's solution solved the problem but I thought it might be useful to provide an alternative that used pointers only and showed appropriate use of strtok(), the use of which may have been misunderstood in the question.
In particular, the second parameter of strtok() is a pointer to a string that lists all the single-character delimiters to be used. One cannot use strtok() to split a string based on multi-character delimiters, as appears to have been the intention in the question.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void remove_stopwords(char *query, char **stopwords) {
char *final_str = strtok(query, " ");
while(final_str != NULL) {
int isStop = 0;
char **s;
for (s = stopwords; *s; s++) {
if (strcmp(final_str,*s) == 0) {
isStop = 1;
}
}
if (!isStop) printf("%s ", final_str);
final_str = strtok(NULL, " ");
}
}
int main() {
const char *q = "the new store in SF";
char *query = malloc(strlen(q)+1);
/* We copy the string before calling remove_stopwords() because
strtok must be able to modify the string given as its first
parameter */
strcpy(query,q);
char *stopwords[] = {"the", "in", NULL};
remove_stopwords(query,stopwords);
return 0;
}
The approach shown here also avoids the need to hard code the sizes of the arrays involved, which therefore reduces potential for bugs.
Can anyone explain why I am getting segmentation fault in the following example?
#include <stdio.h>
#include <string.h>
int main(void) {
char *hello = "Hello World, Let me live.";
char *tokens[50];
strtok_r(hello, " ,", tokens);
int i = 0;
while(i < 5) {
printf("%s\n", tokens[i++]);
}
}
Try this:
#include <stdio.h>
#include <string.h>
int main(void) {
char hello[] = "Hello World, Let me live."; // make this a char array not a pointer to literal.
char *rest; // to point to the rest of the string after token extraction.
char *token; // to point to the actual token returned.
char *ptr = hello; // make q point to start of hello.
// loop till strtok_r returns NULL.
while(token = strtok_r(ptr, " ,", &rest)) {
printf("%s\n", token); // print the token returned.
ptr = rest; // rest contains the left over part..assign it to ptr...and start tokenizing again.
}
}
/*
Output:
Hello
World
Let
me
live.
*/
You need to call strtok_r in a loop. The first time you give it the string to be tokenized, then you give it NULL as the first parameter.
strtok_r takes a char ** as the third parameter. tokens is an array of 50 char * values. When you pass tokens to strtok_r(), what gets passed is a char ** value that points to the first element of that array. This is okay, but you are wasting 49 of the values that are not used at all. You should have char *last; and use &last as the third parameter to strtok_r().
strtok_r() modifies its first argument, so you can't pass it something that can't be modified. String literals in C are read-only, so you need something that can be modified: char hello[] = "Hello World, Let me live."; for example.
A bunch of things wrong:
hello points to a string literal, which must be treated as immutable. (It could live in read-only memory.) Since strtok_r mutates its argument string, you can't use hello with it.
You call strtok_r only once and don't initialize your tokens array to point to anything.
Try this:
#include <stdio.h>
#include <string.h>
int main(void) {
char hello[] = "Hello World, Let me live.";
char *p = hello;
char *tokens[50];
int i = 0;
while (i < 50) {
tokens[i] = strtok_r(p, " ,", &p);
if (tokens[i] == NULL) {
break;
}
i++;
}
i = 0;
while (i < 5) {
printf("%s\n", tokens[i++]);
}
return 0;
}
strtok_r tries to write null characters into hello (which is illegal because it is a const string)
You have understood the usage of strtok_r incorrectly. Please check this example and documentation
And try & see this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char hello[] = "Hello World, let me live.";
char *tmp;
char *token = NULL;
for(token = strtok_r(hello, ", ", &tmp);
token != NULL;
token = strtok_r(NULL, ", ", &tmp))
{
printf("%s\n", token);
}
return 0;
}
I think it might be the char *tokens[50]; because you are declaring it a pointer when it is already a pointer. An array is already a pointer upon declaration. You mean to say char tokens[50];. That should do the trick.