How to delete a string from an array of string in c - c

I have a multidimensional array in which I put words inside. After, I ask the user to delete a word. But it won't delete.
#include<stdio.h>
void main ()
{
int i ;
int nbr ;
char n[50][50];
char d[50];
printf("Enter the number of word you want : \n");
scanf("%d",&nbr);
for(i=0; i < nbr ; i++)
{
printf("Enter words : \n");
scanf("%s",&n[i]);
}
printf("you have enter: \n");
for(i = 0; i < nbr ; i++)
{
printf("%s \n",n[i]);
}
printf("Which word you want to remove : ? \n");
scanf("%s",&d);
for(i=0; i < nbr ; i++)
{
if(strcmp(n[i],d)==0)
{
n[i] = n[i+1] ;
i-- ;
}
}
printf("The rest of array is : \n");
scanf("%s",&n[i]);
}
[Error] assignment to expression with array type

Although arrays are implemented with pointers in C, the compiler will treat them the differently. As you can see in your own example the line n[i] = n[i+1] causes the error you see, because n[i] is an array of chars.
Even if you could make the assignment you wanted, the logic of your program still has an error. If you were able to succeed in your call to n[i] = n[i+1] you would effectively be duplicating whatever was in n[i+1] twice.
Instead you likely want to copy n[i+1] into n[i], then copy n[i+2] into n[i+1] and so on. This will be expensive, you may want to look into using a linked list instead, although this really depends on what else you want to do with this data structure.

[Error] assignment to expression with array type
In C an array can not be assigned.
You need to copy the content of the source array are into the destination array.
For the special case of a 0-terminated chararray (aka C-string) you can use the strcpy() function to do so:
strcpy(n[i], n[i+1]);

Related

how to remove the comma at the end of the last number? [duplicate]

This question already has answers here:
How i can remove the last comma from the output? in c
(2 answers)
Closed 2 months ago.
For example, if I entered the array size to be 5, I will enter 5 elements. Then the elements should print out like n1,n2,n3,n4,n5
To visualize it better here is an example:
Input would be:
Enter array size: 4
Enter element 1: 7
Enter element 2: 14
Enter element 3: 21
Enter element 4: 28
And the output should be printed as:
{7,14,21,28}
But instead, the output that I get from the code is:
{7,14,21,28,}
There is a comma at the end of the number. But I want the comma to print in between the number and no comma at the end of the last number. I didn't know what to add or remove from the I the code I already have.
Here is the code:
#include <stdio.h>
int main() {
int size, i, element [100];
printf("Enter array size: ");
scanf("%d", &size);
for(i=0; i<size; i++) {
printf("Enter element %d: ",i+1);
scanf("%d", &element[i]);
}
printf("{");
for (i = 0; i < size; i++) {
printf("%d,", element[i]);
}
{ printf("}");
}
return 0;
}
I suggest you rewrite your loop to print a leading comma instead, and then print the first value before the loop:
if (size > 1)
printf("{%d", element[0]); // Array is not empty, print the first element
else
printf("{"); // Empty array
// Since the first element have already been printed, start at the second
for (i = 1; i < size; i++) {
printf(",%d", element[i]);
}
printf("}");
I dare to suggest a logically readable code here.
for (i = 0; i < size; i++) {
printf("%d", element[i]);
if (i != size - 1)
printf(",");
}
By treating either the first (if you use prefix) or the last (if you use a suffix) element as a special case.
If you unroll #Someprogrammerdude's answer, say by printing 2 elements in each printf() for 1e8 elements (with value 0) they are are printed in ~4.055s with output redirected to /dev/null.
#Someprogrammerdude's answer original answer: 4.793s (1.182x).
#paddy's suggestion but more readable and flexible (with surprisingly a tiny performance edge over the original): 5.687s (1.402x).
const char *sep[] = {",", ""};
// ...
printf("%d%s", a[i], sep[i + 1 == LEN]);
My initial solution is 6.414s (1.582x):
printf("%d%s", a[i], i + 1 < SIZE ? "," : "");
Both of these benefit from just a single printf() statement while the faster solution require a 2nd conditional printf() either before or after the loop.

Why won't this array get printed?

