Accessing an array referenced by a pointer in C - c

I am new to programming in C and am trying to write a simple function that will compare strings. I am coming from java so I apologize if I'm making mistakes that seem simple. I have the following code:
/* check if a query string ps (of length k) appears
in ts (of length n) as a substring
If so, return 1. Else return 0
*/
int
simple_substr_match(const unsigned char *ps, /* the query string */
int k, /* the length of the query string */
const unsigned char *ts, /* the document string (Y) */
int n /* the length of the document Y */)
{
int i;
for(i = 0;i < n;i+k){
char comp;
comp = ts->substring(i,k);
if (strncmp(comp, ps, k)) {
return 1;
}
}
return 0;
}
When trying to compile i get the error: request for member 'substring' in something not a structure or union.
The idea of the code is describe in the code comment but just to elaborate I am looking to see if ps occurs as a substring of ts in increments of k(length of ps).
What am I doing wrong and how can I fix it? Is there a better way of doing what I am trying to do?

Change
for(i = 0;i < n;i+k){
char comp;
comp = ts->substring(i,k);
if (strncmp(comp, ps, k)) {
return 1;
}
}
to
for(i = 0;i < n-k;i++){
if (!strncmp(ts+i, ps, k)) {
return 1;
}
}

ts is a char* not a class (and you're writing in C, not C++)
How about using the standard 'strstr' C function?
if (strstr(ts, ps) != NULL) {
return 1;
} else {
return 0;
}

C doesn't have member functions. and in c++ char doesn't have a member function substring.
you should use ts as an character array.

Something like this?
#define simple_substr_match(ps,ts) (strstr(ts,ps) != NULL)

Related

segmentation fault (core dumped) error when trying to copy from an array

trying to copy stuff from b into a but i get that error
someone told me it means i'm trying to access memory that i'm not allowed to, but i don't know what should i do to make it compile.
replace(txt , code);
string replace(string a , string b)
{
string alpha[26] = {"abcdefghijklmnopqurstuvwxyz"};
for (int i = 0; i < strlen(a); i++)
{
for(int n = 0; n < 26; n++)
{
if(a[i] == alpha[n])
{
a[i] = b[n];
i++;
}
}
}
return word;
}
i'm a beginner so no comments about clean coding or syntactic sugar or stuff like that just help me resolve this please
It looks like you have some problems with understending pointers, so I recommend you to read about them. Also consider reading about datatypes and types from STL you are using. (cause std::string is already an array of values so, when you are creating std::string[26], you actually are creating pointer to a pointer)
I guess you have are trying to do something like that:
std::string replace(string a , string b)
{
std::string alpha = {"abcdefghijklmnopqurstuvwxyz"};
for (size_t i = 0; i < a.size(); ++i)
{
for(size_t n = 0; n < alpha.size(); ++n)
{
if(a[i] == alpha[n])
{
a[i] = b[n];
i++; // Also, I think you doesnt need this line, cause you already incrementing i in for loop
}
}
}
return a;
}
Also you have used strlen() on your string, that also is not really correct, cause it is used on char values. If you whant to get length of a string it is better to use string.lenght()
Also, It is better to use size_t or unsigned int instead of int in this case, cause you don't need negative numbers in order to parce these strings. ()

How to "delete" every element in array by value in C

I have been trying to solve this problem for about 5 days..can't find any solution please send help. I am supposed to implement a function to "delete" every element in an array by value. Let's say my array is "Hello" and I want to delete every "l". So far I can only delete l once. By the way keep in mind I am not allowed to use pointers for this function...(we haven't learned that yet in my school) Here's my code:
#include <stdio.h>
#include <string.h>
void strdel(char array[], char c);
int main(void)
{
char source[40];
printf("\nStrdel test: ");
strcpy(source, "Hello");
printf("\nsource = %s", source);
strdel(source, 'l');
printf("\nStrdel: new source = %s", source);
return 0;
}
void strdel(char array[], char c)
{
int string_lenght;
int i;
for (string_lenght = 0; array[string_lenght] != '\0'; string_lenght++) {}
for (i = 0; i < string_lenght; i++) {
if (array[i] == c) {
for (i = i; array[i] != '\0'; ++i)
array[i] = array[i + 1];
}
}
}
Simple use 2 indexes, one for reading and one for writing. #Carl Norum
void strdel(char array[], char c) {
int read_index = 0;
int write_index = 0;
while (array[read_index] != '\0') {
if (array[read_index] != c) {
array[write_index] = array[read_index];
write_index++; // Only advance write_index when a character is copied
}
read_index++; // Always advance read_index
}
array[write_index] = '\0';
}
The has O(n) performance, much faster than using nested for() loops which is O(n*n).
Details:
OP: By the way keep in mind I am not allowed to use pointers for this function.
Note that array in void strdel(char array[], char c) is a pointer, even though it might look like an array.
int for array indexing is OK for learner and much code, yet better to use size_t. int may lack the range needed. Type size_t is an unsigned type that is neither too narrow nor too wide for array indexing needs. This becomes important for very long strings.
Your problem is related to using the variable i in both loops. So once the inner loop is executed, outer loop will terminate right after.
Use another variable for the inner loop.
void strdel(char array[], char c)
{
int string_lenght;
int i, j;
for (string_lenght = 0; array[string_lenght] != '\0'; string_lenght++) {}
for (i = 0; i < string_lenght; i++) {
if (array[i] == c) {
for (j = i; array[j] != '\0'; ++j) // Use variable j instead of i
array[j] = array[j + 1];
--i; // Decrement i to "stay" at the same index
--string_lenght; // As one character were just removed
}
}
}
The above shows how to make OPs approach work. For a better solution see the answer from #chux : https://stackoverflow.com/a/53487767/4386427

Segmentation Fault when returning integer

I recently joined Stackoverflow community because I had to ask this question. I've been searching for possible explanations and solutions on the website but so far nothing enlightened me as I wanted. My error is probably caused by a very specific line of code. I'm trying to create a function that reads an array of struct votes, (struct contains integer member number, char *category, char *nominee) and copies all the votes that contain the same number and category to another array of struct. Basically to show all the repeated votes.
typedef struct
{
int member;
char *categ;
char *nom;
}Vote
Vote vote(int member, char *categ, char *nom)
{
Vote result;
result.member = member;
result.categ = categ;
result.nom = nom;
return result;
}
int votes_count(Vote *v, int n, Vote *v1)
{
int result = 0;
int *index = malloc(sizeof(int) * 1000);
int a = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
if (a == 0 && v[i].member == v[j].member && strcmp(v[i].categ, v[j].categ) == 0)
{
v1[result++] = vote(v[j].member, str_dup(v[j].categ), str_dup(v[j].nom));
index[a++] = j;
}
for (int b = 0; b < a; ++b)
{
if( a > 0 && v[i].member == v[j].member && strcmp(v[i].categ, v[j].categ) == 0 && j != index[b])
{
v1[result++] = voto(v[j].member, str_dup(v[j].categ), str_dup(v[j].nom));
index[a++] = j;
}
}
}
}
return result;
}
Afterwads, it returns the number of elements of new array that contains all repetitions. I want to use an array of ints to save all line indexes so that the function doesn't read and copy the lines it already accounted.
Sorry if the code is hard to understand, if needed I can edit to be more understandable. Thanks for any answears.
P.S: I'm portuguese, sorry in advance for grammar mistakes
if your only intention is to harvest the duplicates, you only need to compare to the elements that came before an element
you don't need the index[] array
For simplicity, I used two integer arrays, you should change them to your struct arrays, also change the compare function.
unsigned fetchdups(int orig[], int dups[], unsigned count)
{
unsigned this, that, ndup=0;
for (this=1; this<count; this++){
for (that=0; that<this; that++){
/* change this to your compare() */
if(orig[that] == orig[this]) break;
}
if (this == that) continue; /* no duplicate */
dups[ndup++] = this;
}
return ndup;
}

