I receive a pointer numeric value like: 0xbfe0e6ac it is possible set int foo for example to value of 0xbfe0e6ac that is another int in memory?
My scenario:
I am tried to implement functions for get next index from array passing the pointer value (like the above example) as parameter.
For example:
char * a = "baa";
char* b = "foo";
printf("%c", cgetnext(&a)); // b
printf("%c", cgetnext(&a)); // a
printf("%c", cgetnext(&b)); // f
printf("%c", cgetnext(&b)); // a
The single way that I can see to do this is: in cgetnex() save pointer of array passed like parameter into array and each call, check if the array passed as paramater was used before and get information of it, like lasindexused and pointer value into RAM.
Here is my code:
#include <string.h>
#include <stdlib.h>
typedef struct { int pLocation; int lastIndex; } POINTERINFORMATION;
int __myIndex;
POINTERINFORMATION pointersLocations[256];
int pointersLocationsLength;
char * temparr = NULL;
__myIndex = pointersLocationsLength = 0;
int
plAdd (int p)
{
if (plLen >= sizeof(pointersLocation)) {
return -1;
} else {
pointersLocation[pointersLocationsLength].pLocation = p;
pointersLocation[pointersLocationsLength].lastindex = 0;
pointersLocationsLength ++;
return pointersLocationsLength;
}
}
int
getPointer (int p, POINTERINFORMATION ** out)
{
int i;
for (i = 0; i < pointersLocationsLength; i++)
{
if(pointersLocation[pointersLocationsLength].pLocation == p)
{
*out = makevariablefromponiter(pi.pLocation);
return 1;
}
}
return 0;
}
char
cgetnext(char * arr)
{
char * myarr;
const size_t size = sizeof(char *) + 1;
myarr = malloc(size);
if (NULL == arr){
POINTERINFORMATION * pi;
if (getPointer(p, &pi))
{
__myIndex = pi.lastindex;
myarr = makevariablefromponiter(pi.pLocation);
}
} else {
myarr = strdup (arr);
}
if (strlen(myarr) == __myIndex) {
return '\0';
} else {
__myIndex ++;
temparr = malloc(size);
temparr = strdup(myarr);
return myarr[__myIndex - 1];
}
}
Yes, do something like this:
int *fooPtr = 0xbfe0e6ac;
foo = *fooPtr;
In fact, you can make it even more concise:
foo = *(int *) 0xbfe0e6ac;
Related
I'm trying to create a program which returns the Longest repeated substring. I've almost got the solution, but for some reason my strcmp gives an error when he is busy to find the LRS. Could someone explain me why there is an error and how I solve this?
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NSTRINGS 4
char* searchLongestRepeatedSubstring(char* string);
char** makeSuffixArray(char* string);
void freeSuffixArray(char** suffixArray);
int cmp(const void*a, const void* b);
/* do not change this code */
int main(void)
{
char* strings[NSTRINGS] = {
"bananas",
"ask not what your country can do for you, but what you can do for your country",
"main",
"" };
char* result;
for (int i = 0; i < NSTRINGS; ++i)
{
result = searchLongestRepeatedSubstring(strings[i]);
if (result != NULL)
{
/* write out LRS */
printf("%s: \"%s\"\n", strings[i], result);
/* free() the result */
free(result);
result = NULL;
}
else
printf("Geen longest repeated substring.\n");
}
return 0;
}
/**
* Finds the LRS from a string using the function makeSuffixArray
*
* #param the given string
* #return the longest repeated substring
*/
char* searchLongestRepeatedSubstring(char* string)
{
char **p;
p = makeSuffixArray(string);
size_t length = strlen(string);
int max_sz = 0;
char max_word;
int curr_sz = 0;
int curr_word;
char* word1;
char* word2;
char s1, s2;
size_t length1;
size_t length2;
for (size_t i = 0; i < length; i++)
{
for (size_t j = i + 1; j < length; j++)
{
word1 = p[i];
word2 = p[j];
length1 = strlen(word1);
length2 = strlen(word1);
for (size_t x = 0; x < length1; x++)
{
s1 = word1[x];
for (size_t y = 0; y < length2; y++)
{
s2 = word2[y];
if (strcmp(s1, s2) == 0) {
curr_sz++;
strcat(curr_word, s1);
x++;
}
else
break;
}
}
if (curr_sz > max_sz) {
max_sz = curr_sz;
curr_sz = 0;
max_word = curr_word;
curr_word = "";
}
else {
curr_sz = 0;
curr_word = "";
}
}
}
return max_word;
}
/**
* Creates the suffix array of the given string
*
* #param the given string
* #return the suffix array
*/
char** makeSuffixArray(char* string)
{
size_t length = strlen(string);
char **p = (char**)malloc(length * sizeof(char*));
for (size_t i = 0; i < strlen(string); i++)
{
p[i] = &string[i];
puts(p[i]);
}
qsort(p, length, sizeof(char*), cmp);
return p;
}
int cmp(const void* a, const void* b)
{
char ** p = (char**)a;
char ** t = (char**)b;
return strcmp(*p, *t);
}
/**
* free() the memory allocated for the suffix array
*
* #param the given suffix array
*/
void freeSuffixArray(char** suffixArray)
{
free(suffixArray);
}
In your function char* searchLongestRepeatedSubstring-
if (strcmp(s1, s2) == 0) {
s1 and s2 are both char variables , and you pass them to strcmp which expects const char * as arguments , therefore, your compiler complaints .
You can compare them like this-
if(s1==s2)
Also this statement in same if block -
strcat(curr_word, s1);
instead you can do this -
size_t len=strlen(curr_word);
curr_word[len]=s1; // make sure curr_word is large enough
curr_word[len+1]='\0';
I want to write a function to transform an array of n doubles to an string, a show function, something like:
struct vec { uint64_t n; double *x; };
char *show(struct vec *v) {...}
Notice that I don't want to print them, only do a serialization into a string.
How can I do this in C?
You can do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_DOUBLE_LENGTH 15
typedef struct
{
size_t n;
double* x;
} DoubleArray;
int ShowArray(const DoubleArray* const doubleArrayPtr, char** const resultStringPtr)
{
int errorCode = 0;
char* tempStr = NULL;
char str[MAX_DOUBLE_LENGTH + 2]; /* 1 for trailing space and 1 for null-terminator */
size_t N = 0;
size_t i = 0;
if (doubleArrayPtr == NULL || resultStringPtr == NULL)
{
errorCode = 1;
}
else
{
if (doubleArrayPtr->n != 0)
{
/*
calculating max string length from:
str = <double01> <space> <double02> <space> <double03> <null-terminator>
ex.: str = '3.25 4.75 0.01 5.678\0'
*/
N = doubleArrayPtr->n * MAX_DOUBLE_LENGTH + doubleArrayPtr->n;
tempStr = malloc(N * sizeof(*tempStr));
if (tempStr == NULL)
{
errorCode = 1;
}
else
{
memset(tempStr, 0, N * sizeof(*tempStr));
for(i = 0; i < doubleArrayPtr->n; i++)
{
sprintf(str, "%.6f ", doubleArrayPtr->x[i]);
strcat(tempStr, str);
}
tempStr[strlen(tempStr) - 1] = '\0';
/* string formed -- allocating buffer for result */
(*resultStringPtr) = malloc((strlen(tempStr) + 1) * sizeof(**resultStringPtr));
if ((*resultStringPtr) == NULL)
{
errorCode = 1;
}
else
{
/* exporting result */
memcpy((*resultStringPtr), tempStr, strlen(tempStr) * sizeof(*tempStr));
(*resultStringPtr)[strlen(tempStr)] = '\0';
}
}
free(tempStr);
tempStr = NULL;
}
}
return errorCode;
}
int main(void)
{
/* test code part */
DoubleArray d;
char* s = NULL;
size_t i = 0;
srand(time(NULL));
d.n = rand() % 21;
d.x = malloc(d.n * sizeof(*d.x));
for(i = 0; i < d.n; i++)
{
d.x[i] = (rand() % 99999) / 100.0;
printf("[%d] = %f\n", i, d.x[i]);
}
ShowArray(&d, &s);
printf("str = '%s'\n", s);
free(d.x);
free(s);
return 0;
}
I am trying to compare two arrays. Both of these arrays contain 15 characters. I want to see if they have the same element or not.
characters being read in to the array
Array1: ATGGAATTCTCGCTC
Array2: TTGGAATTCTAGCTC
These are both in the form of arrays and are being passed in as arrayt and arraymt. n_size and m_size are the size of each array.(this is because the arrays can be any length 1-15)
int mutations(char arrayt[],char arraymt[],int n_size,int m_size)
{
int i=0,mutation=0;
do{
for(i=0;i<n_size;i++)
{
if (arrayt[i]==arraymt[i])
{
mutation=1;
}
}
}while(n_size == m_size);
return mutation;
}
This is the code I have so far for finding the differences in the two arrays. Problem is I don't know of a way that I can return if there is a difference for each of the elements. 1 is for a change and 0 is no change.
If anything is unclear let me know and I will try and clarify.
The code you required may be:
int* mutations(char arrayt[],char arraymt[],int n_size,int m_size)
{
int i, size;
int* mutation;
// size = min(m_size,n_size)
if n_size>m_size
size=m_size;
else
size=n_size;
endif
mutation=*malloc( sizeof(int) * size); // allocate memory for return value
for(i=0;i<size;i++)
{
if (arrayt[i]==arraymt[i])
{
mutation[i]=1;
} else {
mutation[i]=0;
}
}
return mutation;
}
Let's use 15 bits of an unsigned to record the results.
unsigned mutations(char arrayt[], char arraymt[], int n_size, int m_size) {
int sizemin = min(n_size, m_size);
int sizemax = max(n_size, m_size);
unsigned dest = 0;
int i;
for (i = 0; i < sizemin; i++) {
if (arrayt[i] == arraymt[i])
dest |= 1 << i;
}
for (; i < sizemax; i++) {
dest |= 1 << i; // compares against empty values are set to 1
}
return dest;
}
void foo(void) {
const char *Array1 = "ATGGAATTCTCGCTC";
const char *Array2 = "TTGGAATTCTAGCTC";
unsigned result = mutations(Array1, Array2, strlen(Array1), strlen(Array1));
// LSBit contains the result of the compare of Array1[0] vs. Array1[1]
printf("%X\n", result);
}
void mutations(char arrayt[],char arraymt[], int *result, int max_index)
{
int i = 0;
for (i = 0; i < max_index; i++)
{
if (arrayt[i] == arraymt[i])
{
result[i] = 0;
continue;
}
else
{
result[i] = 1;
}
}
}
int main()
{
int i = 0;
int max_index;
int *res;
char arrayt[] = "aabbccduu";
char arraymt[] = "aabcccd";
max_index = strlen(arrayt) <= strlen(arraymt) ? strlen(arrayt) : strlen(arraymt);
res = calloc (1, sizeof(int) * max_index);
if (res != NULL)
{
mutations(arrayt, arraymt, res, max_index);
while (i < max_index)
{
printf("res[i] = %d\n", res[i]);
i++;
}
free(res);
}
return 0;
}
I have a struct:
typedef struct myStruct {
char** a;
char** b;
} myStruct;
I am trying to read from stdin and initialize an array of myStruct*
int main() {
int maxlength = 60 + 1;
int arraySize = 2;
myStruct** myArray = (myStruct*) malloc(sizeof(myStruct*) * arraySize);
int runningIndex = 0;
while(1) {
char* aline = (char*) malloc(maxlength);
int status = getline(&aline, &maxlength, stdin);
if(status == -1)
break;
char* bline = (char*) malloc(maxlength);
getline(&bline, &maxlength, stdin);
if(runningIndex == arraySize) {
arraySize *= 2;
myArray = realloc(myArray, sizeof(myStruct*) * arraySize);
}
myArray[runningIndex] = (myStruct*) malloc(sizeof(myStruct*));
myArray[runningIndex]->a = &aline;
myArray[runningIndex]->a = &bline;
runningIndex++;
}
for(int i = 0; i < runningIndex; i++) {
printf("outside the loop at index %d, a is %s and b is %s", i, *myArray[i]->a, *myArray[i]->b);
}
}
I did a few printf within the while to confirm that each myStruct is successfully created with the strings from stdin. However, outside the loop, all the stored values seems to be gone. I was thinking about scope but could not figure out why. Could someone explain how I shall do this properly? Thanks!
sample to fix :
#include <stdio.h>
#include <stdlib.h>
typedef struct myStruct {
char *a;
char *b;
} myStruct;
int main() {
int maxlength = 60 + 1;
int arraySize = 2;
myStruct* myArray = malloc(sizeof(myStruct) * arraySize);
int runningIndex = 0;
while(1) {
char *aline = malloc(maxlength);
int status = getline(&aline, &maxlength, stdin);
if(status == -1)
break;
char *bline = malloc(maxlength);
getline(&bline, &maxlength, stdin);
if(runningIndex == arraySize) {
arraySize *= 2;
myArray = realloc(myArray, sizeof(myStruct) * arraySize);
}
myArray[runningIndex].a = aline;//&aline is address of local variable.
myArray[runningIndex].b = bline;//And content is rewritten in each loop.
runningIndex++;
}
for(int i = 0; i < runningIndex; i++) {
printf("outside the loop at index %d, a is %s and b is %s", i, myArray[i].a, myArray[i].b);
}
//deallocate
return 0;
}
A single string pointer is defined like this:
char *pStr;
An array of string pointers is defined like this:
char **pStrArr;
To dynamically create memory for a single string, do this:
pStr = malloc(STRING_LEN);
To dynamically create memory for an array of strings, do this:
pStrArr = (NUM_STRINGS * (*pStrArr));
for(str = 0; str < NUM_STRINGS; str++)
pStrArr[str] = malloc(STRING_LEN);
In your case, you'd need to create either two char strings for your struct or two arrays of char strings, whatever your requirements are. It looks like you really only need two single strings. If so, do this:
typedef struct
{
char* a;
char* b;
} myStruct;
myStruct structure;
structure.a = malloc(STRING_LEN);
structure.b = malloc(STRING_LEN);
I've tried using a tripple pointer, but it keeps failing. Code:
#include <stdlib.h>
#include <stdio.h>
int set(int *** list) {
int count, i;
printf("Enter number:\n");
scanf("%d", &count);
(*list) = (int **) malloc ( sizeof (int) * count);
for ( i = 0; i<count;i++ ) {
(**list)[count] = 123;
}
return count;
}
int main ( int argc, char ** argv )
{
int ** list;
int count;
count = set(&list);
return 0;
}
Thanks for any advice
What you call list is actually an array. You might do it the following way:
#include <stdlib.h>
#include <stdio.h>
ssize_t set(int ** ppList)
{
ssize_t count = -1;
printf("Enter number:\n");
scanf("%zd", &count);
if (0 <= count)
{
(*ppList) = malloc(count * sizeof **ppList);
if (*ppList)
{
size_t i = 0;
for (; i < count; ++i)
{
(*ppList)[i] = 42;
}
}
else
{
count = -1;
}
}
return count;
}
int main (void)
{
int * pList = NULL;
size_t count = 0;
{
ssize_t result = set(&pList);
if (0 > result)
{
perror("set() failed");
}
else
{
count = result;
}
}
if (count)
{
/* use pList */
}
...
free(pList);
return 0;
}
As far as I understand your question you want to return an array which is allocated in another function : here is the simple version of this
#include<stdio.h>
#include<stdlib.h>
int* set(int *list) {
int count, i;
printf("Enter number:\n");
scanf("%d", &count);
list = (int *) malloc ( sizeof (int) * count);
for ( i = 0; i<count;i++ ) {
list[i] = 123;
}
return list;
}
int main ( int argc, char ** argv )
{
int *list;
list = set(list);
//Use whatever you want to do with that array
free(list); // don't forget to free
return 0;
}
you have an array of integer arrays. Let's look at your set function closely:
for (i = 0; i < count;i++ ) {
(**list)[count] = 123;
}
As you can see you are treating every array object like an integer value.
That should be a nested loop:
for (i to n)
// allocate each array
for (k to m)
// assign value for each value of array