I'm trying to write a program to take 10 words as input from the user, then store it an array, and then print out the length of each word.
Here's my code:
#include <stdio.h>
#include <string.h>
char *words[10];
char length[10];
int i, j;
int main()
{
printf("Input ten words: \n");
for(i = 0; i < 10; i++)
{
printf("Enter element %d \n", i + 1);
scanf("%s", &words[i]);
}
for(i = 0; i < 10; i++)
printf("%c", words[i]);
for(i = j = 0; j < 10; j++)
{
length[j] = strlen(words[i]);
i++;
}
for(j = 0; j < 10; j++)
printf("%c", length[j]);
return 0;
}
It should be noted that I have no idea why the array "words" is defined as a pointer, I only do it because if I don't I get some warning about making a pointer from integer without a cast.
When I run the program what happens is, I get prompted to input the 10 elements, that much works, but then when it's supposed to print the "words" array, the program just crashes.
Also the reason I coded it like this is because later on I also need to print the longest and shortest word - so I figured it would help if I had the lengths of all the strings in their own array.
Does anyone know what's wrong here?
Thanks
With the line char *words[10], you are declaring an array of 10 pointers. However, these pointers are uninitialized, which means they are wild pointers. Dereferencing a wild pointer causes undefined behavior (i.e. the program may crash). If you want to use these pointers in a meaningful way, you must make each pointer point to a valid memory location, for example to an address returned by the function malloc or to the address of a char array.
However, probably the easiest solution to your problem is to not use pointers at all, but to instead declare a two-dimensional char array, like this:
char words[10][100];
That way, you are allocating space for 10 words of up to 100 characters each (including the null terminating character).
Beware that a buffer overflow will occur if the user enters a word longer than 99 (1 byte is required for the terminating null character). Therefore, the scanf line should be changed to the following:
scanf("%99s", words[i]);
That way, scanf will never attempt to write more than 100 bytes (including the terminating null character).
I have also removed the & in the scanf line above, because the & is not necessary, since words[i] will automatically decay to &words[i][0].
Also, as a general rule, you should verify that the return value of scanf is 1 before attempting to use the value that scanf wrote. For example, if the user triggers end of file on the input stream (for example by pressing CTRL-D on Linux or CTRL-Z on Windows), then scanf will return -1 without writing anything into words[i]. In that case, by subsequently reading from words[i], your program will cause undefined behavior.
Additionally, the line
printf("%c", words[i]);
must be changed to:
printf("%s", words[i]);
The loop
for(i = j = 0; j < 10; j++)
{
length[j] = strlen(words[i]);
i++;
}
can be simplified to:
for(i = 0; i < 10; i++)
{
length[i] = strlen(words[i]);
}
The line
printf("%c", length[j]);
should probably be changed to
printf("%hhu", length[j]);
because length[j] does not represent the ASCII code of a character, but just a number.

I'm just trying to scan strings into an array. What am I doing wrong?

#include <stdio.h>
#include <string.h>
int main(void) {
const int NUM_VALS = 20;
int i;
int actualInput;
char userString[actualInput][NUM_VALS];
int matchCount = 0;
scanf("%d", &actualInput);
for (i = 0; i < actualInput; ++i) {
scanf("%s", userString[i]);
printf("%s", userString[i]);
}
return 0;
}
Output:
b'hellohi\x80\x07#\xd2\x05#\x9a\x16[\xea\xccp\xa6\x15\xf6\x18+\xbf\x87\x8a#\x14)\x05#\xfe\x7f'b'\x92\x1fk\xb3\xfe\x7f\xfe\x7f\x118\x08\xe8\x03\x0eY\x03k\xb3\xfe\x7f\xfe\x7f\xb2Y{\xe8C}8\r\x8b-u{\x8cx86_64'F-8sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin/usr/sbin:/usr/bin:/sbin:/binsbin:/binTF-88tf8RELOAD=/usr/lib/x86_64-linux-gnu/coreutils/libstdbuf.so64-linux-gnu/coreutils/libstdbuf.sols/libstdbuf.soout
I've tried some variations replacing userString[i] with userString in the scanf function. The result is outputting 50,000 inputs of my last string. I don't understand what's happening.
The problem is this sequence of code:
int actualInput;
char userString[actualInput][NUM_VALS];
int matchCount = 0;
scanf("%d", &actualInput);
The first line declares a variable called actualInput but doesn't assign a value to that variable.
The second line declares a variable length array (VLA) using the value in actualInput. Using the value of an uninitialized variable results in undefined behavior, which basically means that after that point in the code, anything can happen. What's likely happening (based on your description of the problem) is that actualInput is either zero, or a small number, so you get an array that's too small to hold your input.
The last line (with the scanf) finally assigns a value to actualInput. You may be thinking that the array will resize itself when actualInput is changed. That definitely does not happen. In C, after a VLA is created, its size cannot be changed.
The solution is simple, rearrange the code so that things are done in the proper order:
int actualInput;
scanf("%d", &actualInput);
char userString[actualInput][NUM_VALS];
int matchCount = 0;
As a side note, you should really do some error checking to make sure that the user inputs a reasonable number, before using that number to create an array. For example
int actualInput;
if (scanf("%d", &actualInput) != 1 || actualInput < 1 || actualInput > 1000)
{
printf("That is not a valid array size\n");
return 1;
}
char userString[actualInput][NUM_VALS];
you cant declare it as a 2D array then treat it as a normal array .
each case should include only one letter but it can't be done automatically , I suggest you add this :
for (i = 0; i < actualInput; ++i)
{
gets(stri);
for (k=0;k<strlen(stri);k++)
userString[i][j]=stri[j];
}