Having trouble making memset function?

void memSet(char destination[], char valueMemSet, int numOfValue)
{
char temp;
int j=1;
for (int i = 0; i <= numOfValue; i++)
{
temp = destination[i];
destination[i] = valueMemSet;
destination[j] = temp;
j++;
}
}
The array is originally "this is the source Concatenate means to link."
This is what I am trying to get "------this is the source Concatenate means to link."
This is What I am currently getting "-------Tthe source Concatenate means to link."
When I ran the debugger it saves the first letter of the array but every single one after gets replaced.
How can I solve this issue?
memset() is a function, which sets a particular value in a given memory, like you want to initialize total array's elements to some particular value(for eg - zero). So it will set the same in that array.
what you need here is strcat() function.
Is that what you need?
void memSet(char destination[], char valueMemSet, int numOfValue, int len)
{
int j=len-numOfValue;
for (int i = len-1;i>=numOfValue;i--) {
destinstion[i] = destination[j--];
}
for (int i = 0; i < numOfValue; i++)
{
destination[i] = valueMemSet;
}
}

IN operator in C

Can I use the "IN" operator in C?
For instance, in searching an array, can I say:
if(a in array[i])
{
printf("%d \n", array[i]);
}
In Python, we may say this.
There's no built-in C syntax that does this. You can write a function that does. Ie, if array[i] is an array of ints:
int in(int n, int* arr, int len) {
int i;
for (i = 0; i < len; ++i) {
if (arr[i] == n) {
return 1;
}
}
return 0;
}
In some contexts such a function might already exist in the standard library. As n.m pointed out, strchr finds a pointer to first occurence of a character in a character array, or else NULL, so you can do strchar(array[i], a) == NULL if array[i] is a character array.
No there's no in in C language.
If want, you can call a function passing the variable a to check if it is there in the array or not, using linear search(or binary depending on the data).
if(isKey(a,array)) // if(in(a,array))
{
}
int isKey(int a, int* array, int size)
{
// code to search element is present return 1 if present else 0
}
EDIT :- It was supposed to be a pointer mistake while . and edited for size.

Resources