Why is my for loop running infinitly?

Entering the size of the array works. But the Enter integers for loop runs infinitely.
#include <stdio.h>
int main() {
int c, array[5], i;
printf("Enter the size of the array.");
scanf("%d", &c);
array[c];
printf("Enter the integers to fill the array.");
for (i = 0; i <= c; i++) {
scanf("%d", &array[i]);
}
for (i = 0; i <= c; i++) {
printf("%d", array[i]);
//if (array[0] >= array[i]) {
// ...
//}
}
return 0;
}
Your array is of a fixed size 5. The line array[c]; doesn't resize it. It's an array access (possibly an out of bounds access) and therefore your entire program has undefined behavior.
To define a VLA, you must move the array declaration after the call to scanf1:
int c;
printf("Enter the size of the array.");
scanf("%d",&c);
int array[c];
Then, make sure your loop condition is correct. In C array indices a 0-based, meaning we loop on the interval [0, c-1] and not [0, c].
for(int i = 0; i < c; ++i)
And as a final point of contention, notice how I moved all variable declaration to just before their initial use. Organizing your code like that (with a certain locality of data and execution) has a tendency to clarify what you write. So I strongly advise you to do this.
And be sure to check the return value of scanf. You do not want to define an array if the call to the library function failed.
array[c] refers to an element at 'c' position in array and doesn't do any fruitful job. Try removing that and check once.
In your for loop, you're reading and printing elements from 0 to c, which means you took c+1 elements instead of c elements. Make it : for(i=0;i<c;++i)

Search/print specific elements in array

Anyone know how to search (with luck) for specific elements in an array? I'v tried about everything - except the correct way.
My two corresponding char-arrays looks something like this:
char array1[10][10]={"Alpha","Bravo","Charlie","Delta","Alpha2"}; //room for some more here
char array2[10][10]={"123456","234567","345678","456789","567890"}; //room for some more here
I can print them all by the regular for-loop:
for (i=0;i<10;i++){
printf("%s %s \n", &array1[i], &array2[i]);
}
But let's say I want do the same loop, and only print the two elements starting with 'A' (the first and last one). I thought something like this would work
do {
for (i=0;i<10;i++){
printf("Name: %s\nDate: %s\n\n", &array1[i][x], &array2[i]);
}
} while (x=='A');
That's the same for-loop, except I put the extra [x] behind &array1 to tell my 'x' have to match the first character in each element of array1 (like it will only do the for loop while (x=='A') - which is the first letter in the elements I want.
But it doesn't do any good..
Anyone have a better solution? I've tried other variants of the for loop also, without luck. I'm just stuck now...
#include <stdio.h>
int main(void) {
char array1[10][10]={"Alpha","Bravo","Charlie","Delta","Alpha2"}; //room for some more here
char array2[10][10]={"123456","234567","345678","456789","567890"}; //room for some more here
int i;
for (i=0;i<10;i++){
if(array1[i][0]=='A') //add this statement in your code
printf("%s %s \n", &array1[i], &array2[i]);
}
return 0;
}
using while you are checking x=='A' it will compare with the ASCII value of A. The condition is wrong.
you can use
while((strncmp(array,"A",1)) == 0)
this will check the first character of the string.
except I put the extra [x] behind &array1 to tell my 'x' have to match the first character in each element of array1
That's not quite how array subscripts work. As you have found, array1[i] will refer to the ith string in array1. You can then access the xth character in array1[i] by indexing into the string, i.e. array1[i][x].
You don't actually assign x anywhere, so you'll end up with undefined behaviour. What you want to do is extract the first character of array1[i] (i.e. element zero), so the following is possible:
char x = '\0';
do {
for (i=0;i<10;i++){
x = array1[i][0];
printf("Name: %s\nDate: %s\n\n", &array1[i][x], &array2[i]);
}
} while (x=='A');
You'll then notice that this probably doesn't give the behaviour you want. It'll loop over all 10 strings, then perform the x == 'A' check. You should move that inside the loop instead, e.g.
char x = '\0';
for(i = 0; i < 10; i++)
{
x = array1[i][0];
if(x == 'A')
printf("%s %s \n", &array1[i], &array2[i]);
}

Resources